public void DbFunctionsTests_DiffMonths_DateTime_Test()
        {
            DateTime testDateTime2 = this.TestDateTime.AddMonths(1);
            var      result        = this.GetOrderQuery().Select(x => DbFunctions.DiffMonths(this.TestDateTime, testDateTime2)).First();

            Assert.AreEqual(-1, result);
        }
        /// <summary>
        /// 创建 <see cref="RecentPlayedPointList"/>
        /// </summary>
        /// <param name="currentUserId">当前登录用户 ID</param>
        /// <param name="dbContext"><see cref="KeylolDbContext"/></param>
        /// <param name="cachedData"><see cref="CachedDataProvider"/></param>
        /// <returns>Item1 表示 <see cref="RecentPlayedPointList"/>,Item2 表示第一个据点头部图</returns>
        public static async Task <Tuple <RecentPlayedPointList, string> > CreateAsync(string currentUserId,
                                                                                      KeylolDbContext dbContext, CachedDataProvider cachedData)
        {
            var queryResult = await(string.IsNullOrWhiteSpace(currentUserId)
                ? from point in dbContext.Points
                                    where DbFunctions.DiffMonths(point.CreateTime, DateTime.Now) <= 3 &&
                                    (point.Type == PointType.Game || point.Type == PointType.Hardware)
                                    orderby dbContext.Subscriptions
                                    .Count(s => s.TargetId == point.Id && s.TargetType == SubscriptionTargetType.Point) descending,
                                    point.LastActivityTime descending
                                    select new
            {
                point.Id,
                point.IdCode,
                point.HeaderImage,
                point.ThumbnailImage,
                point.ChineseName,
                point.EnglishName,
                TwoWeekPlayedTime = (double?)null
            }
                : from record in dbContext.UserSteamGameRecords
                                    where record.UserId == currentUserId
                                    join point in dbContext.Points on record.SteamAppId equals point.SteamAppId
                                    where !dbContext.Subscriptions.Any(s =>
                                                                       s.SubscriberId == currentUserId && s.TargetId == point.Id &&
                                                                       s.TargetType == SubscriptionTargetType.Point)
                                    orderby record.TwoWeekPlayedTime descending, record.LastPlayTime descending
                                    select new
            {
                point.Id,
                point.IdCode,
                point.HeaderImage,
                point.ThumbnailImage,
                point.ChineseName,
                point.EnglishName,
                TwoWeekPlayedTime = (double?)record.TwoWeekPlayedTime
            }
                                    ).Take(5).ToListAsync();
            var result = new RecentPlayedPointList(queryResult.Count);

            foreach (var p in queryResult)
            {
                result.Add(new RecentPlayedPoint
                {
                    Id                = p.Id,
                    IdCode            = p.IdCode,
                    ThumbnailImage    = p.ThumbnailImage,
                    ChineseName       = p.ChineseName,
                    EnglishName       = p.EnglishName,
                    AverageRating     = (await cachedData.Points.GetRatingsAsync(p.Id)).AverageRating,
                    TwoWeekPlayedTime = p.TwoWeekPlayedTime
                });
            }
            var firstRecord = queryResult.FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.HeaderImage));

            return(new Tuple <RecentPlayedPointList, string>(
                       result,
                       firstRecord?.HeaderImage));
        }
