public void Normalize()
        {
            if (Sorting.IsNullOrWhiteSpace())
            {
                Sorting = "ExecutionTime DESC";
            }

            if (Sorting.IndexOf("UserName", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                Sorting = "User." + Sorting;
            }
            else
            {
                Sorting = "AuditLog." + Sorting;
            }

            if (StartDate == DateTime.MinValue)
            {
                StartDate = Clock.Now;
            }

            StartDate = StartDate.Date;

            if (EndDate == DateTime.MinValue)
            {
                EndDate = Clock.Now;
            }

            EndDate = EndDate.AddDays(1).Date;
        }
Beispiel #2
0
        internal Expression WasMemberAsOf()
        {
            var tf  = CodeIds == "1";
            var now = Util.Now;

            EndDate = EndDate?.AddDays(1) ?? StartDate?.AddDays(1);
            Expression <Func <Person, bool> > pred = p => (
                from et in p.EnrollmentTransactions
                where et.TransactionTypeId <= 3     // things that start a change
                where et.TransactionStatus == false
                where et.TransactionDate <= EndDate // transaction starts <= looked for end
                where et.MemberTypeId != MemberTypeCode.Prospect
                where (et.Pending ?? false) == false
                where (et.NextTranChangeDate ?? now) >= StartDate // transaction ends >= looked for start
                where (OrgTypeInt ?? 0) == 0 || et.Organization.OrganizationTypeId == OrgTypeInt
                where OrganizationInt == 0 || et.OrganizationId == OrganizationInt
                where DivisionInt == 0 || et.Organization.DivOrgs.Any(dg => dg.DivId == DivisionInt)
                where ProgramInt == 0 || et.Organization.DivOrgs.Any(dg => dg.Division.ProgDivs.Any(pg => pg.ProgId == ProgramInt))
                select et
                ).Any();
            Expression expr = Expression.Convert(Expression.Invoke(pred, parm), typeof(bool));

            if (!(op == CompareType.Equal && tf))
            {
                expr = Expression.Not(expr);
            }
            return(expr);
        }
Beispiel #3
0
        private void AllDayEventValidation()
        {
            if (!AllDayEvent)
            {
                return;
            }

            _startTime = DefaultTimeValue;
            RaisePropertyChanged(() => StartTime);

            _endTime = DefaultTimeValue;
            RaisePropertyChanged(() => EndTime);

            if (Math.Abs((EndDate - StartDate).TotalDays) < 1)
            {
                _endDate = EndDate.AddDays(1);
                RaisePropertyChanged(() => EndDate);
            }

            if ((int)Math.Abs((EndDate - StartDate).TotalDays) == 1)
            {
                if (DateTime.Parse(StartTime).TimeOfDay > DateTime.Parse(EndTime).TimeOfDay)
                {
                    _endTime = StartTime;
                    RaisePropertyChanged(() => EndTime);
                }
            }
        }
Beispiel #4
0
        internal Expression MemberTypeAsOf()
        {
            var end = EndDate?.AddDays(1) ?? StartDate?.AddDays(1);

            Expression <Func <Person, bool> > pred = p => (
                from et in p.EnrollmentTransactions
                where et.TransactionTypeId <= 3                        // things that start a change
                where et.TransactionStatus == false
                where StartDate <= (et.NextTranChangeDate ?? Util.Now) // where it ends
                where et.TransactionDate <= end                        // where it begins
                where (et.Pending ?? false) == false
                where CodeIntIds.Contains(et.MemberTypeId)             // what it's type was during that time
                where (OrgTypeInt ?? 0) == 0 || et.Organization.OrganizationTypeId == OrgTypeInt
                where OrganizationInt == 0 || et.OrganizationId == OrganizationInt
                where DivisionInt == 0 || et.Organization.DivOrgs.Any(dg => dg.DivId == DivisionInt)
                where ProgramInt == 0 || et.Organization.DivOrgs.Any(dg => dg.Division.ProgDivs.Any(pg => pg.ProgId == ProgramInt))
                select et
                ).Any();
            Expression expr = Expression.Invoke(pred, parm);

            if (op == CompareType.NotEqual || op == CompareType.NotOneOf)
            {
                expr = Expression.Not(expr);
            }
            return(expr);
        }
Beispiel #5
0
        public void Normalize()
        {
            if (Sorting.IsNullOrWhiteSpace())
            {
                Sorting = $"{sort} {order}" ?? "ExecutionTime DESC";//
            }

            if (Sorting.IndexOf("UserName", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                Sorting = "User." + Sorting;
            }
            else
            {
                //Abp.Logging.LogHelper.Logger.Debug("11111111111");
                Sorting = "AuditLog." + Sorting;
            }

            if (StartDate == DateTime.MinValue)
            {
                StartDate = Clock.Now;
            }

            StartDate = StartDate.Date;

            if (EndDate == DateTime.MinValue)
            {
                EndDate = Clock.Now;
            }

            EndDate = EndDate.AddDays(1).Date;
        }
        public WhenEditingEndDateFixture()
        {
            var fixture = new Fixture();

            fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            Now            = EndDate = DateTime.UtcNow;
            CompletionDate = EndDate.AddDays(10);
            StartDate      = EndDate.AddDays(-10);

            UnitOfWorkContext = new UnitOfWorkContext();

            Cohort = new CommitmentsV2.Models.Cohort()
                     .Set(c => c.Id, 111)
                     .Set(c => c.EmployerAccountId, 222)
                     .Set(c => c.ProviderId, 333);

            CurrentDateTime = new Mock <ICurrentDateTime>();
            CurrentDateTime.Setup(x => x.UtcNow).Returns(Now);

            UserInfo = fixture.Create <UserInfo>();

            Apprenticeship = fixture.Build <CommitmentsV2.Models.Apprenticeship>()
                             .With(s => s.Cohort, Cohort)
                             .With(s => s.PaymentStatus, PaymentStatus.Completed)
                             .With(s => s.EndDate, EndDate)
                             .With(s => s.CompletionDate, CompletionDate)
                             .With(s => s.StartDate, StartDate)
                             .Without(s => s.DataLockStatus)
                             .Without(s => s.EpaOrg)
                             .Without(s => s.ApprenticeshipUpdate)
                             .Without(s => s.Continuation)
                             .Without(s => s.PreviousApprenticeship)
                             .Create();
        }
        public MonthlyInterval(DateTime startDate, int endDay) : base(Period.Monthly)
        {
            var endDateAtEndOfMonth = false;

            EndDay = endDay;
            if (EndDay == -1 || EndDay > 30)
            {
                endDateAtEndOfMonth = true;
            }

            if (endDateAtEndOfMonth)
            {
                EndDate = new DateTime(startDate.Year, startDate.Month, DateTime.DaysInMonth(startDate.Year, startDate.Month));
            }
            else
            {
                var tmp = (endDay < startDate.Day)
                    ? startDate.AddMonths(1)
                    : startDate;

                EndDate = new DateTime(tmp.Year, tmp.Month, Math.Min(endDay, DateTime.DaysInMonth(tmp.Year, tmp.Month)));
            }
            if (!endDateAtEndOfMonth)
            {
                StartDate = EndDate.AddMonths(-1).AddDays(1);
            }
            else
            {
                StartDate = EndDate.AddDays(1).AddMonths(-1);
            }
        }
        SaveScheduleEntryRangeParam createSaveParam()
        {
            SaveScheduleEntryRangeParam param = new SaveScheduleEntryRangeParam();

            param.Entries.AddRange(Entries.Select(x => x.Item));
            param.StartDay = StartDate.ToUniversalTime();
            param.EndDay   = EndDate.AddDays(1).ToUniversalTime();
            return(param);
        }
Beispiel #9
0
        private bool TryGetConditions(int pageIndex, int pageSize, out Hashtable conditions)
        {
            var errors = new List <string>();

            Int32 pageStart = pageSize * (pageIndex - 1) + 1;
            Int32 pageEnd   = pageSize * pageIndex;

            EndDate = EndDate.AddDays(1).AddSeconds(-1);
            var logType = GetLogType();

            conditions = new Hashtable()
            {
                { "RecordType", logType },
                { "StartDate", StartDate },
                { "EndDate", EndDate },
                { "PageStart", pageStart },
                { "PageEnd", pageEnd },
            };

            if (!string.IsNullOrWhiteSpace(DeviceCode))
            {
                if (DeviceCode.ToInt32() == ConvertorExtension.ConvertionFailureValue)
                {
                    errors.Add("设备编号的输入值必须是数字");
                }
                if (ApplicationManager.GetInstance().AuthorizationDevices.All(x => x.Code != DeviceCode))
                {
                    errors.Add("输入的设备编号不存在系统中");
                }

                conditions.Add("DeviceCode", DeviceCode);
            }


            if (!string.IsNullOrWhiteSpace(DeviceUserId))
            {
                if (DeviceUserId.ToInt32() == ConvertorExtension.ConvertionFailureValue)
                {
                    errors.Add("人员工号的输入值必须是数字");
                }

                conditions.Add("DeviceUserId", DeviceUserId);
            }

            if (errors.Any())
            {
                var message = string.Join("\n", errors);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Messenger.Default.Send(new NotificationMessage(message), Tokens.DeviceTrafficLogPage_ShowNotification);
                });
                return(false);
            }

            return(true);
        }
