public async Task <IHttpActionResult> DailyStatistics()
        {
            using (var context = this.DataAccess.GetContext())
            {
                var offset = DateTime.Now.AddHours(-24);
                var start  = new DateTime(offset.Year, offset.Month, offset.Day, offset.Hour, 0, 0);
                var result = await context.NoTracking <DAL.Entities.QueryExecution>()
                             .Where(e => e.Start >= start)
                             .GroupBy(e => DbFunctions.DiffHours(start, e.Start))
                             .Select(g => new
                {
                    Hours      = g.Key,
                    Total      = g.Count(),
                    Successful = g.Count(e => e.Successful),
                    Failed     = g.Count(e => !e.Successful)
                })
                             .Select(x => new
                {
                    Hour       = DbFunctions.AddHours(start, x.Hours),
                    Total      = x.Total,
                    Successful = x.Successful,
                    Failed     = x.Failed
                })
                             .OrderBy(x => x.Hour)
                             .ToListAsync();

                return(this.Ok(result));
            }
        }
        public bool ValidateAppointment(DateTime apptDate, int id)
        {
            var isAvailable = _db.Appointments.Any(m => DbFunctions.DiffHours(m.StartDateTime, apptDate) == 1 ||
                                                   DbFunctions.DiffHours(DbFunctions.AddHours(m.StartDateTime, -1), apptDate) == 1 ||
                                                   m.StartDateTime == apptDate && m.DoctorId == id && m.DStatus == true);

            return(isAvailable);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var latestBooks = this.Data.Books.All()
                              .Where(b => DbFunctions.AddHours(DateTime.Now, -1) < b.DateAdded).ToList();


            this.LatestBooks.DataSource = latestBooks;
            this.LatestBooks.DataBind();
        }
        public void DbFunctionsTests_AddHours_DateTime_Test()
        {
            var result = this.GetOrderQuery().Select(x => (DateTime)DbFunctions.AddHours(this.TestDateTime, 1)).First();

            Assert.AreEqual(YEAR, result.Year);
            Assert.AreEqual(MONTH, result.Month);
            Assert.AreEqual(DAY, result.Day);
            Assert.AreEqual(HOUR + 1, result.Hour);
            Assert.AreEqual(MINUTE, result.Minute);
            Assert.AreEqual(SECOND, result.Second);
        }
        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);
            }
        }
        public ChartData CreateChartData(ISendSMSHostContext db, bool includeDeleted)
        {
            List <DateTime> hourList = new List <DateTime>();

            for (int i = 0; i < (24 / INTERVAL_HOURS); i++)
            {
                hourList.Add(DateTime.Today.AddHours(i * INTERVAL_HOURS));
            }

            var lastLogs = db.Log
                           .Where(x => x.Timestamp >= hourList.Min())
                           .GroupBy(x => x.SmsId)
                           .Select(y => y.OrderByDescending(z => z.Timestamp).FirstOrDefault());

            if (!includeDeleted)
            {
                lastLogs = lastLogs.Where(z => z.Operation != "DELETE");
            }
            ;

            var data = db.Status
                       .Select(s => new
            {
                Label = s.Name,
                Data  = hourList
                        .OrderBy(dt => dt)
                        .Select(h => lastLogs.Count(x => h <= x.Timestamp &&
                                                    x.Timestamp < DbFunctions.AddHours(h, INTERVAL_HOURS) &&
                                                    x.StatusName == s.Name)),
                BackgroundColor = s.DefaultColorHex
            })
                       .AsEnumerable()
                       .Select(d => new DataSet
            {
                Label           = d.Label,
                Data            = d.Data.ToArray(),
                BackgroundColor = d.BackgroundColor,
                BorderColor     = Constants.BORDER_COLOR,
                BorderWidth     = Constants.BORDER_WIDTH
            })
                       .ToArray();

            ChartData chartData = new ChartData
            {
                Labels   = hourList.Select(d => d.ToString("HH:mm")).ToArray(),
                Datasets = data
            };

            return(chartData);
        }