Пример #3
0
        public List <Despesa> ListarHistoricoPorCartao(int cartaoId, int ano, int mes)
        {
            Cartao              cartao           = _contexto.Set <Cartao>().SingleOrDefault(c => c.Id == cartaoId);
            DateTime            diaFechamentoMes = new DateTime(ano, mes, cartao.DiaFechamento);
            List <Parcelamento> parcelamentos    = _contexto.Set <Parcelamento>()
                                                   .Where(p => p.Cartao.Id == cartaoId &&
                                                          DbFunctions.DiffMonths(p.DataCompra, diaFechamentoMes) >= 0 &&
                                                          DbFunctions.DiffMonths(p.DataCompra, diaFechamentoMes) <= p.NumParcelas)
                                                   .ToList();
            List <Despesa> despesas = parcelamentos.Cast <Despesa>().ToList();

            return(despesas);
        }
        public IQueryable <CurrencyRateByTime> GetAllActual()
        {
            var allRates = _currencyRateByTimeRepository.GetAll();
            var span     = new TimeSpan(4, 0, 0).TotalHours;
            var now      = DateTime.UtcNow;
            var result   = allRates.Where(x =>
                                          DbFunctions.DiffMonths(now, x.DateTime) == 0 &&
                                          DbFunctions.DiffYears(now, x.DateTime) == 0 &&
                                          DbFunctions.DiffDays(now, x.DateTime) == 0 &&
                                          DbFunctions.DiffHours(x.DateTime, now) < span);

            return(result);
        }
        public void DateFunctions()
        {
            using (var context = new BloggingContext(ConnectionString))
            {
                IQueryable <int> oneRow = context.Posts.Where(p => false).Select(p => 1).Concat(new int[] { 1 });

                var dateAdds = oneRow.Select(p => new List <DateTime?>
                {
                    DbFunctions.AddDays(new DateTime(2014, 2, 28), 1),
                    DbFunctions.AddHours(new DateTime(2014, 2, 28, 23, 0, 0), 1),
                    DbFunctions.AddMinutes(new DateTime(2014, 2, 28, 23, 59, 0), 1),
                    DbFunctions.AddSeconds(new DateTime(2014, 2, 28, 23, 59, 59), 1),
                    DbFunctions.AddMilliseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 2 - p),
                    DbFunctions.AddMicroseconds(DbFunctions.AddMicroseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 500), 500),
                    DbFunctions.AddNanoseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 999999 + p),
                    DbFunctions.AddMonths(new DateTime(2014, 2, 1), 1),
                    DbFunctions.AddYears(new DateTime(2013, 3, 1), 1)
                }).First();
                foreach (var result in dateAdds)
                {
                    Assert.IsTrue(result.Value == new DateTime(2014, 3, 1, 0, 0, 0));
                }

                var dateDiffs = oneRow.Select(p => new {
                    a = DbFunctions.DiffDays(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    b = DbFunctions.DiffHours(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    c = DbFunctions.DiffMinutes(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    d = DbFunctions.DiffSeconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    e = DbFunctions.DiffMilliseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    f = DbFunctions.DiffMicroseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    g = DbFunctions.DiffNanoseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    h = DbFunctions.DiffMonths(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(3000, 1, 1, 0, 0, 0)),
                    i = DbFunctions.DiffYears(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(3000, 1, 1, 0, 0, 0)),
                    j = DbFunctions.DiffYears(null, new DateTime(2000, 1, 1)),
                    k = DbFunctions.DiffMinutes(new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6)),
                    l = DbFunctions.DiffMinutes(new TimeSpan(1, 2, 3), null)
                }).First();
                Assert.AreEqual(dateDiffs.a, 1);
                Assert.AreEqual(dateDiffs.b, 1);
                Assert.AreEqual(dateDiffs.c, 1);
                Assert.AreEqual(dateDiffs.d, 1);
                Assert.AreEqual(dateDiffs.e, 1);
                Assert.AreEqual(dateDiffs.f, 1000);
                Assert.AreEqual(dateDiffs.g, 1000000);
                Assert.AreEqual(dateDiffs.h, 12001);
                Assert.AreEqual(dateDiffs.i, 1001);
                Assert.AreEqual(dateDiffs.j, null);
                Assert.AreEqual(dateDiffs.k, 183);
                Assert.AreEqual(dateDiffs.l, null);
            }
        }