Beispiel #10
0
        public SystemLogViewModel(ILoggerService service, IUserService userService, IMessenger messenger)
            : base(messenger)
        {
            _LoggerService = service;
            _UserService   = userService;


            EndDate   = DateTime.Today;
            StartDate = EndDate.AddDays(-7);
            LoadRoot();
        }
Beispiel #11
0
        public DataTimeParamViewModel()
        {
            StartDate = StartDate.AddSeconds(StartTime);
            EndDate   = EndDate.AddSeconds(StartTime);

            if (StartDate > DateTime.Now)
            {
                StartDate = StartDate.AddDays(-1);
                EndDate   = EndDate.AddDays(-1);
            }
        }
Beispiel #12
0
        private List <Calendar.Appointment> GetMatchingAppointments(DateTime start, DateTime end, bool sorted = false)
        {
            // Future items are always populated on demand
            m_FutureItems = new Dictionary <uint, CalendarFutureItem>();

            var    appts        = new List <Calendar.Appointment>();
            UInt32 nextFutureId = (((m_MaxTaskID / 1000) + 1) * 1000);

            foreach (System.Collections.Generic.KeyValuePair <UInt32, CalendarItem> pair in m_Items)
            {
                CalendarItem item = pair.Value;

                if (!IsItemDisplayable(item))
                {
                    continue;
                }

                if (IsItemWithinRange(item, start, end))
                {
                    appts.Add(item);
                }

                if (m_ShowFutureOcurrences && item.IsRecurring)
                {
                    // Add this task's future items for the current date range
                    // Note: we deliberately double the range else we lose
                    // future items which overlap the the current item
                    var futureItems = m_TaskRecurrences.Get(item.Id, StartDate, EndDate.AddDays(DaysShowing));

                    if (futureItems != null)
                    {
                        foreach (var futureItem in futureItems)
                        {
                            var futureAppt = new CalendarFutureItem(item, nextFutureId, futureItem);

                            if (IsItemWithinRange(futureAppt, start, end))
                            {
                                m_FutureItems[nextFutureId++] = futureAppt;
                                appts.Add(futureAppt);
                            }
                        }
                    }
                }
            }

            if (sorted)
            {
                appts.Sort((a, b) => (int)(b.StartDate.Ticks - a.StartDate.Ticks));
            }

            return(appts);
        }