Exemple #7
0
        public void DateTimeOffsetAddHours()
        {
            DateTimeOffset offset = stored.AddHours(-1);

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddHours(x.Offset, -1) == offset);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddHours(x.Offset, -1) == offset);
#endif

            q.Should().NotBeEmpty();
        }
        public void TimeAddHours()
        {
            TimeSpan time = stored.Add(TimeSpan.FromHours(-1));

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddHours(x.Time, -1) == time);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddHours(x.Time, -1) == time);
#endif

            q.Should().NotBeEmpty();
        }
        /// <summary>
        /// Clean all connections
        /// </summary>
        internal void SwipeOldConnections()
        {
            using (PasswordKeeperEntities context = new PasswordKeeperEntities())
            {
                // Delete any previous row older than an hour
                List <ConnectionTemp> existingConnections = (from conn in context.ConnectionTemps
                                                             where DbFunctions.AddHours(conn.ConnexionDate, 1) < DateTime.Now
                                                             select conn).ToList();

                if (existingConnections.Count > 0)
                {
                    context.ConnectionTemps.RemoveRange(existingConnections);
                    context.SaveChanges();
                }
            }
        }
        public void DateTimeAddHours()
        {
            DateTime date = stored.AddHours(-1);

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddHours(x.DateTime, -1) == date);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddHours(x.DateTime, -1) == date);
#endif

            q.Should().NotBeEmpty();
        }
        public Tuple <int, List <TraceViewModel> > GetTraces(TraceSearchRequest request)
        {
            // get logs newer than 7 days
            var nowUtc = _now.UtcNow;

            var traces =
                _context.AsQueryable <Trace>()
                .Where(x => DbFunctions.AddHours(x.RequestTimestamp, LogLimit) > nowUtc)
                .AsQueryable();

            IOrderedQueryable <Trace> pagedTraces;

            if (!string.IsNullOrEmpty(request.Search))
            {
                var searchLikeExpression = $"%{request.Search}%";
                Expression <Func <Trace, bool> > searchExpression =
                    entry => SqlFunctions.PatIndex(searchLikeExpression, entry.Url) > 0 ||
                    SqlFunctions.PatIndex(searchLikeExpression, entry.RequestPayload) > 0 ||
                    SqlFunctions.PatIndex(searchLikeExpression, entry.ResponsePayload) > 0;
                traces = traces.Where(searchExpression).AsQueryable();
            }

            switch (request.Order)
            {
            case LogsSortAscendingKey:
                pagedTraces = traces.OrderAscending(request.Sort);
                break;

            case LogsSortDescendingKey:
                pagedTraces = traces.OrderDescending(request.Sort);
                break;

            default:
                pagedTraces = traces.OrderDescending(request.Sort);
                break;
            }

            var totalTraces     = pagedTraces.Count();
            var pagedTracesList = pagedTraces
                                  .Skip(request.Offset / request.Limit * request.Limit).Take(request.Limit).ToList();

            return(new Tuple <int, List <TraceViewModel> >(totalTraces, _mapper.Map <List <TraceViewModel> >(pagedTracesList)));
        }