Пример #6
0
        /// <summary>
        /// 查询的数据在这个月内的阅读量排行榜最高的最新攻略
        /// </summary>
        /// <returns></returns>
        public List <RaidersViewModel> GetNewestRaiders()
        {
            int    rec   = (short)Reccommend.RecIndex;
            string t     = rec.ToString();
            int    state = (short)CheckState.Pass;
            string pass  = state.ToString();

            return(dbSession.UserRaidersDal.LoadEntities(r => r.State == pass)
                   //查询的数据在这个月内的阅读量排行榜最高的
                   .Where(n => DbFunctions.DiffMonths(n.InTime, DateTime.Now) <= 30).AsNoTracking()
                   .OrderByDescending(n => n.Views).Take(10).Select(r => new RaidersViewModel {
                Title = r.Title, EditTitle = r.EditTitle, Id = r.Id
            }).ToList());
        }
        public int Add(IFlight entity)
        {
            int id = RepositoryMethods.Add <Flight>(this.context,
                                                    (Flight)entity,
                                                    x => DbFunctions.DiffYears(x.SheduledTime, entity.SheduledTime) == 0 &&
                                                    DbFunctions.DiffMonths(x.SheduledTime, entity.SheduledTime) == 0 &&
                                                    DbFunctions.DiffDays(x.SheduledTime, entity.SheduledTime) == 0 &&
                                                    DbFunctions.DiffHours(x.SheduledTime, entity.SheduledTime) == 0 &&
                                                    DbFunctions.DiffMinutes(x.SheduledTime, entity.SheduledTime) == 0 &&
                                                    x.DestinationAirportId == entity.DestinationAirportId &&
                                                    x.FlightTypeId == entity.FlightTypeId);

            return(id);
        }
Пример #8
0
        /// <summary>
        /// 根据浏览量的高低查询最近一个月的新闻数据
        /// </summary>
        /// <returns></returns>
        public List <NewsViewModel> InLikeNumNews()
        {
            var data = dbSession.NewsDal.LoadEntities(n => DbFunctions.DiffMonths(n.InTime, DateTime.Now) <= 30 && n.State == "1").Select(n => new NewsViewModel()
            {
                Id        = n.Id,
                EditTitle = n.EditTitle,
                Views     = n.Views,
                Msg       = n.Msg,
                InTime    = n.InTime,
                Title     = n.Title,
                Type      = n.Type
            }).AsNoTracking().OrderByDescending(n => n.Views).Take(10).ToList();

            return(data);
        }
        public void DateTimeDiffMonths()
        {
            DateTime date = stored.AddYears(-1).AddMonths(-1);

#if !EFOLD
            var q = this.Entities
                    .Select(x =>
                            DbFunctions.DiffMonths(date, x.DateTime) == 13);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.DiffMonths(date, x.DateTime) == 13);
#endif

            q.Should().NotBeEmpty();
        }
Пример #10
0
        public List <ItemIndexViewModel> Handle(WalletIndexViewModel message)
        {
            var userId = message.UserId;
            // var wallet = walletRepo.Get(x => x.UserId == userId && x.Items.Any(i => DbFunctions.DiffMonths(DateTime.Now, i.Time) == 0), x => x.Items);
            var items = (from i in itemRepo.All.Where(x => DbFunctions.DiffMonths(DateTime.Now, x.Time) == 0)
                         join w in walletRepo.All.Where(x => x.UserId == x.UserId) on i.WalletId equals w.Id
                         orderby i.Time descending
                         select i).ToList();


            if (items == null)
            {
                return(new List <ItemIndexViewModel>());
            }

            return(MapperConfig.Factory.Map <List <Item>, List <ItemIndexViewModel> >(items));
        }