Beispiel #13
0
        public IList <CallRecord> Find()
        {
            var searchText = String.IsNullOrEmpty(SearchText) ? String.Empty : SearchText.ToLower();

            searchText.Trim();
            searchText = Utils.StringToMySqlString(searchText);
            var sortFilter      = String.Format(" order by `{0}` {1} ", GetSortProperty(), GetSortDirection());
            var limit           = String.Format("limit {0}, {1}", Page * PageSize, PageSize);
            var searchCondition = String.IsNullOrEmpty(searchText) ? String.Empty :
                                  " and (LOWER({CallRecord}.`From`) like \"%" + searchText +
                                  "%\" or LOWER({CallRecord}.`To`) like \"%" + searchText +
                                  "%\" or LOWER({CallRecord}.NameFrom) like \"%" + searchText +
                                  "%\" or LOWER({CallRecord}.NameTo) like \"%" + searchText + "%\") ";

            if (CallType != null)
            {
                searchCondition += " and {CallRecord}.CallType = " + Convert.ToInt32(CallType);
            }

            IList <CallRecord> callList = null;
            var sql = @"
select {CallRecord.*}
from logs.RecordCalls {CallRecord}
where {CallRecord}.WriteTime > :BeginDate and {CallRecord}.WriteTime < :EndDate"
                      + searchCondition + sortFilter + limit;

            var countSql = @"
select count(*)
from logs.RecordCalls {CallRecord}
where {CallRecord}.WriteTime > :BeginDate and {CallRecord}.WriteTime < :EndDate" + searchCondition;

            countSql = countSql.Replace("{CallRecord}", "c");

            ArHelper.WithSession(session => {
                callList = session.CreateSQLQuery(sql)
                           .AddEntity(typeof(CallRecord))
                           .SetParameter("BeginDate", BeginDate)
                           .SetParameter("EndDate", EndDate.AddDays(1))
                           .List <CallRecord>();

                var count = Convert.ToInt32(session.CreateSQLQuery(countSql)
                                            .SetParameter("BeginDate", BeginDate)
                                            .SetParameter("EndDate", EndDate.AddDays(1))
                                            .UniqueResult());
                TotalPages = count / PageSize;
                if (count % PageSize > 0)
                {
                    TotalPages++;
                }
            });
            return(callList);
        }
        protected override IEnumerable <ShopGuiderSaleAchievementEntity> SearchData()
        {
            var lp            = VMGlobal.DistributionQuery.LinqOP;
            var oids          = OrganizationArray.Select(o => o.ID).ToArray();
            var endDate       = EndDate.AddDays(1);
            var retailContext = lp.Search <BillRetail>(o => oids.Contains(o.OrganizationID) && o.CreateTime >= BeginDate && o.CreateTime <= endDate);
            var result        = this.SearchData(retailContext);

            foreach (var r in result)
            {
                var org = OrganizationArray.FirstOrDefault(o => o.ID == r.OrganizationID);
                if (org != null)
                {
                    r.OrganizationName = org.Name;
                }
            }
            return(result);
        }
        /// <summary>
        /// Raise do search event.
        /// </summary>
        private void RaiseDoExcel()
        {
            _isInquiring = true;
            DoSearchEventArgs args = new DoSearchEventArgs(DoExcelEvent, this)
            {
                PageIndex        = PageIndex,
                PageSize         = PageSize,
                ProductName      = GetSelectedProductName(),
                StartDate        = StartDate,
                EndDate          = EndDate.AddDays(1).AddSeconds(-1),
                OrdersTypeString = GetOrdersTypeString(),
                AccountName      = AccountName,
                StockCode        = this.CbStockCode.SelectedItem.ToString(),
            };

            RaiseEvent(args);
            _isInquiring = false;
        }
        private bool TryGetConditions(int pageIndex, int pageSize, out Hashtable conditions)
        {
            var errors = new List <string>();

            Int32 pageStart = pageSize * (pageIndex - 1) + 1;
            Int32 pageEnd   = pageSize * pageIndex;

            EndDate = EndDate.AddDays(1).AddSeconds(-1);

            conditions = new Hashtable()
            {
                { "StartDate", StartDate },
                { "EndDate", EndDate },
                { "PageStart", pageStart },
                { "PageEnd", pageEnd },
            };

            if (!string.IsNullOrWhiteSpace(Keyword))
            {
                conditions.Add("Keyword", Keyword);
            }

            if (!string.IsNullOrWhiteSpace(OperatorId))
            {
                if (OperatorId.ToInt32() == ConvertorExtension.ConvertionFailureValue)
                {
                    errors.Add("操作人员ID的输入值必须是数字");
                }

                conditions.Add("UserID", OperatorId);
            }

            if (errors.Any())
            {
                var message = string.Join("\n", errors);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    Messenger.Default.Send(new NotificationMessage(message), Tokens.SysOperationLogPage_ShowNotification);
                });
                return(false);
            }

            return(true);
        }