Exemple #12
0
        static Dictionary <DateTime, decimal> GetRevenueDataPastDay(Item item)
        {
            Dictionary <DateTime, decimal> revenueDataPoints = new Dictionary <DateTime, decimal>();
            var now = DateTime.Now;

            //first dp
            revenueDataPoints.Add(now.AddDays(-1), 0);

            //create other dps
            decimal total = 0;

            using (var dbContext = new InventoryContext())
            {
                //every 5 mins
                for (int hour = 1; hour < 25; hour = hour + 2)
                {
                    total = 0;
                    var validItemTransactions = from i_t in dbContext.ItemTransactions
                                                where i_t.Transaction.TimeOfTransaction >= DbFunctions.AddHours(now, (-1) * hour) &&
                                                i_t.Transaction.TimeOfTransaction < DbFunctions.AddHours(now, ((-1) * hour) + 2) &&
                                                i_t.ItemID == item.ItemID
                                                select i_t;

                    if (validItemTransactions != null)
                    {
                        //find total for transactions
                        foreach (ItemTransaction itemTransaction in validItemTransactions)
                        {
                            total += itemTransaction.Quantity * itemTransaction.Item.RRP;
                        }
                    }
                    else
                    {
                        total = 0;
                    }

                    revenueDataPoints.Add(now.AddHours((-1) * hour), total);
                }
            }
            return(revenueDataPoints);
        }
        public Dictionary <int, Table> GetAllFreeTablesForRestaurant(ReservationParameters resParameters)
        {
            IEnumerable <Table> tablesForRes = GetAllTablesForRestaurant(resParameters.Id);
            var result = from reservation in RestaurantModelContext.Reservations
                         join restable in RestaurantModelContext.Resevated_tables
                         on reservation.RE_ID equals restable.RE_ID
                         where
                         reservation.ID.Equals(resParameters.Id) &&
                         (reservation.RE_DATE < DbFunctions.AddHours(resParameters.ReservationTime, resParameters.Duration)) &&
                         (DbFunctions.AddHours(reservation.RE_DATE, reservation.RE_LENGTH) > resParameters.ReservationTime)
                         select new { restable.ID };

            Dictionary <int, Table> tablesForResponse = tablesForRes.ToDictionary(table => table.ID, table => table);

            foreach (var element in result.ToList())
            {
                if (tablesForResponse.ContainsKey(element.ID))
                {
                    tablesForResponse.Remove(element.ID);
                }
            }

            return(tablesForResponse);
        }
Exemple #14
0
        /// <summary>
        /// Sends notifications for all expiring and expired asset reservations.
        /// </summary>
        /// <param name="expirationNotifier">The <see cref="ExpirationNotifier" />.</param>
        public void SendExpirationNotifications(ExpirationNotifier expirationNotifier)
        {
            using (AssetInventoryContext context = new AssetInventoryContext(_connectionString))
            {
                List <AssetReservation> reservations = context.AssetReservations.Where(n => n.End < DbFunctions.AddHours(DateTime.Now, 24)).ToList();
                LogDebug($"Found {reservations.Count} expiring or expired reservations.");

                foreach (AssetReservation reservation in reservations.Where(n => n.NotificationRecipient != null))
                {
                    SendExpirationNotification(expirationNotifier, reservation);
                }

                LogDebug("Finished processing asset reservation notifications.");
            }
        }
        public SearchNotificationsResult SearchNotifications(SearchNotificationCriteria criteria)
        {
            var retVal = new SearchNotificationsResult();

            using (var repository = _repositoryFactory())
            {
                retVal.Notifications = new List <Core.Notifications.Notification>();

                var query = repository.Notifications;

                if (!string.IsNullOrEmpty(criteria.ObjectId))
                {
                    query = query.Where(n => n.ObjectId == criteria.ObjectId);
                }
                if (!string.IsNullOrEmpty(criteria.ObjectTypeId))
                {
                    query = query.Where(n => n.ObjectTypeId == criteria.ObjectTypeId);
                }

                if (criteria.IsActive)
                {
                    query = query.Where(n => n.IsActive && n.SentDate == null && (n.LastFailAttemptDate == null || DbFunctions.AddHours(n.LastFailAttemptDate, criteria.RepeatHoursIntervalForFail) < DateTime.UtcNow) &&
                                        (n.StartSendingDate == null || n.StartSendingDate < DateTime.UtcNow));
                }
                retVal.TotalCount = query.Count();

                var sortInfos = criteria.SortInfos;
                if (sortInfos.IsNullOrEmpty())
                {
                    sortInfos = new[] { new SortInfo {
                                            SortColumn = "CreatedDate", SortDirection = SortDirection.Descending
                                        } };
                }
                query = query.OrderBySortInfos(sortInfos);

                retVal.Notifications = query.Skip(criteria.Skip)
                                       .Take(criteria.Take)
                                       .ToArray()
                                       .Select(x => GetNotificationCoreModel(x))
                                       .ToList();
            }

            return(retVal);
        }
 public void DbFunctionsTests_AddHours_DateTimeOffset_Test()
 {
     this.AssertException <NotSupportedException>(() => {
         this.GetOrderQuery().Select(x => DbFunctions.AddHours(this.TestDateTimeOffset, 1)).First();
     });
 }