Пример #11
0
        protected MonthRanking GetMonthRankingInner(int year, int month)
        {
            var thisMonth = new DateTime(year, month, 1);
            var monthEndDate = thisMonth.AddMonths(1).AddDays(-1);
            var model = new MonthRanking();
            var currentMonthData = _db.HistoryRankings.Where(h => DbFunctions.DiffMonths(h.RankDate, thisMonth) == 0 && DbFunctions.DiffYears(h.RankDate, thisMonth) == 0)
                .Select(h => new { HistoryRanking = h, PostCount = _db.Posts.Count(p => p.ItemId == h.BlogID && p.IdType == ItemType.Blog), Deleted = !_db.Blogs.Any(b => b.BlogID == h.BlogID) })
                .ToList();
            var name2nick = _blogUtil.GetNickNames(currentMonthData.Select(r => r.HistoryRanking.Author));
            var currentMonthRankingData = currentMonthData.Select(h => new RankingDisplay
            {
                Author = name2nick[h.HistoryRanking.Author],
                BlogDate = h.HistoryRanking.BlogDate,
                BlogID = h.HistoryRanking.BlogID,
                BlogThumb = h.HistoryRanking.BlogThumb,
                BlogTitle = h.HistoryRanking.BlogTitle,
                BlogVisit = h.HistoryRanking.BlogVisit,
                BlogUrl = Url.Action("Details", "Blog", new { id = h.HistoryRanking.BlogID }),
                RankDate = h.HistoryRanking.RankDate,
                Rating = h.HistoryRanking.Rating,
                PostCount = h.PostCount,
                RankType = h.HistoryRanking.RankType,
                Deleted = h.Deleted,
            });

            var dailyRanking = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankDaily).ToList();
            if (year == DateTime.Today.Year && month == DateTime.Today.Month)
            {
                var dayFromMonday = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
                if (dayFromMonday < 0)
                    dayFromMonday += 7;
                monthEndDate = DateTime.Today.AddDays(-dayFromMonday);
                // If don't have today's ranking, read from 24h
                if (!dailyRanking.Any(h => h.RankDate.Date == DateTime.Today))
                {
                    dailyRanking.AddRange(currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.Rank24h));
                }
            }
            model.MonthlyRankings = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankMonthly).ToList();
            model.DailyRankings = dailyRanking;
            model.WeeklyRankings = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankWeekly && d.RankDate < monthEndDate).ToList();
            return model;
        }
Пример #12
0
        public void Execute()
        {
            var surveyCompletions = this.modelContext
                                    .SurveyCompletionParent
                                    .Include("Company")
                                    .Include("Role")
                                    .Where(x =>
                                           x.Role.Name == "OFERTA" &&
                                           x.PartialSave == false &&
                                           x.DeletedAt == null &&
                                           x.Status == "Aprobado" &&
                                           (
                                               (x.UpdateReminderSentAt == null && DbFunctions.DiffMonths(x.CreatedAt, DateTime.Now) >= 6) ||
                                               (x.UpdateReminderSentAt != null && DbFunctions.DiffMonths(x.UpdateReminderSentAt, DateTime.Now) >= 6))
                                           )
                                    .Take(20)
                                    .ToList();

            var existingCategories = this.modelContext
                                     .Categories
                                     .Select(x => x.Id)
                                     .ToList();

            foreach (var surveyCompletionParent in surveyCompletions)
            {
                try
                {
                    if (existingCategories.Contains(surveyCompletionParent.Category.Id))
                    {
                        var PdfName = this.pdfService.GetEvaluationFileName(surveyCompletionParent.Id);
                        this.supplyUpdateRegistrationReminderEmailService.Send(PdfName, surveyCompletionParent);
                    }
                }
                catch (Exception e)
                {
                }
                finally
                {
                    surveyCompletionParent.UpdateReminderSentAt = DateTime.Now;
                    this.modelContext.SaveChanges();
                }
            }
        }
Пример #13
0
        public static void FillMonth(int year, int month)
        {
            DateTime firstday = new DateTime(year, month, 1);
            DateTime lastDay  = new DateTime(firstday.Year, firstday.Month, DateTime.DaysInMonth(firstday.Year, firstday.Month));
            var      factory  = new BlogContextFactory();

            using (var db = factory.Create())
            {
                var oldRankings = db.HistoryRankings.Where(h => h.RankType == HistoryRanking.Type.RankMonthly && DbFunctions.DiffMonths(lastDay, h.RankDate) == 0).ToList();
                db.HistoryRankings.RemoveRange(oldRankings);
                var rankings = db.BlogRatings.Where(r => DbFunctions.DiffMonths(firstday, r.ratetime) == 0).GroupBy(r => r.BlogID)
                               .Select(g => new { blogId = g.Key, rating = g.Sum(r => r.value) })
                               .Join(
                    db.Blogs.Where(b => b.isApproved == true && !(new[] { 11, 12 }).Contains(b.CategoryID)),
                    a => a.blogId,
                    b => b.BlogID,
                    (a, b) =>
                    new
                {
                    blog = b,
                    a.rating,
                    postCount = db.Posts.Count(p => p.IdType == ItemType.Blog && p.ItemId == b.BlogID)
                }
                    ).OrderByDescending(r => r.rating)
                               .ThenByDescending(r => r.blog.BlogDate)
                               .Take(5)
                               .ToList().Select(r => new HistoryRanking
                {
                    Author    = r.blog.Author,
                    BlogDate  = r.blog.BlogDate,
                    BlogID    = r.blog.BlogID,
                    BlogThumb = firstImgPath(r.blog),
                    BlogTitle = r.blog.BlogTitle,
                    BlogVisit = r.blog.BlogVisit,
                    PostCount = r.postCount,
                    Rating    = r.rating,
                    RankType  = HistoryRanking.Type.RankMonthly,
                    RankDate  = lastDay,
                });
                db.HistoryRankings.AddRange(rankings);
                db.SaveChanges();
            }
        }