Beispiel #17
0
        public WeeklyInterval(DateTime startDate, int endDay) : base(Period.Weekly)
        {
            EndDay = endDay;

            if ((int)startDate.DayOfWeek > endDay)
            {
                EndDate = startDate.AddDays(7 - (int)startDate.DayOfWeek + endDay);
            }
            else if ((int)startDate.DayOfWeek < endDay)
            {
                EndDate = startDate.AddDays(endDay - (int)startDate.DayOfWeek);
            }
            else
            {
                EndDate = startDate;
            }

            StartDate = EndDate.AddDays(-6);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CalendarViewFormat"/> class.
        /// </summary>
        /// <param name="viewType">Type of the view.</param>
        /// <param name="showday">The showday.</param>
        /// <param name="weekStartDay">The week start day.</param>
        public CalendarViewFormat(CalendarViewType viewType, DateTime showday, DayOfWeek weekStartDay)
        {
            int index, w;

            switch (viewType)
            {
            case CalendarViewType.day:     //ÈÕ
                StartDate = showday.Date;
                EndDate   = showday.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
                break;

            case CalendarViewType.week:                          // ÖÜ
                index = weekStartDay.GetHashCode();              //0
                w     = index - showday.DayOfWeek.GetHashCode(); //0-1
                if (w > 0)
                {
                    w = w - 7;
                }
                StartDate = showday.AddDays(w).Date;
                EndDate   = StartDate.AddDays(6).AddHours(23).AddMinutes(59).AddSeconds(59);
                break;

            case CalendarViewType.month:                           // ÔÂ
                DateTime firstdate = new DateTime(showday.Year, showday.Month, 1);
                index = weekStartDay.GetHashCode();                //0
                w     = index - firstdate.DayOfWeek.GetHashCode(); //0-1
                if (w > 0)
                {
                    w -= 7;
                }
                //w = 0;
                StartDate = firstdate.AddDays(w).Date;
                EndDate   = StartDate.AddDays(34);

                if (EndDate.Year == showday.Year && EndDate.Month == showday.Month && EndDate.AddDays(1).Month == EndDate.Month)
                {
                    EndDate = EndDate.AddDays(7);
                }
                EndDate.AddHours(23).AddMinutes(59).AddSeconds(59);
                break;
            }
        }
        /// <summary>
        /// Поиск логов для нового приложения analit-f
        /// </summary>
        /// <returns></returns>
        public IList <RequestLog> Find(ISession session)
        {
            var logQuery = session.Query <ClientAppLog>()
                           .Where(x => x.CreatedOn > BeginDate && x.CreatedOn < EndDate.AddDays(1));
            var requestQuery = session.Query <RequestLog>()
                               .Where(x => x.CreatedOn > BeginDate && x.CreatedOn < EndDate.AddDays(1))
                               .OrderBy(string.Format("{0} {1}", SortBy, SortDirection));

            if (User != null)
            {
                logQuery     = logQuery.Where(i => i.User == User);
                requestQuery = requestQuery.Where(i => i.User == User);
            }
            else if (Client != null)
            {
                logQuery     = logQuery.Where(i => i.User.Client == Client);
                requestQuery = requestQuery.Where(i => i.User.Client == Client);
            }
            if (ErrorType == 1)
            {
                requestQuery = session.Query <RequestLog>().Where(i => i.ErrorType == 1 && i.CreatedOn > BeginDate && i.CreatedOn < EndDate.AddDays(1))
                               .OrderBy(string.Format("{0} {1}", SortBy, SortDirection));
            }
            else if (ErrorType == 0)
            {
                requestQuery = session.Query <RequestLog>()
                               .Where(i => i.IsCompleted && !i.IsFaulted && i.UpdateType == "MainController" && i.CreatedOn > BeginDate && i.CreatedOn < EndDate.AddDays(1))
                               .OrderBy(string.Format("{0} {1}", SortBy, SortDirection));
            }

            var logs = logQuery.ToList();

            var results = requestQuery.ToList();

            var connectedLogs = logs
                                .Where(l => l.RequestToken != null && results.Any(x => x.RequestToken == l.RequestToken))
                                .ToArray();

            results.Each(x => x.HaveLog = connectedLogs.Any(y => y.RequestToken == x.RequestToken));

            return(results);
        }
Beispiel #20
0
        private void loadEventsToDays()
        {
            days = new List <Day>();
            ArrayList items = (ArrayList)ViewState["Items"];

            if (Resources == null)
            {
                return;
            }

            foreach (Resource resource in Resources)
            {
                Day d = new Day(StartDate, EndDate.AddDays(1), resource.Name, resource.Value, CellDuration);
                days.Add(d);
            }

            foreach (Day d in days)
            {
                d.Load(items);
            }
        }
Beispiel #21
0
        internal Expression OrgMemberJoinedAsOf()
        {
            var tf = CodeIds == "1";

            EndDate = EndDate?.AddDays(1) ?? StartDate?.AddDays(1);
            Expression <Func <Person, bool> > pred = p => (
                from om in p.OrganizationMembers
                where om.EnrollmentDate >= StartDate
                where om.EnrollmentDate < EndDate
                where (OrgTypeInt ?? 0) == 0 || om.Organization.OrganizationTypeId == OrgTypeInt
                where OrganizationInt == 0 || om.OrganizationId == OrganizationInt
                where DivisionInt == 0 || om.Organization.DivOrgs.Any(dg => dg.DivId == DivisionInt)
                where ProgramInt == 0 || om.Organization.DivOrgs.Any(dg => dg.Division.ProgDivs.Any(pg => pg.ProgId == ProgramInt))
                select om
                ).Any();
            Expression expr = Expression.Convert(Expression.Invoke(pred, parm), typeof(bool));

            if (!(op == CompareType.Equal && tf))
            {
                expr = Expression.Not(expr);
            }
            return(expr);
        }
Beispiel #22
0
 public bool IsActive()
 {
     return(StartDate <= DateTime.Now && DateTime.Now <= EndDate.AddDays(1));
 }
Beispiel #23
0
 public bool IsExpired()
 {
     return(DateTime.Now > EndDate.AddDays(1));
 }
 Func <IEnumerable <TradeRecordInfo>, IEnumerable <TradeRecordInfo> > GetCondtionByTime()
 {
     if (TimeSelectIndex == 0)
     {
         //all
         return((IEnumerable <TradeRecordInfo> x) => { return x; });
     }
     if (TimeSelectIndex == 1)
     {
         //today
         return((IEnumerable <TradeRecordInfo> x) => { return x.Where(p => p.TradeTime.ToString("yyyyMMdd").Equals(DateTime.Now.ToString("yyyyMMdd"))); });
     }
     if (TimeSelectIndex == 2)
     {
         //thisweek
         return((IEnumerable <TradeRecordInfo> x) =>
         {
             return x.Where(p =>
             {
                 DateTime temp1 = p.TradeTime.AddDays(-(int)p.TradeTime.DayOfWeek).Date;
                 DateTime temp2 = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek).Date;
                 return temp1 == temp2;
             });
         });
     }
     if (TimeSelectIndex == 3)
     {
         //thisMon
         return((IEnumerable <TradeRecordInfo> x) =>
         {
             return x.Where(p => p.TradeTime.Year == DateTime.Now.Year && p.TradeTime.Month == DateTime.Now.Month);
         });
     }
     if (TimeSelectIndex == 4)
     {
         //prevMon
         return((IEnumerable <TradeRecordInfo> x) =>
         {
             if (DateTime.Now.Month == 1)
             {
                 return x.Where(p => p.TradeTime.Year == (DateTime.Now.Year - 1) && p.TradeTime.Month == 12);
             }
             else
             {
                 return x.Where(p => p.TradeTime.Year == DateTime.Now.Year && (DateTime.Now.Month - p.TradeTime.Month) == -1);
             }
         });
     }
     if (TimeSelectIndex == 5)
     {
         //thisYear
         return((IEnumerable <TradeRecordInfo> x) =>
         {
             return x.Where(p => p.TradeTime.Year == DateTime.Now.Year);
         });
     }
     if (TimeSelectIndex == 6)
     {
         //other
         return((IEnumerable <TradeRecordInfo> x) =>
         {
             return x.Where(p => p.TradeTime >= StartDate && p.TradeTime <= EndDate.AddDays(1));
         });
     }
     return(null);
 }