Exemple #17
0
        private async Task ProcessTransactions()
        {
            Log.Message(LogLevel.Info, "[ProcessNZDT] - Processing NZDT Transactions...");

            List <NzdtTransaction> nzdtTransactions;

            using (var context = ExchangeDataContextFactory.CreateContext())
            {
                nzdtTransactions = await context.NzdtTransaction
                                   .Where(x => x.TransactionStatus == NzdtTransactionStatus.ReadyForProcessing)
                                   .Where(x => DbFunctions.AddHours(x.CreatedOn, 1) <= DateTime.UtcNow)
                                   .ToListNoLockAsync();

                Log.Message(LogLevel.Info, $"[ProcessNZDT] - {nzdtTransactions.Count()} transactions found, processing...");

                foreach (var transaction in nzdtTransactions)
                {
                    transaction.TransactionStatus = NzdtTransactionStatus.Processed;
                }

                await context.SaveChangesAsync();
            }

            var wallet = new WalletConnector(_nzdtAssetWalletIp, _nzdtAssetWalletPort, _nzdtAssetWalletUserName, _nzdtAssetWalletPassword, 30000);

            foreach (var transaction in nzdtTransactions)
            {
                try
                {
                    var sendResult = await wallet.SendToAddressAsync(Constant.NzdtBaseExchangeAddress, transaction.Amount);

                    using (var context = ExchangeDataContextFactory.CreateContext())
                    {
                        var deposit = new Deposit
                        {
                            Txid          = string.IsNullOrEmpty(sendResult?.Txid) ? $"{transaction.Id}" : sendResult.Txid,
                            Amount        = transaction.Amount,
                            TimeStamp     = DateTime.UtcNow,
                            CurrencyId    = Constant.NZDT_ID,
                            Status        = DepositStatus.Confirmed,
                            Confirmations = 20,
                            UserId        = transaction.UserId.Value,
                            Type          = DepositType.Normal
                        };

                        var tx = await context.NzdtTransaction.FirstNoLockAsync(x => x.Id == transaction.Id);

                        tx.Deposit = deposit;

                        await context.SaveChangesAsync();

                        await context.AuditUserBalance(transaction.UserId.Value, Constant.NZDT_ID);

                        await context.SaveChangesAsync();
                    }
                }
                catch (Exception ex)
                {
                    Log.Exception($"[ProcessNZDT] Insert Deposit failed for transaction {transaction.Id}", ex);
                }
            }

            Log.Message(LogLevel.Info, $"[ProcessNZDT] - Processing NZDT Transactions complete.");
        }
        /**
         * Get all the played matches for every leagues
         */
        public async Task <List <ResultViewModel> > GetAll(MatchViewFilter filter)
        {
            var filteredMatchQuery = this.FilterMatchView(db.Matches, filter);

            // Getting all the played matches
            var matchQuery = getMatchResultViewModel(filteredMatchQuery);

            // Grouping the matches by local date
            int hourOffset = 0;

            if (filter != null && filter.HourOffset != null)
            {
                hourOffset = filter.HourOffset.Value;
            }

            var groupedMatches = matchQuery.GroupBy(m => DbFunctions.TruncateTime(DbFunctions.AddHours(m.Date, hourOffset))).ToList().Select(mq => mq).ToList();

            // we group by the league Id
            var leagueMatches = groupedMatches.Select(
                gm => gm.GroupBy(svg => svg.LeagueId)
                .Select(
                    lq => new LeagueResultViewModel
            {
                CountryId   = lq.FirstOrDefault().CountryId,
                CountryName = lq.FirstOrDefault().CountryName,
                SeasonId    = lq.FirstOrDefault().SeasonId,
                SeasonName  = lq.FirstOrDefault().SeasonName,
                Id          = lq.FirstOrDefault().LeagueId,
                Name        = lq.FirstOrDefault().LeagueName,
                Date        = lq.FirstOrDefault().Date,
                matches     = lq.ToList()
                              .OrderBy(mv => mv.homeTeamPlayer.PlayerName)
                              .ThenBy(mv => mv.homeTeamPlayer.TeamName)
                              .ThenBy(mv => mv.awayTeamPlayer.PlayerName)
                              .ThenBy(mv => mv.awayTeamPlayer.TeamName)
            }
                    )
                .OrderBy(l => l.Name).ToList()
                );

            // we group by the Season ID
            var seasonMatches = leagueMatches.Select(
                lm => lm.GroupBy(svg => svg.SeasonId)
                .Select(
                    lq => new SeasonResultViewModel
            {
                CountryId     = lq.FirstOrDefault().CountryId,
                CountryName   = lq.FirstOrDefault().CountryName,
                Id            = lq.FirstOrDefault().SeasonId,
                Name          = lq.FirstOrDefault().SeasonName,
                Date          = lq.FirstOrDefault().Date,
                leagueMatches = lq.ToList()
            }
                    )
                .OrderBy(l => l.Name).ToList()
                );


            // we group by the Country ID
            var countryMatches = seasonMatches.Select(
                sm => sm.GroupBy(svg => svg.CountryId)
                .Select(
                    lq => new CountryResultViewModel
            {
                Id            = lq.FirstOrDefault().CountryId,
                Name          = lq.FirstOrDefault().CountryName,
                Date          = lq.FirstOrDefault().Date,
                seasonMatches = lq.ToList()
            }
                    )
                .OrderBy(l => l.Name).ToList()
                );


            // Finnaly we group by the Date
            var resultView = countryMatches.Select(
                lq => new ResultViewModel
            {
                Date           = lq.FirstOrDefault().Date,
                countryMatches = lq.ToList()
            }
                )
                             .OrderByDescending(l => l.Date).ToList();

            return(await this.ReturnResult(resultView, filter));
        }
        public List <EmployeeAttendanceModel> GetAttendanceForRange(Int64 UserID, DateTime FromDateTime, DateTime ToDateTime, string requestLevelPerson, bool isDirectEmployees, bool getBreakStatus)
        {
            List <EmployeeAttendanceModel> employeeAttendanceModelList = new List <EmployeeAttendanceModel>();
            EmployeeDac   employeeDac = new EmployeeDac();
            IList <Int64> employeeIDs = new List <Int64>();

            if (requestLevelPerson.ToUpper() == "MY")
            {
                employeeIDs.Add(UserID);
            }
            else
            {
                if (isDirectEmployees)
                {
                    employeeIDs = employeeDac.GetDirectEmployees(UserID);
                }
                else
                {
                    employeeIDs = employeeDac.GetEmployeesReporting(UserID);
                }
            }

            using (var context = new NLTDDbContext())
            {
                employeeAttendanceModelList = (from ea in context.EmployeeAttendance
                                               join e in context.Employee on ea.UserID equals e.UserId
                                               join s in context.ShiftMapping on e.UserId equals s.UserID
                                               join sm in context.ShiftMaster on s.ShiftID equals sm.ShiftID
                                               where employeeIDs.Contains(ea.UserID ?? 0) && ea.InOutDate >= FromDateTime && ea.InOutDate <= ToDateTime &&
                                               ea.InOutDate >= DbFunctions.AddHours(s.ShiftDate, sm.FromTime.Hours - BeforeShiftBuffer) &&
                                               ea.InOutDate <= (sm.ToTime.Hours > 9 ? DbFunctions.AddHours(s.ShiftDate, sm.ToTime.Hours + AfterShiftBuffer) : DbFunctions.AddHours(DbFunctions.AddDays(s.ShiftDate, 1), sm.ToTime.Hours + AfterShiftBuffer))
                                               select new EmployeeAttendanceModel
                {
                    UserID = ea.UserID,
                    InOutDate = ea.InOutDate,
                    InOut = (ea.InOut ? "Out" : "In"),
                    Name = (e.FirstName + " " + e.LastName),
                    ShiftDate = s.ShiftDate
                }).OrderBy(e => e.UserID).ThenBy(e => e.InOutDate).ToList();
            }

            if (getBreakStatus)
            {
                TimeSpan punchTime = new TimeSpan();
                TimeSpan breakTime = new TimeSpan();
                TimeSpan workTime  = new TimeSpan();

                for (int i = 0; i <= employeeAttendanceModelList.Count - 1; i++)
                {
                    if (i == employeeAttendanceModelList.Count - 1)
                    {
                        employeeAttendanceModelList[i].BreakDuration = "Total Work : " + workTime.ToString() + ", Total Break : " + breakTime.ToString();
                    }
                    else if (employeeAttendanceModelList[i].UserID == employeeAttendanceModelList[i + 1].UserID)
                    {
                        punchTime = (employeeAttendanceModelList[i + 1].InOutDate - employeeAttendanceModelList[i].InOutDate);

                        if (employeeAttendanceModelList[i].ShiftDate == employeeAttendanceModelList[i + 1].ShiftDate)
                        {
                            if (employeeAttendanceModelList[i].InOut == "In")
                            {
                                if (employeeAttendanceModelList[i + 1].InOut == "Out")
                                {
                                    employeeAttendanceModelList[i].BreakDuration = "Work : " + punchTime.ToString();
                                    workTime += punchTime;
                                }
                                else
                                {
                                    employeeAttendanceModelList[i].BreakDuration = "Missing Out Punch";
                                }
                            }
                            else
                            {
                                if (employeeAttendanceModelList[i + 1].InOut == "In")
                                {
                                    employeeAttendanceModelList[i].BreakDuration = "Break : " + punchTime.ToString();
                                    breakTime += punchTime;
                                }
                                else
                                {
                                    employeeAttendanceModelList[i].BreakDuration = "Missing In Punch";
                                }
                            }
                        }
                        else
                        {
                            employeeAttendanceModelList[i].BreakDuration = "Total Work : " + workTime.ToString() + ", Total Break : " + breakTime.ToString();
                            workTime  = TimeSpan.Zero;
                            breakTime = TimeSpan.Zero;
                        }
                    }
                    else
                    {
                        employeeAttendanceModelList[i].BreakDuration = "Total Work : " + workTime.ToString() + ", Total Break : " + breakTime.ToString();
                        workTime  = TimeSpan.Zero;
                        breakTime = TimeSpan.Zero;
                    }
                }
            }
            return(employeeAttendanceModelList.OrderBy(e => e.Name).ThenByDescending(e => e.InOutDate).ToList());
        }