Пример #14
0
 /// <summary>
 /// 积分记录  http://192.168.1.223/GR_User/RecordList
 /// </summary>
 /// <param name="type">1 最近7天,2最近30天,3本月</param>
 /// <param name="times">开始日期</param>
 /// <param name="timee">结束日期</param>
 /// <param name="pagesize">条数</param>
 /// <param name="pageindex">页码</param>
 /// <returns></returns>
 public string RecordList(int type, DateTime times, DateTime timee, int pagesize = 10, int pageindex = 1)
 {
     timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
     using (var db = new shhouseEntities())
     {
         try
         {
             var user_score_wuxi = new List <user_score_wuxi>();
             var count           = 0;
             if (type == 1)
             {
                 user_score_wuxi = db.user_score_wuxi.Where(p => DbFunctions.DiffDays(p.addtime, DateTime.Now) <= 7 && p.userid == User.userid).OrderByDescending(p => p.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList();
                 count           = db.user_score_wuxi.Where(p => DbFunctions.DiffDays(p.addtime, DateTime.Now) <= 7 && p.userid == User.userid).Count();
             }
             else if (type == 2)
             {
                 user_score_wuxi = db.user_score_wuxi.Where(p => DbFunctions.DiffDays(p.addtime, DateTime.Now) <= 30 && p.userid == User.userid).OrderByDescending(p => p.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList();
                 count           = db.user_score_wuxi.Where(p => DbFunctions.DiffDays(p.addtime, DateTime.Now) <= 30 && p.userid == User.userid).Count();
             }
             else if (type == 3)
             {
                 user_score_wuxi = db.user_score_wuxi.Where(p => DbFunctions.DiffMonths(p.addtime, DateTime.Now) == 0 && p.userid == User.userid).OrderByDescending(p => p.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList();
                 count           = db.user_score_wuxi.Where(p => DbFunctions.DiffMonths(p.addtime, DateTime.Now) == 0 && p.userid == User.userid).Count();
             }
             else
             {
                 user_score_wuxi = db.user_score_wuxi.Where(p => p.userid == User.userid && (DbFunctions.TruncateTime(p.addtime) >= times.Date && DbFunctions.TruncateTime(p.addtime) <= timee.Date)).OrderByDescending(p => p.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList();
                 count           = db.user_score_wuxi.Where(p => p.userid == User.userid && (DbFunctions.TruncateTime(p.addtime) >= times.Date && DbFunctions.TruncateTime(p.addtime) <= timee.Date)).Count();
             }
             return(JsonConvert.SerializeObject(new repmsg {
                 state = 1, msg = "积分记录", data = new { userscore = user_score_wuxi, counts = count }
             }, timeFormat));
         }
         catch (Exception e)
         {
             return(JsonConvert.SerializeObject(new repmsg {
                 state = 2, msg = "暂无记录,请稍后再试!", data = null
             }));
         }
     }
 }
Пример #15
0
        public List <Despesa> ListarHistorico(string pessoaId, int ano, int mes)
        {
            DateTime inicioMes = new DateTime(ano, mes, 1);
            DateTime finalMes  = new DateTime(ano, mes, DateTime.DaysInMonth(ano, mes));

            List <SemParcelamento> semParcelamentos = _contexto.Set <SemParcelamento>()
                                                      .Where(p => p.Pessoa.Id == pessoaId && p.DataCompra > inicioMes && p.DataCompra < finalMes)
                                                      .ToList();

            List <Parcelamento> parcelamentos = _contexto.Set <Parcelamento>()
                                                .Where(p => p.Pessoa.Id == pessoaId &&
                                                       DbFunctions.DiffMonths(p.DataCompra, inicioMes) >= 0 &&
                                                       DbFunctions.DiffMonths(p.DataCompra, finalMes) < p.NumParcelas)
                                                .ToList();

            List <Despesa> despesas = new List <Despesa>(semParcelamentos);

            despesas.AddRange(parcelamentos);

            return(despesas.OrderBy(p => p.DataCompra).OrderByDescending(p => p.Valor).ToList());
        }
Пример #16
0
        Task IJob.Execute(IJobExecutionContext context)
        {
            List <Reservation> reservations = db.Reservations
                                              .Where(r => DbFunctions.DiffMonths(r.ProjectionStartDate, now) == 0 &&
                                                     DbFunctions.DiffDays(r.ProjectionStartDate, now) == 0)
                                              .ToList();

            foreach (var reserv in reservations)
            {
                if (reserv.ProjectionStartDate.AddMinutes(-10) < now)
                {
                    db.Reservations
                    .Where(r => r.Id == reserv.Id)
                    .ToList()
                    .ForEach(r => r.IsActive = false);
                }
            }

            db.SaveChanges();

            Task successMessage = new Task(() => Console.WriteLine("Some reservations deleted at {0}", DateTime.Now.ToString()));

            return(successMessage);
        }
Пример #17
0
        /// <summary>
        /// 获取客流数据
        /// </summary>
        /// <returns></returns>
        public ActionResult CustData()
        {
            try
            {
                using (DataWallContext db = new DataWallContext())
                {
                    var Cookies = SecurityHelper.DecryptDES(CookieHelper.GetCookieValue("Library"), db.SysProgramInfos.AsNoTracking().FirstOrDefault().CookieSecretKey);
                    if (Cookies != null)
                    {
                        SysLibrary           Library        = JsonConvert.DeserializeObject <SysLibrary>(Cookies);
                        List <SysCustDevice> SysCustDevices = db.SysCustDevices.Where(u => u.DelState == 0).AsNoTracking().ToList();
                        var query = from a in db.SysCustDevices
                                    join b in db.SysCustDatas
                                    on a.ID equals b.SysCustDeviceId
                                    where a.SysLibraryId == Library.ID
                                    select b;

                        //额外数据
                        var AdditionalData = from a in db.SysAdditionalDatas where a.SysLibraryId == Library.ID & a.IsEnable == 0 & a.Type == 0 select a;
                        int AllNumEw       = 0;
                        int LastMonthNumEw = 0;
                        int YesterdayNumEw = 0;
                        int ThisMonthNumEw = 0;
                        int TodayNumEw     = 0;
                        if (AdditionalData != null)
                        {
                            AllNumEw       = AdditionalData.Sum(d => (int?)d.PeopleNum) ?? 0;
                            LastMonthNumEw = AdditionalData.Where(s => DbFunctions.DiffMonths(s.DataDatetime, DateTime.Now) == -1).Sum(d => (int?)d.PeopleNum) ?? 0;
                            YesterdayNumEw = AdditionalData.Where(s => DbFunctions.DiffMonths(s.DataDatetime, DateTime.Now) == 0).Sum(d => (int?)d.PeopleNum) ?? 0;
                            ThisMonthNumEw = AdditionalData.Where(s => DbFunctions.DiffDays(s.DataDatetime, DateTime.Now) == -1).Sum(d => (int?)d.PeopleNum) ?? 0;
                            TodayNumEw     = AdditionalData.Where(s => DbFunctions.DiffDays(s.DataDatetime, DateTime.Now) == 0).Sum(d => (int?)d.PeopleNum) ?? 0;
                        }

                        var AllNum       = (query.Sum(d => (decimal?)d.D_InNum) ?? 0) + AllNumEw;
                        var LastMonthNum = (query.Where(d => DbFunctions.DiffMonths(d.D_Date, DateTime.Now) == -1).Sum(d => (decimal?)d.D_InNum) ?? 0) + LastMonthNumEw;
                        var ThisMonthNum = (query.Where(d => DbFunctions.DiffMonths(d.D_Date, DateTime.Now) == 0).Sum(d => (decimal?)d.D_InNum) ?? 0) + YesterdayNumEw;
                        var YesterdayNum = (query.Where(d => DbFunctions.DiffDays(d.D_Date, DateTime.Now) == -1).Sum(d => (decimal?)d.D_InNum) ?? 0) + ThisMonthNumEw;
                        var TodayNum     = (query.Where(d => DbFunctions.DiffDays(d.D_Date, DateTime.Now) == 0).Sum(d => (decimal?)d.D_InNum) ?? 0) + TodayNumEw;

                        return(Json(new
                        {
                            code = 201,
                            AllNum = AllNum,
                            LastMonthNum = LastMonthNum,
                            ThisMonthNum = ThisMonthNum,
                            YesterdayNum = YesterdayNum,
                            TodayNum
                        }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json(new
                        {
                            code = 202,
                            msg = "验证失败"
                        }, JsonRequestBehavior.AllowGet));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog(ex.Message);
                return(Json(new
                {
                    code = 202,
                    msg = "服务器错误"
                }, JsonRequestBehavior.AllowGet));
            }
        }
 public void DbFunctionsTests_DiffMonths_DateTimeOffset_Test()
 {
     this.AssertException <NotSupportedException>(() => {
         this.GetOrderQuery().Select(x => DbFunctions.DiffMonths(this.TestDateTimeOffset, this.TestDateTimeOffset)).First();
     });
 }
Пример #19
0
        public ActionResult History(int?year, int?month)
        {
            int y         = year ?? DateTime.Today.Year;
            int m         = month ?? DateTime.Today.Month;
            var minDate   = new DateTime(2019, 1, 25);
            var thisMonth = new DateTime(y, m, 1);

            if (thisMonth.Year < 2019 || thisMonth > DateTime.Today)
            {
                return(Json(Enumerable.Empty <PunchInHistory>()));
            }
            var user             = _udb.Users.SingleOrDefault(u => u.UserName == User.Identity.Name);
            var currentMonthData = _udb.PunchInHistories.Where(h => h.User.UserName == User.Identity.Name && DbFunctions.DiffMonths(h.TimeStamp, thisMonth) == 0 && DbFunctions.DiffYears(h.TimeStamp, thisMonth) == 0);
            var response         = new PunchInHistoryResponse {
                PunchIns = currentMonthData.Select(u => new PunchInHistoryResponse.PunchIn {
                    TimeStamp = u.TimeStamp, IsMakeUp = u.IsMakeup
                }).ToList(),
                MinSignDate = user.CreateDate > minDate ? user.CreateDate : minDate,
            };

            if (y == 2019 && m == 1)
            {
                response.LegacySignDays = user.HistoryConsecutiveSign;
            }
            return(Json(response));
        }
Пример #20
0
 private void MonthlyRewardTask()
 {
     using (var scope = _scopeFactory.CreateScope())
     {
         var db = scope.ServiceProvider.GetRequiredService <BlogContext>();
         // today should be first day of new month
         DateTime firstday = DateTime.Today.AddMonths(-1);
         DateTime lastDay  = new DateTime(firstday.Year, firstday.Month, DateTime.DaysInMonth(firstday.Year, firstday.Month));
         var      rankings = GetRankingSinceDate(db, firstday, lastDay, HistoryRanking.Type.RankMonthly);
         db.HistoryRankings.RemoveRange(db.HistoryRankings.Where(h => h.RankType == HistoryRanking.Type.RankMonthly && DbFunctions.DiffMonths(h.RankDate, firstday) == 0));
         db.HistoryRankings.AddRange(rankings);
         db.SaveChanges();
         // Remove any key at rankdate as we just updated.
         IDictionary <DateTime, MonthRanking> cache = _cache.Get <System.Collections.Concurrent.ConcurrentDictionary <DateTime, MonthRanking> >("~MonthRanking");
         if (cache != null && cache.ContainsKey(firstday))
         {
             cache.Remove(firstday);
         }
         ExpUtil expUtil = scope.ServiceProvider.GetService <ExpUtil>();
         expUtil.addRankExp(rankings, MonthlyReward, "月榜奖励");
     }
 }
Пример #21
0
        private void RankingScheduler()
        {
            Action timertask = new Action(() =>
            {
                _logger.LogInformation("Starting Ranking Scheduler!");
                using (var scope = _scopeFactory.CreateScope())
                {
                    var db         = scope.ServiceProvider.GetRequiredService <BlogContext>();
                    var sincemonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                    if (DateTime.Today.Day != 1) // Show last month on day 1
                    {
                        var ranking1month = GetRankingSinceDate(db, sincemonth, DateTime.Today, HistoryRanking.Type.RankMonthly);
                        db.HistoryRankings.RemoveRange(db.HistoryRankings.Where(h => h.RankType == HistoryRanking.Type.RankMonthly && DbFunctions.DiffMonths(h.RankDate, sincemonth) == 0));
                        db.HistoryRankings.AddRange(ranking1month);
                    }

                    var rankings24h = db.Blogs.Where(b => !NoRankCategories.Contains(b.CategoryID) && DbFunctions.DiffMinutes(b.BlogDate, DateTime.Now) < 1440 && b.isApproved == true)
                                      .OrderByDescending(r => r.Rating)
                                      .ThenByDescending(r => r.BlogDate)
                                      .Take(RankSize)
                                      .Select(b => new
                    {
                        blog      = b,
                        rating    = b.Rating ?? 0,
                        postCount = db.Posts.Count(p => p.IdType == ItemType.Blog && p.ItemId == b.BlogID)
                    }).ToList()
                                      .Select(r => new HistoryRanking
                    {
                        Rating    = r.rating,
                        PostCount = r.postCount,
                        Author    = r.blog.Author,
                        BlogVisit = r.blog.BlogVisit,
                        BlogTitle = r.blog.BlogTitle,
                        BlogThumb = BlogHelper.firstImgPath(r.blog, true),
                        BlogID    = r.blog.BlogID,
                        BlogDate  = r.blog.BlogDate,
                        RankDate  = DateTime.Now,
                        RankType  = HistoryRanking.Type.Rank24h
                    });
                    db.HistoryRankings.RemoveRange(db.HistoryRankings.Where(h => h.RankType == HistoryRanking.Type.Rank24h));
                    db.HistoryRankings.AddRange(rankings24h);

                    var dayFromMonday = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
                    if (dayFromMonday < 0)
                    {
                        dayFromMonday += 7;
                    }
                    var firstday = DateTime.Today.AddDays(-dayFromMonday);
                    // remove this week's data.
                    db.HistoryRankings.RemoveRange(db.HistoryRankings.Where(h => h.RankType == HistoryRanking.Type.RankWeekly && firstday <= h.RankDate));
                    if (dayFromMonday == 0) //if today is monday reuse last week data.
                    {
                        var lastWeek = GetRankingSinceDate(db, firstday.AddDays(-7), DateTime.Today, HistoryRanking.Type.RankWeekly);
                        db.HistoryRankings.AddRange(lastWeek);
                    }
                    else
                    {
                        var rankings7d = GetRankingSinceDate(db, firstday, DateTime.Today, HistoryRanking.Type.RankWeekly);
                        db.HistoryRankings.AddRange(rankings7d);
                    }
                    db.SaveChanges();
                }
            });

            Schedule(timertask).WithName(RankingTask).ToRunEvery(UpdateInterval).Minutes();
        }
Пример #22
0
        public IEnumerable <LightOrder> GetAllLastMonthOrders()
        {
            var now = DateTime.Now;

            return(this.GetAllOrders(o => DbFunctions.DiffMonths(now, o.Date) == -1));
        }