Beispiel #25
0
 internal void AddDay()
 {
     EndDate = EndDate.AddDays(1);
 }
Beispiel #26
0
 private DateTime NextStartDate()
 {
     return(EndDate.AddDays(1));
 }
Beispiel #27
0
        private void LoadTable()
        {
            try
            {
                DateTime      StDate;
                DateTime      EndDate;
                string        DateFmt;
                DAO.Recordset RS;
                int           ID = 0;

                // make tmp table
                string SQL1 = "SELECT recTimeStamp, senSensorNumber, recTemp INTO tmpRecs";
                SQL1 += " FROM tblSensors LEFT JOIN tblRecords ON tblSensors.senID = tblRecords.recSenID";
                SQL1 += " GROUP BY recTimeStamp,senSensorNumber,recTemp,senBinNumber,senCableNumber";
                SQL1 += " Having senBinNumber = " + tbBin.Text;
                SQL1 += " And senCableNumber = " + tbCable.Text;

                // date
                StDate  = dtpSingle.Value;
                EndDate = dtpRange.Value;
                if (StDate == EndDate | rbSingle.Checked)
                {
                    // single date, end date is beginning of the next day
                    EndDate = StDate.AddDays(1);
                }
                else
                {
                    // date range, end date is beginning of the next day after user selected end date
                    EndDate = EndDate.AddDays(1);
                }
                SQL1 += " And recTimeStamp >= " + mf.Dbase.ToAccessDate(StDate) + " And recTimeStamp < " + mf.Dbase.ToAccessDate(EndDate);
                SQL1 += " Order By senBinNumber,recTimeStamp,senCableNumber,senSensorNumber";

                mf.Dbase.DeleteTable("tmpRecs"); // delete old table, if any

                mf.Dbase.DB.Execute(SQL1);       // create tmp table

                // make crosstab recordset
                if (rbHour.Checked)
                {
                    DateFmt = "" + (char)39 + "yyyy/mm/dd  hh" + (char)39;
                }
                else
                {
                    DateFmt = "" + (char)39 + "yyyy/mm/dd" + (char)39;
                }
                string SQL = "Transform Avg(recTemp) as AvgOfrecTemp";
                SQL += " Select Format([recTimeStamp]," + DateFmt + ") as ReadDate";
                SQL += " From tmpRecs";
                SQL += " Group By Format([recTimeStamp]," + DateFmt + ")";
                SQL += " PIVOT senSensorNumber In (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)";
                RS   = mf.Dbase.DB.OpenRecordset(SQL);

                dataSet1.Clear();

                try  // needed to close recordset after error
                {
                    while (!RS.EOF)
                    {
                        ID++;
                        DataRow Rw = dataSet1.Tables[0].NewRow();
                        Rw[0] = ID;
                        Rw[1] = mf.Dbase.FieldToString(RS, "ReadDate");
                        for (int i = 0; i < 16; i++)
                        {
                            Rw[i + 2] = mf.Dbase.FieldToFloat(RS, (i + 1).ToString("N0"));
                        }

                        dataSet1.Tables[0].Rows.Add(Rw);
                        RS.MoveNext();
                    }
                }
                catch (Exception)
                {
                }
                RS.Close();
            }
            catch (Exception ex)
            {
                mf.Tls.TimedMessageBox(ex.Message);
                mf.Tls.WriteErrorLog("frmBinReport:LoadTable " + ex.Message);
            }
        }