Exemple #20
0
        public JsonResult GetTracesPaged(int offset, int limit, string search, string sort, string order)
        {
            // get logs newer than 7 days
            var nowUtc = _now.UtcNow;

            var traces =
                _context.AsQueryable <LogEntry>().Include(x => x.Steps)
                .Where(x => DbFunctions.AddHours(x.Timestamp, LogLimit) > nowUtc)
                .AsQueryable();

            IOrderedQueryable <LogEntry> pagedTraces;

            switch (order)
            {
            case LogsSortAscendingKey:
                pagedTraces = traces.OrderAscending(sort);
                break;

            case LogsSortDescendingKey:
                pagedTraces = traces.OrderDescending(sort);
                break;

            default:
                pagedTraces = traces.OrderDescending(sort);
                break;
            }

            List <LogEntry> pagedTracesList;

            if (string.IsNullOrEmpty(search))
            {
                pagedTracesList = pagedTraces
                                  .Skip((offset / limit) * limit)
                                  .Take(limit).ToList();
            }
            else
            {
                string searchLikeExpression = string.Format("%{0}%", search);
                Expression <Func <LogEntry, bool> > searchExpression =
                    entry => SqlFunctions.PatIndex(searchLikeExpression, entry.RequestUri) > 0 ||
                    entry.Steps.Any(x => SqlFunctions.PatIndex(searchLikeExpression, x.Frame) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Message) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Name) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Metadata) > 0);

                pagedTracesList = pagedTraces.AsExpandable().Where(searchExpression).Skip((offset / limit) * limit).Take(limit).ToList();
            }

            var tracesVms = new List <TraceViewModel>();

            foreach (var trace in pagedTracesList)
            {
                var traceSteps = trace.Steps.OrderBy(x => x.Index).ToList();

                var builder = new StringBuilder();
                builder.Append("<p style=\"white-space: nowrap;\">Start request </p>");

                foreach (var tracestep in traceSteps)
                {
                    builder.Append(string.Format("<p style=\"white-space: nowrap;\">{0}</p>", string.Format("From {0} method located in frame {1} {2} {3} \r\n", tracestep.Source,
                                                                                                            string.Format("<pre class=\"prettyprint lang-cs\">{0}</pre>", tracestep.Frame),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Name) ? string.Format(" (which processes {0}) ", tracestep.Name) : ""),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Message) ? string.Format(" (with message {0}) ", tracestep.Message) : ""))));

                    if (string.IsNullOrEmpty(tracestep.Metadata))
                    {
                        continue;
                    }

                    builder.Append("<p style=\"white-space: nowrap;\">With metadata: </p>");

                    string beautified;
                    if (XmlUtils.IsValidXml(tracestep.Metadata))
                    {
                        // xml
                        // operation metadata is xml in our case
                        beautified = XmlPrettifyHelper.Prettify(tracestep.Metadata.Replace(XmlHeader8, "").Replace(XmlHeader16, ""));
                    }
                    else if (JsonUtils.IsValidJson(tracestep.Metadata))
                    {
                        beautified = string.Format("<pre class=\"prettyprint lang-json\">{0}</pre>",
                                                   JsonPrettifier.BeautifyJson(tracestep.Metadata));
                    }
                    else
                    {
                        beautified = tracestep.Metadata;
                    }

                    builder.Append(beautified);
                }

                builder.Append("<p style=\"white-space: nowrap;\">End request </p>");

                var traceString = HttpUtility.HtmlEncode(builder.ToString());

                var captureDuration = trace.ResponseTimestamp.HasValue && trace.RequestTimestamp.HasValue;

                var item = new TraceViewModel
                {
                    Duration = captureDuration ? string.Format("{0} seconds",
                                                               (trace.ResponseTimestamp.Value - trace.RequestTimestamp.Value).TotalSeconds.ToString("#.##")) : "Duration not captured",
                    Timestamp = trace.Timestamp.ToString(CultureInfo.InvariantCulture),
                    Uri       = trace.RequestUri,
                    Workflow  = new HtmlString(HttpUtility.HtmlDecode(traceString)).ToHtmlString()
                };

                tracesVms.Add(item);
            }

            var model = new
            {
                total = traces.Count(),
                rows  = tracesVms
            };

            return(Json(model, JsonRequestBehavior.AllowGet));
        }
Exemple #21
0
 public void RemoveOutDated()
 {
     try
     {
         using (var context = DataAccessHelper.CreateContext())
         {
             foreach (BazaarItem entity in context.BazaarItem.Where(e => DbFunctions.AddDays(DbFunctions.AddHours(e.DateStart, e.Duration), e.MedalUsed ? 30 : 7) < DateTime.Now))
             {
                 context.BazaarItem.Remove(entity);
             }
         }
     }
     catch (Exception e)
     {
         Logger.Error(e);
     }
 }