Beispiel #28
0
        public IEnumerable <string> GetDays(RequestHourlyPricing requestHourlyPricing, DayShifts Shift, int countOfDays, Promotion promotion)
        {
            requestHourlyPricing.ContractStartDate = requestHourlyPricing.ContractStartDate.Replace('/', '-');
            DateTime startDate;

            try
            {
                startDate = DateTime.ParseExact(requestHourlyPricing.ContractStartDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                startDate = DateTime.ParseExact(requestHourlyPricing.ContractStartDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            var totalVisits          = requestHourlyPricing.ContractDuration * requestHourlyPricing.Weeklyvisits;
            var extraVisits          = (promotion.FreeVisitsFactor ?? 0) == 0 ? 0 : Math.Truncate((decimal)totalVisits / promotion.FreeVisitsFactor.Value);
            var totalPlusExtraVisits = totalVisits + extraVisits;

            DateTime EndDate;

            var contractDurationAfterPromotionInWeeks = (int)Math.Ceiling(totalPlusExtraVisits / requestHourlyPricing.Weeklyvisits);


            if (contractDurationAfterPromotionInWeeks <= 3)
            {
                EndDate = startDate.AddDays(6 * contractDurationAfterPromotionInWeeks);
            }
            else
            {
                EndDate = startDate.AddDays(7 * contractDurationAfterPromotionInWeeks);
                EndDate = EndDate.AddDays(-1);
            }


            string shift = Shift.ToString();

            #region commented

            /* string sql = @"Select distinct DayName  from HourContractShifts('@ContractStartDate','@ContractEndDate','@districtid','@ShiftName',4)
             *           where nationalityId='@nationality'
             *           group by HourContractShifts.new_resourcecode,DayName
             *           having COUNT(*)>=@visitsCount order by DayName";
             *
             *
             *
             *
             *
             *
             *
             *
             *
             * //
             * sql = sql.Replace("@ContractStartDate", startDate.Date.ToString());
             * sql = sql.Replace("@ContractEndDate", EndDate.Date.ToString());
             * sql = sql.Replace("@districtid", DistrictId);
             * sql = sql.Replace("@ShiftName", shift);
             * sql = sql.Replace("@nationality", NationalityId);
             * if (months!=0)
             * sql = sql.Replace("@visitsCount", (4 * months).ToString());
             * else
             *  sql = sql.Replace("@visitsCount", (countofdays).ToString());
             *
             * DataTable dt = CRMAccessDB.SelectQ(sql).Tables[0];
             *
             * string sql2 = @"select new_days from new_district  where new_districtId='@id'";
             * sql2 = sql2.Replace("@id", DistrictId);
             * DataTable dtdistrict = CRMAccessDB.SelectQ(sql2).Tables[0];
             */
            #endregion


            //            string sql = @"
            //with allSihfts as  (
            // select  ShiftFrom,  nationalityId,dayname,Count(distinct new_hourresourceId) SeatNo,count(distinct new_employeeid) as NoOfResources from
            //HourContractShiftsV02('@MinDate','@MaxDate','@districtid','@ShiftName','@nationality',@hoursCount,'@cityid')
            //                       --where Dayname in ('Sunday')
            //                    group by dayname,shiftfrom,nationalityId
            //					having Count(distinct new_hourresourceId)>=@EmpCount and count(distinct new_employeeid)>=@EmpCount
            //)

            //select nationalityId,dayname,count(dayname) counts from allSihfts
            //group by nationalityId,dayname
            //having count(dayname) >=@visitsCount";

            string sql = @"exec dbo.HourContractShifts_ValidationV01 
                                '@MinDate','@MaxDate','@districtid','@ShiftName','@nationality',@hoursCount,'@cityid' , @empCount, @visitsCount
                          ";

            //sql = sql.Replace("@visitsCount", (countOfDays / requestHourlyPricing.Weeklyvisits).ToString());

            sql = sql.Replace("@visitsCount", (contractDurationAfterPromotionInWeeks).ToString());

            sql = sql.Replace("@empCount", (requestHourlyPricing.Empcount).ToString());

            sql = sql.Replace("@hoursCount", requestHourlyPricing.HoursCount.ToString());
            sql = sql.Replace("@cityid", requestHourlyPricing.CityId);


            sql = sql.Replace("@MinDate", startDate.AddHours(3).Date.ToString("MM/dd/yyyy"));
            sql = sql.Replace("@MaxDate", EndDate.Date.ToString("MM/dd/yyyy"));



            sql = sql.Replace("@districtid", requestHourlyPricing.DistrictId);

            //if (shift == "صباحي") ShiftName = "Morning";
            //if (ShiftName == "مسائي") ShiftName = "Evening";
            sql = sql.Replace("@ShiftName", shift);
            sql = sql.Replace("@nationality", requestHourlyPricing.NationalityId);
            // SqlCommand CMD = new SqlCommand(sql);
            System.Data.DataTable dt = CRMAccessDB.SelectQ(sql).Tables[0];
            string avaDays           = string.Empty;


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (avaDays.IndexOf(dt.Rows[i]["DayName"].ToString()) == -1)
                {
                    avaDays = avaDays + dt.Rows[i]["DayName"] + ",";
                }
            }
            if (!string.IsNullOrEmpty(avaDays))
            {
                avaDays = avaDays.Remove(avaDays.Length - 1);
            }


            List <string> DaysOfWeek = avaDays.Split(',').ToList();

            //Avilable Days List
            //List<string> List = new List<string>();
            //for (int i = 0; i < dt.Rows.Count; i++) List.Add(dt.Rows[i][0].ToString());

            return(DaysOfWeek);
        }
        public void SearchData()
        {
            var lp             = VMGlobal.DistributionQuery.LinqOP;
            var oids           = OrganizationArray.Select(o => o.ID).ToArray();
            var endDate        = EndDate.AddDays(1);
            var retailContext  = lp.Search <BillRetail>(o => o.CreateTime >= BeginDate && o.CreateTime <= endDate && oids.Contains(o.OrganizationID));
            var detailsContext = lp.GetDataContext <BillRetailDetails>();
            var productContext = lp.GetDataContext <ViewProduct>();

            if (BrandID != default(int))
            {
                productContext = productContext.Where(p => p.BrandID == BrandID);
            }
            if (Quarter != default(int))
            {
                productContext = productContext.Where(p => p.Quarter == Quarter);
            }

            var data = from retail in retailContext
                       from details in detailsContext
                       where retail.ID == details.BillID
                       from product in productContext
                       where product.ProductID == details.ProductID && product.Year == Year
                       select new ABCEntity
            {
                StyleCode = product.StyleCode,
                CostMoney = details.Price * details.Quantity * details.Discount / 100 - details.CutMoney,
                ColorID   = product.ColorID,
                NameID    = product.NameID
            };
            var result = data.ToList();

            foreach (var r in result)
            {
                r.Name = VMGlobal.ProNames.Find(o => o.ID == r.NameID).Name;
            }
            AmountCostMoney = result.Sum(o => o.CostMoney);
            StyleABCEntity  = result.GroupBy(o => new { o.StyleCode, o.Name }).Select(g => new ABCEntity
            {
                StyleCode = g.Key.StyleCode,
                Name      = g.Key.Name,
                CostMoney = g.Sum(o => o.CostMoney)
            }).OrderByDescending(o => o.CostMoney).ToList();
            decimal accumulativeProportion = 0;

            foreach (var abc in StyleABCEntity)
            {
                abc.Proportion          = abc.CostMoney / AmountCostMoney;
                accumulativeProportion += abc.Proportion;
                abc.AccuProportion      = accumulativeProportion;
            }
            ProNameABCEntity = result.GroupBy(o => o.Name).Select(g => new ABCEntity
            {
                Name      = g.Key,
                CostMoney = g.Sum(o => o.CostMoney)
            }).OrderByDescending(o => o.CostMoney).ToList();
            accumulativeProportion = 0;
            foreach (var abc in ProNameABCEntity)
            {
                abc.Proportion          = abc.CostMoney / AmountCostMoney;
                accumulativeProportion += abc.Proportion;
                abc.AccuProportion      = accumulativeProportion;
            }
            ColorABCEntity = result.GroupBy(o => o.ColorID).Select(g => new ABCEntity
            {
                ColorID   = g.Key,
                CostMoney = g.Sum(o => o.CostMoney)
            }).OrderByDescending(o => o.CostMoney).ToList();
            accumulativeProportion = 0;
            foreach (var abc in ColorABCEntity)
            {
                abc.ColorName           = VMGlobal.Colors.Find(o => o.ID == abc.ColorID).Name;
                abc.Proportion          = abc.CostMoney / AmountCostMoney;
                accumulativeProportion += abc.Proportion;
                abc.AccuProportion      = accumulativeProportion;
            }
            OnPropertyChanged("StyleABCEntity");
            OnPropertyChanged("ColorABCEntity");
            OnPropertyChanged("ProNameABCEntity");
            OnPropertyChanged("AmountCostMoney");
        }
Beispiel #30
0
 private void InitDefaults()
 {
     _endDate   = DateTime.Now.AddDays(1).Date;
     _startDate = EndDate.AddDays(-60).Date;
 }