예제 #1
0
        public void TestStartOfWeek()
        {
            DateTime dt = new DateTime(2014, 3, 13);
            Assert.AreEqual(new DateTime(2014, 3, 10), dt.StartOfWeek(DayOfWeek.Monday));
            Assert.AreEqual(new DateTime(2014, 3, 9), dt.StartOfWeek(DayOfWeek.Sunday));

            DateTime dt2 = new DateTime(2016, 5, 1);
            Assert.AreEqual(new DateTime(2016, 4, 30), dt2.StartOfWeek(DayOfWeek.Saturday));
        }
예제 #2
0
        public void StartOfWeekWithCustomDayOfWeekShouldReturnExpectedResult()
        {
            var date = new DateTime( 2013, 3, 1 );
            var expected = new DateTime( 2013, 2, 24 );
            var actual = date.StartOfWeek( DayOfWeek.Sunday );
            Assert.Equal( expected.Date, actual.Date );

            expected = new DateTime( 2013, 2, 25 );
            actual = date.StartOfWeek( DayOfWeek.Monday );
            Assert.Equal( expected.Date, actual.Date );
        }
        public void StartOfWeekTestCase()
        {
            var dateTime = new DateTime( 2014, 3, 27 );
            var expected = new DateTime( 2014, 3, 24 );
            var actual = dateTime.StartOfWeek();

            Assert.AreEqual( expected, actual );

            expected = new DateTime( 2014, 3, 26 );
            actual = dateTime.StartOfWeek( DayOfWeek.Wednesday );

            Assert.AreEqual( expected, actual );
        }
예제 #4
0
        public GroupNotes()
        {
            InitializeComponent();
            admin = false;

            String query = "select ClientNum, ClientName from ClientInfo where IntakeDate not like '0001-01-01%' and ExitDate like '0001-01-01%'";
            clients = database.GetTable(query);

            editingDay = DateTime.Now;
            lastDayOfWeek = editingDay.Next(DayOfWeek.Sunday);
            firstDayOfWeek = editingDay.StartOfWeek(DayOfWeek.Monday);
            dayOfWeek = editingDay.DayOfWeek.ToString();
            WeekOf_Label.Text = "Week of " + firstDayOfWeek.ToString("MM/dd") + " through " + lastDayOfWeek.ToString("MM/dd");

            updateClientList();
            clientList.SetSelected(0, true);

            newPDFPath = "/clientfiles/groupnotes/" + loadClientID + "/"; // C:\\Users/Darryl/SparkleShare/WestSlopeSecure
            newFile = newPDFPath + firstDayOfWeek.ToString("MM-dd-yyyy") + ".pdf";
            templatePathFromOld = newPDFPath + firstDayOfWeek.ToString("MM-dd-yyyy") + "-old.pdf";

            // Wipe out shit files.
            if (Directory.Exists(newPDFPath))
            {
                foreach (var file in Directory.EnumerateFiles(newPDFPath, "*-old.pdf", SearchOption.TopDirectoryOnly))
                    File.Delete(file);
            }

            processPdfGen();
            DaySelection.SelectedIndex = ((int)(editingDay.DayOfWeek) + 6) % 7;
        }
예제 #5
0
파일: UserController.cs 프로젝트: ICBM/TARS
        public void checkForTimesheet(string userName, DateTime tsDate)
        {
            Authentication auth = new Authentication();
            if (auth.isUser(this) || Authentication.DEBUG_bypassAuth)
            {
                Timesheet resulttimesheet = new Timesheet();
                DateTime startDay = tsDate.StartOfWeek(DayOfWeek.Sunday);

                //Check if there is a timesheet for the week that corresponds to newhours.timestamp
                var searchTs = from m in TimesheetDB.TimesheetList
                               where (m.worker.CompareTo(userName) == 0)
                               where m.periodStart <= tsDate
                               where m.periodEnd >= tsDate
                               select m;
                foreach (var item in searchTs)
                {
                    resulttimesheet = item;
                }

                //if there isn't a timesheet for the pay period, then create one
                //If there is a timesheet for the current pay period, don't do anything
                if (resulttimesheet.periodStart.CompareTo(startDay) != 0)
                {
                    createTimesheet(userName, startDay);
                    return;
                }
                return;
            }
            else
            {
                return;
            }
        }
예제 #6
0
 public void StartOfWeekShouldReturnExpectedResult()
 {
     var date = new DateTime( 2013, 3, 1 );
     var expected = new DateTime( 2013, 2, 24 );
     var actual = date.StartOfWeek();
     Assert.Equal( expected.Date, actual.Date );
 }
        public void StartOfWeekTestCase2()
        {
            var week = new DateTime( 2014, 09, 21 );
            var expected = new DateTime( 2014, 09, 20 );
            var actual = week.StartOfWeek( DayOfWeek.Saturday );

            Assert.AreEqual( expected, actual );
        }
        public void StartOfWeek()
        {
            // Type
            var @this = new DateTime(2014, 04, 16);

            // Examples
            DateTime value = @this.StartOfWeek(); // value = "2013/04/13 00:00:00:000";

            // Unit Test
            Assert.AreEqual(new DateTime(2014, 04, 13), value);
        }
예제 #9
0
        public DateTimeHelper()
        {
            _now = DateTime.Now;
            _todayStartDate = _now.Hour < 4
                ? new DateTime(_now.Year, _now.Month, _now.Day, 4, 0, 0).AddDays(-1)
                : new DateTime(_now.Year, _now.Month, _now.Day, 4, 0, 0);

            _todayEndDate = _todayStartDate.AddHours(24);
            NextDay = _todayEndDate;

            _weekStartDate = _now.StartOfWeek(DayOfWeek.Monday).AddHours(4);
            _weekEndDate = _weekStartDate.AddDays(7);
            NextWeek = _weekEndDate;
        }
예제 #10
0
 public IEnumerable<Task> CreateTasksForWeek(DateTime week)
 {
     var tasks = new List<Task>();
     DateTime weekStart = week.StartOfWeek(DayOfWeek.Monday);
     for (var day = weekStart; (day - weekStart).Days < 7; day = day.AddDays(1))
     {
         if (IncludesDay(day)) tasks.Add(new Task {
             ActivityId = Activity.ActivityId,
             Activity = Activity,
             Start = day,
             Finished = false
         });
     }
     return tasks;
 }
예제 #11
0
        private MemberAttendanceForView GetMemberAttendanceObject(Attendance attendance, List<MemberAttendance> memberAttendances, DateTime weekRequested)
        {
            var mondayDate = weekRequested.StartOfWeek(DayOfWeek.Monday); // DateTime.Now.StartOfWeek(DayOfWeek.Monday);

            return new MemberAttendanceForView
            {
                Attendance = attendance,
                AttendanceId = attendance.AttendanceId,
                MemberAttendances = memberAttendances,
                Projects = _unitOfWork.ProjectRepository.Get().ToList(),
                MondayDate = mondayDate.ToShortDateString(),
                TuesdayDate = mondayDate.AddDays(1).ToShortDateString(),
                WednesdayDate = mondayDate.AddDays(2).ToShortDateString(),
                ThursdayDate = mondayDate.AddDays(3).ToShortDateString(),
                FridayDate = mondayDate.AddDays(4).ToShortDateString(),
                SaturdayDate = mondayDate.AddDays(5).ToShortDateString(),
                SundayDate = mondayDate.AddDays(6).ToShortDateString()
            };
        }
 private DateTime GetLastStartWeek(DateTime lastStart)
 {
     return lastStart.StartOfWeek(DayOfWeek.Monday).AddDays(7).Add(GetLeagueStartTimeSpan());
 }
        //
        /* Retrieves all the employee objects of employees that work for the specified departement 
         * within the Information Technology division (as per client request), then returns them
         * as a list. If department is null, it displays all employees in the division
         */
        public virtual ActionResult userManagement(DateTime refDate, string department = null)
        {
            Authentication auth = new Authentication();
            if (auth.isManager(this) || Authentication.DEBUG_bypassAuth)
            {
                //if it's a redirect from submitRejectTimesheet()
                if (TempData["emailSentFlag"] != null)
                {
                    ViewBag.emailSentFlag = true;
                    ViewBag.messageRecipient = TempData["recipient"];
                }

                string division = getUserDivision();
                IEnumerable<TARSUser> employees = getDivisionEmployeeObjList(division, department);
                ViewBag.division = division;
                ViewBag.departmentList = getDepartmentSelectList(division);
                ViewBag.refDate = refDate;
                ViewBag.refSunday = refDate.StartOfWeek(DayOfWeek.Sunday);
                ViewBag.refPayPeriod = getPayPeriod(refDate);
                return View(employees);
            }
            else
            {
                return View("error");
            }
        }
예제 #14
0
        public void TestStartOfWeek() {
            var wellKnownWeek1 = new DateTime(2009, 2, 11);
            var startOfWellKnownWeek1 = new DateTime(2009, 2, 8);
            var wellKnownWeek2 = new DateTime(2007, 10, 20);
            var startOfWellKnownWeek2 = new DateTime(2007, 10, 14);

            Assert.IsTrue(wellKnownWeek1.StartOfWeek().Equals(startOfWellKnownWeek1));
            Assert.IsTrue(wellKnownWeek2.StartOfWeek().Equals(startOfWellKnownWeek2));
            Assert.IsFalse(wellKnownWeek1.StartOfWeek().Equals(startOfWellKnownWeek2));
            Assert.IsFalse(wellKnownWeek2.StartOfWeek().Equals(startOfWellKnownWeek1));
        }
 public void GivenADateTimeThenReturnThePreviousMondayDateTime(DateTime dateTime, DateTime answer)
 {
     var startOfWeek = dateTime.StartOfWeek();
     Assert.AreEqual(startOfWeek, answer);
 }
 // 
 //Returns the pay period for the reference date as a string
 public virtual string getPayPeriod(DateTime refDate)
 {
     DateTime startDay = refDate.StartOfWeek(DayOfWeek.Sunday);
     DateTime endDay = startDay.AddDays(6);
     string payPeriod = startDay.ToShortDateString() + " - " + endDay.ToShortDateString();
     return payPeriod;
 }
예제 #17
0
 //
 /* Retrieves all TARSUser objects of employees that work for the specified departement 
  * within the Information Technology division and sends them to the view as a list. If 
  * department is null, it retrieves all employees in the division.
  */
 public ActionResult viewTimesheetStatuses(DateTime refDate, string department = null)
 {
     Authentication auth = new Authentication();
     if (auth.isAdmin(this) || Authentication.DEBUG_bypassAuth)
     {
         string division = getUserDivision();
         IEnumerable<TARSUser> employees = getDivisionEmployeeObjList(division, department);
         ViewBag.division = division;
         ViewBag.departmentList = getDepartmentSelectList(division);
         ViewBag.refDate = refDate;
         ViewBag.refSunday = refDate.StartOfWeek(DayOfWeek.Sunday);
         ViewBag.refPayPeriod = getPayPeriod(refDate);
         return View(employees);
     }
     else
     {
         return View("error");
     }
 }
예제 #18
0
        public ScheduleViewModel GenerateSchedule(int userId, DateTime dateFrom, DateTime dateTo)
        {
            var user = DataProvider.Users.FirstOrDefault(p => p.Id == userId);
            if (user == null || (user.Prepod_PrepodMeta == null && user.Student_StudentMeta == null))
                return new ScheduleViewModel();

            List<IGrouping<DateTime, Raspisanie>> schedulesDateGroups;

            dateFrom = new DateTime(dateFrom.Year, dateFrom.Month, dateFrom.Day);
            dateTo = new DateTime(dateTo.Year, dateTo.Month, dateTo.Day);

            #region Правка даты

            if (dateTo.WeeksInYear() != dateFrom.WeeksInYear())
            {
                dateFrom = dateFrom.StartOfWeek(DayOfWeek.Monday);
                dateTo = dateTo.EndOfWeek(DayOfWeek.Saturday);
            }

            #endregion

            #region Условия для отбора данных из базы

            if (user.Prepod_PrepodMeta != null && user.Prepod_PrepodMeta.Any())
            {

                var prepodIds = DataProvider.PrepodiCafedri.Filter(p => p.Prepod_PrepodMeta.UserId == userId)
                                           .Select(p => p.Id);

                schedulesDateGroups = DataProvider.Raspisanie.Filter(p => prepodIds.Contains(p.IdPrepodaCafedri) && p.Data >= dateFrom && p.Data <= dateTo)

                                                 .GroupBy(p => p.Data)
                                                 .OrderBy(p => p.Key)
                                                 .ToList();

            }

            else
            {
                var userGroup = user.Student_StudentMeta.FirstOrDefault()
                                    .SostavGrupp.OrderByDescending(p => p.DateEdit)
                                               .FirstOrDefault();

                var flow = userGroup.SpisokGrupp.Pot;
                var groupId = userGroup.SpisokGrupp.IdGroup;
                var subGroup = userGroup.Podgroup;
                var specialityId = userGroup.SpisokGrupp.IdSpezMeta;
                //var formOfStudy = user.Student_StudentMeta.FirstOrDefault().FormOfStuduId;
                schedulesDateGroups = DataProvider.Raspisanie.Filter(p => p.Data >= dateFrom &&
                                                                           p.Data <= dateTo &&
                                                                           p.SpezialRazdeliDisziplini.IdSpezMeta == specialityId &&
                                                                           p.Pot == flow &&
                                                                           (!p.IdSpiskaGrupp.HasValue || p.IdSpiskaGrupp == groupId) &&
                                                                           (!p.NomerPodGrupp.HasValue || p.NomerPodGrupp == subGroup)
                                                                          )
                                                .GroupBy(p => p.Data)
                                                .OrderBy(p => p.Key)
                                                .ToList();
            }

            #endregion

            #region Отбор заметок

            var notifications = DataProvider.Notifications.Filter(p => userId == p.UserId && p.Date >= dateFrom && p.Date <= dateTo).ToList();

            #endregion

            var daysCount = (dateTo - dateFrom).Days + 1;

            var scheduleViewModel = new ScheduleViewModel()
            {
                DaysCount = daysCount,
                DateFrom = dateFrom.ToString("yyyy-MM-dd")
            };

            ScheduleWeekViewModel scheduleWeek = new ScheduleWeekViewModel();
            var scheduleDay = new ScheduleDayViewModel();
            var totalCount = schedulesDateGroups.Count;

            int maxLessonsInSimilarTime = 0;

            DateTime dateOfDay = new DateTime();
            List<string> lessonsTimes = new List<string>();

            #region Формируем расписание

            foreach (var schedulesDateGroup in schedulesDateGroups)
            {
                dateOfDay = schedulesDateGroup.Key;
                scheduleDay.DateOfDay = dateOfDay.ToString("yyyy-MM-dd");
                scheduleDay.IsCurrentDay = dateOfDay == DateTime.Now.Date;
                scheduleDay.IsPast = dateOfDay == DateTime.Now.Date;

                #region Добавляем уроки

                scheduleDay.Lessons = schedulesDateGroup.OrderBy(p => p.VremyaZanyatia.StartTime)
                                                   .Select(LessonViewModel.ToLessonViewModel)
                                                   .ToList();
                #endregion

                #region Добавляем заметки

                scheduleDay.Notifications = notifications.Where(p => p.Date == schedulesDateGroup.Key).OrderBy(p => p.IdVremyaZanyatia).Select(NotificationViewModel.ToNotificationViewModel).ToList();

                #endregion

                var tempCount = scheduleDay.Lessons.GroupBy(p => p.LessonTime).Select(p => p.Count()).Max(p => p);
                maxLessonsInSimilarTime = maxLessonsInSimilarTime < tempCount ? tempCount : maxLessonsInSimilarTime;

                lessonsTimes.AddRange(scheduleDay.Lessons.Select(p => p.LessonTime));
                lessonsTimes.AddRange(scheduleDay.Notifications.Select(p => p.NotificationTime));

                switch (dateOfDay.DayOfWeek)
                {
                    case DayOfWeek.Monday:
                        scheduleWeek.Monday = scheduleDay;
                        break;
                    case DayOfWeek.Tuesday:
                        scheduleWeek.Tuesday = scheduleDay;
                        break;
                    case DayOfWeek.Wednesday:
                        scheduleWeek.Wednesday = scheduleDay;
                        break;
                    case DayOfWeek.Thursday:
                        scheduleWeek.Thursday = scheduleDay;
                        break;
                    case DayOfWeek.Friday:
                        scheduleWeek.Friday = scheduleDay;
                        break;
                    case DayOfWeek.Saturday:
                        scheduleWeek.Saturday = scheduleDay;
                        break;
                }

                //если один день то сразу в новую неделю
                if (daysCount == 1)
                {
                    scheduleViewModel.Weeks.Add(scheduleWeek);
                }
                //если суббота или последняя запись то  сохраняем неделю и созаем новую
                if (dateOfDay.DayOfWeek == DayOfWeek.Saturday || schedulesDateGroups.IndexOf(schedulesDateGroup) == totalCount - 1 || schedulesDateGroup.Key.WeeksInYear() != schedulesDateGroups[schedulesDateGroups.IndexOf(schedulesDateGroup) + 1].Key.WeeksInYear())
                {
                    scheduleViewModel.Weeks.Add(scheduleWeek);
                    scheduleWeek = new ScheduleWeekViewModel();
                }
                scheduleDay = new ScheduleDayViewModel();
            }

            #endregion

            List<string> lessons = lessonsTimes.Distinct().OrderBy(p => p).ToList();
            List<string> finalLessons = new List<string>();

            Dictionary<int, string> list = DataProvider.VremyaZanyatia.GetAllNoTracking().AsEnumerable().Select(x => new
            {
                Id = x.Id,
                Name = x.StartTime.ToString("H.mm") + '-' + x.EndTime.ToString("H.mm")
            }).AsEnumerable().ToDictionary(x => x.Id, x => x.Name);

            bool isExist = false;
            for (int i = 1; i <= list.Count; i++)
            {
                for (int j = 0; j < lessons.Count; j++)
                {
                    if (list[i] == lessons[j])
                    {
                        isExist = true;
                        break;
                    }
                }

                if (isExist)
                    finalLessons.Add(list[i]);

                isExist = false;
            }
            scheduleViewModel.MaxLessonsInSimilarTime = maxLessonsInSimilarTime;
            scheduleViewModel.LessonsTime = finalLessons;

            return scheduleViewModel;
        }
예제 #19
0
        public static DateTime StartOfWeek( this Calendar calendar, DateTime date, DayOfWeek firstDayOfWeek )
        {
            Arg.NotNull( calendar, nameof( calendar ) );

            return date.StartOfWeek( firstDayOfWeek );
        }
예제 #20
0
파일: TableSalg.cs 프로젝트: tborgund/kgsa
 public DataTable GetWeeklySales(int avdeling, DateTime date)
 {
     string sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + KEY_AVDELING + " = " + avdeling
         + " AND CONVERT(NVARCHAR(10)," + KEY_DATO + ",121) >= CONVERT(NVARCHAR(10),'" + date.StartOfWeek().ToString("yyyy-MM-dd")
         + "',121) AND CONVERT(NVARCHAR(10)," + KEY_DATO + ",121) <= CONVERT(NVARCHAR(10),'" + date.EndOfWeek().ToString("yyyy-MM-dd") + "',121)";
     DataTable table = main.database.GetSqlDataTable(sql);
     if (table != null)
         table.Columns.Add("SalgsprisExMva", typeof(double), "Salgspris / Mva");
     return table;
 }
예제 #21
0
        public static DateTime StartOfWeek( this Calendar calendar, DateTime date )
        {
            Arg.NotNull( calendar, nameof( calendar ) );

            return date.StartOfWeek( CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek );
        }
예제 #22
0
        /// <summary>
        /// 轉換為課程行事曆
        /// </summary>
        /// <param name="SchoolYearSemesterDates"></param>
        /// <returns></returns>
        public void CreateClassBusy(
            DateTime dteStart,
            DateTime dteEnd,
            Dictionary<string,ClassEx> Classes)
        {
            ClassBusyDates = new List<ClassBusyDate>();

            if (!Classes.ContainsKey(this.ClassName))
            {
                TransferComment = "此筆資料找不到系統中對應的班級,無法進行轉換。";
                return;
            }

            int StartWeekday = dteStart.GetWeekday();
            DateTime dteStartWeekday = dteStart.StartOfWeek(DayOfWeek.Monday);
            int intWeekday = K12.Data.Int.Parse(Weekday);
            dteStartWeekday = intWeekday < StartWeekday ? dteStartWeekday = dteStartWeekday.AddDays(7).AddDays(intWeekday - 1) : dteStartWeekday = dteStartWeekday.AddDays(intWeekday - 1);

            while (dteStartWeekday <= dteEnd)
            {
                ClassBusyDate vClassBusyDate = new ClassBusyDate();

                DateTime StartDateTime = new DateTime();
                DateTime EndDateTime = new DateTime();

                DateTime.TryParse(dteStartWeekday.ToShortDateString() + " " + StartTime, out StartDateTime);
                DateTime.TryParse(dteStartWeekday.ToShortDateString() + " " + EndTime, out EndDateTime);

                vClassBusyDate.WeekDay = K12.Data.Int.Parse(Weekday);
                vClassBusyDate.Period = K12.Data.Int.Parse(Period);
                vClassBusyDate.BeginDateTime = StartDateTime;
                vClassBusyDate.EndDateTime = EndDateTime;
                vClassBusyDate.BusyDesc = Desc;
                vClassBusyDate.ClassID = K12.Data.Int.Parse(Classes[ClassName].UID);
                ClassBusyDates.Add(vClassBusyDate);

                dteStartWeekday = dteStartWeekday.AddDays(7);
            }
            if (ClassBusyDates.Count > 0)
                TransferComment = "此筆資料已產生" + ClassBusyDates.Count + "筆班級不調代時段;開始日期為" + ClassBusyDates[0].BeginDateTime.ToShortDateString() + "、結束日期為" + ClassBusyDates[ClassBusyDates.Count - 1].BeginDateTime.ToShortDateString();
            else
                TransferComment = "此筆資料未產生班級不調代時段";
        }
예제 #23
0
            public void StartOfWeek()
            {
                var anyDate = new DateTime(2014, 1, 3, 3, 24, 50);
                var expectedResult = new DateTime(2013, 12, 29, 0, 0, 0);

                Assert.Equal(expectedResult, anyDate.StartOfWeek());
            }
예제 #24
0
        private void UpdateAttendance(MemberAttendanceForView memberAttendanceData, int projectId, DateTime weekRequested)
        {
            var weekSought = weekRequested.GetWeek();
            var yearSought = weekRequested.Year;

            bool isInsert = memberAttendanceData.AttendanceId == -1;

            Attendance attendance;

            if (isInsert) //that means its an INSERT
            {
                attendance = new Attendance
                    {
                        ProjectId = projectId,
                        CreatedBy = User.Identity.Name,
                        CreatedOn = DateTime.UtcNow,
                        Year = yearSought,
                        Week = weekSought,
                        WeekString = GetDisplayWeek(weekRequested.StartOfWeek(DayOfWeek.Monday))
                    };

                using (var scope = new TransactionScope())
                {
                    try
                    {
                        _unitOfWork.AttendanceRepository.Insert(attendance);
                        _unitOfWork.Save();

                        foreach (var item in memberAttendanceData.MemberAttendances)
                        {
                            var newMembAtt = GetNewMemberAttendance(attendance.AttendanceId, item);

                            _unitOfWork.MemberAttendanceRepository.Insert(newMembAtt);
                        }

                        _unitOfWork.Save();
                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        scope.Dispose();
                        //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                        Utility.WriteToLog("AttendanceController.UpdateAttendance() : " + ex, "Error");
                        throw new Exception(ex.Message);
                    }
                }
            }
            else
            {
                attendance = _unitOfWork.AttendanceRepository.GetById(memberAttendanceData.AttendanceId);

                attendance.ModifiedBy = User.Identity.Name;
                attendance.ModifiedOn = DateTime.UtcNow;

                try
                {
                    _unitOfWork.AttendanceRepository.Update(attendance);
                    _unitOfWork.Save();

                    foreach (var item in memberAttendanceData.MemberAttendances)
                    {
                        var item1 = item;
                        var memberAttendance = _unitOfWork.MemberAttendanceRepository.Get(filter: x => x.MemberId == item1.Member.MemberId && x.AttendanceId == attendance.AttendanceId).ToList();
                        if (memberAttendance.Any())
                        {
                            var dataToUpdate = memberAttendance[0];
                            UpdateMemberAttendanceData(item1, dataToUpdate);
                            _unitOfWork.MemberAttendanceRepository.Update(dataToUpdate);
                        }
                    }
                    _unitOfWork.Save();
                }
                catch (Exception ex)
                {
                    //scope.Dispose();
                    //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                    Utility.WriteToLog("AttendanceController.UpdateAttendance() : " + ex, "Error");
                    throw new Exception(ex.Message);
                }
            }
        }
예제 #25
0
        public void WeekStart()
        {
            DateTime d = new DateTime(2010, 6, 15);
            Assert.AreEqual(new DateTime(2010,6,13), d.StartOfWeek());

            DateTime d1 = new DateTime(2010, 6, 15,1,2,3);
            Assert.AreEqual(new DateTime(2010, 6, 13), d1.StartOfWeek());

            DateTime d2 = new DateTime(2010, 6, 20);
            Assert.AreEqual(new DateTime(2010, 6, 20), d2.StartOfWeek());
        }
예제 #26
0
 public void DateTimeStartOfWeek()
 {
     DateTime dt = new DateTime(2013,2,1);
     var start = dt.StartOfWeek(DayOfWeek.Monday);
     Assert.AreEqual(new DateTime(2013, 1, 28), start);
 }
예제 #27
0
 //
 /* Retrieves all holidays that are within the same pay period as the specified
  * reference date. If the search results in an empty list, then FALSE is returned.
  * If there is at least one holiday in the list, then TRUE is returned.
  */
 public bool isHolidayWeek(DateTime refDate)
 {
     DateTime refStart = refDate.StartOfWeek(DayOfWeek.Sunday);
     DateTime refEnd = refStart.AddDays(7);
     var searchHolidays = from h in HolidaysDB.HolidaysList
                          where h.date >= refStart
                          where h.date < refEnd
                          select h;
     foreach (var item in searchHolidays)
     {
         return true;
     }
     return false;
 }
예제 #28
0
        /// <summary>
        /// pnl : 整個課表的 container
        /// schType : 課表類型
        /// 
        /// </summary>
        /// <param name="pnl"></param>
        /// <param name="schType"></param>
        public DecCalendar(DevComponents.DotNetBar.PanelEx pnl)
        {
            pnl.Tag = this;

            #region 註冊事件
            CalendarEvents.ReplaceEvent += (sender, e) => UpdateContent();
            CalendarEvents.ExchangeEvent += (sender, e) =>
            {
                this.SelectedCalendars = new List<CalendarRecord>();
                UpdateContent();
            };
            CalendarEvents.WeekChangeEvent += (vsender, ve) =>
            {
                if (ve.Type.Equals(this.Type) &&
                    ve.AssocID.Equals(this.AssocID))
                {
                    this.SelectedCalendars = new List<CalendarRecord>();
                    this.UpdateContent();
                }
            };
            CalendarEvents.WeekdayPeriodChangeEvent += CalendarEvents_WeekdayPeriodChangeEvent;
            #endregion

            #region 建立元件
            pnl.Controls.Clear();

            PanelEx pnlCalendarControl = makePanel(string.Empty, string.Empty, new Point(), new Size(10,50));
            pnlCalendarControl.Dock = DockStyle.Top;

            btnPrevious = CreateButton(new Size(50, 25));
            btnNext = CreateButton(new Size(50, 25));

            btnPrevious.Text = "上週";
            btnPrevious.Location = new Point(10, 10);
            btnPrevious.Click += (sender, e) =>
            {
                SchoolYearSemesterOption.Instance.StartDate = SchoolYearSemesterOption.Instance.StartDate.AddDays(-7);
                SchoolYearSemesterOption.Instance.EndDate = SchoolYearSemesterOption.Instance.EndDate.AddDays(-7);
                CalendarEvents.RaiseWeekChangeEvent(this.Type,this.AssocID);
            };

            btnNext.Text = "下週";
            btnNext.Location = new Point(70, 10);
            btnNext.Click += (sender, e) =>
            {
                SchoolYearSemesterOption.Instance.StartDate = SchoolYearSemesterOption.Instance.StartDate.AddDays(7);
                SchoolYearSemesterOption.Instance.EndDate = SchoolYearSemesterOption.Instance.EndDate.AddDays(7);
                CalendarEvents.RaiseWeekChangeEvent(this.Type,this.AssocID);
            };

            btnCurrent = CreateButton(new Size(50, 25));
            btnCurrent.Text = "本週";
            btnCurrent.Location = new Point(130, 10);
            btnCurrent.Click += (sender,e)=>
            {
                SchoolYearSemesterOption.Instance.StartDate = DateTime.Now.StartOfWeek(DayOfWeek.Monday).ToDayStart();
                SchoolYearSemesterOption.Instance.EndDate = SchoolYearSemesterOption.Instance.StartDate.AddDays(6);
                CalendarEvents.RaiseWeekChangeEvent(this.Type,this.AssocID);
            };

            ButtonX btnPrint = CreateButton(new Size(50, 25));
            btnPrint.Location = new Point(190,10);
            btnPrint.Text = "列印";
            btnPrint.Click += (sender,e)=>
            {
                if (this.Type.Equals(CalendarType.Teacher))
                {
                    List<CalendarRecord> QueryResult = new List<CalendarRecord>();

                    DateTime dteStart = SchoolYearSemesterOption.Instance.StartDate;
                    DateTime dteEnd = SchoolYearSemesterOption.Instance.EndDate;
                    List<string> SelectedClassNames = new List<string>();
                    List<string> SelectedTeacherNames = new List<string>(){AssocID};

                    BackgroundWorker worker = new BackgroundWorker();

                    worker.DoWork += (vsender, ve) =>
                    {
                        #region 找出調課記錄
                        List<CalendarRecord> ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null,
                        null, null, null, null, null);

                        List<CalendarRecord> ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null);

                        Dictionary<string, CalendarRecord> Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出代課記錄
                        List<CalendarRecord> RepRecords = Calendar.Instance.FindReplaceRecords(
                            SelectedTeacherNames, null, SelectedClassNames, null, dteStart, dteEnd);

                        List<CalendarRecord> AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, SelectedTeacherNames, SelectedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);
                        #endregion

                        QueryResult.AddRange(Records.Values);

                        List<CalendarRecord> RelatedQueryResult = new List<CalendarRecord>();

                        List<string> RelatedClassNames = new List<string>();
                        List<string> RelatedTeacherNames = new List<string>();

                        foreach (CalendarRecord record in Records.Values)
                        {
                            if (!string.IsNullOrWhiteSpace(record.ReplaceID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.AbsTeacherName);
                            }

                            if (!string.IsNullOrWhiteSpace(record.ExchangeID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);

                                if (record.ExchangeCalendar!=null)
                                    RelatedTeacherNames.Add(record.ExchangeCalendar.TeacherName);
                            }
                        }

                        RelatedTeacherNames = RelatedTeacherNames.Distinct().ToList();
                        RelatedClassNames = RelatedClassNames.Distinct().ToList();
                        QueryResult.Clear();

                        #region 找出相關調課記錄
                        ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, RelatedTeacherNames, RelatedClassNames, null,
                        null, null, null, null, null);

                        ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, RelatedTeacherNames, RelatedClassNames, null);

                        Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出相關代課記錄
                        RepRecords = Calendar.Instance.FindReplaceRecords(
                            RelatedTeacherNames, null, RelatedClassNames, null, dteStart, dteEnd);

                        AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, RelatedTeacherNames, RelatedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion
                    };

                    worker.RunWorkerCompleted += (vsender, ve) =>
                    {
                        ExchangeReplaceReport.Instance.Print(QueryResult, dteStart, dteEnd);
                        MotherForm.SetStatusBarMessage(string.Empty);
                        btnPrint.Enabled = true;
                    };

                    worker.RunWorkerAsync();
                    MotherForm.SetStatusBarMessage("取得報表資料中!");
                    btnPrint.Enabled = false;
                }
                else if (this.Type.Equals(CalendarType.Class))
                {
                    List<CalendarRecord> QueryResult = new List<CalendarRecord>();

                    DateTime dteStart = SchoolYearSemesterOption.Instance.StartDate;
                    DateTime dteEnd = SchoolYearSemesterOption.Instance.EndDate;
                    List<string> SelectedClassNames = new List<string>() { AssocID };
                    List<string> SelectedTeacherNames = new List<string>();

                    BackgroundWorker worker = new BackgroundWorker();

                    worker.DoWork += (vsender, ve) =>
                    {
                        #region 找出調課記錄
                        List<CalendarRecord> ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null,
                        null, null, null, null, null);

                        List<CalendarRecord> ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null);

                        Dictionary<string, CalendarRecord> Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出代課記錄
                        List<CalendarRecord> RepRecords = Calendar.Instance.FindReplaceRecords(
                            SelectedTeacherNames, null, SelectedClassNames, null, dteStart, dteEnd);

                        List<CalendarRecord> AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, SelectedTeacherNames, SelectedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);
                        #endregion

                        QueryResult.AddRange(Records.Values);

                        List<CalendarRecord> RelatedQueryResult = new List<CalendarRecord>();

                        List<string> RelatedClassNames = new List<string>();
                        List<string> RelatedTeacherNames = new List<string>();

                        foreach (CalendarRecord record in Records.Values)
                        {
                            if (!string.IsNullOrWhiteSpace(record.ReplaceID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.AbsTeacherName);
                            }

                            if (!string.IsNullOrWhiteSpace(record.ExchangeID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.ExchangeCalendar.TeacherName);
                            }
                        }

                        RelatedTeacherNames = RelatedTeacherNames.Distinct().ToList();
                        RelatedClassNames = RelatedClassNames.Distinct().ToList();
                        QueryResult.Clear();

                        #region 找出相關調課記錄
                        ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, RelatedTeacherNames, null, null,
                        null, null, null, null, null);

                        ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, RelatedTeacherNames, null, null);

                        Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出相關代課記錄
                        RepRecords = Calendar.Instance.FindReplaceRecords(
                            RelatedTeacherNames, null, null, null, dteStart, dteEnd);

                        AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, RelatedTeacherNames, null, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion
                    };

                    worker.RunWorkerCompleted += (vsender, ve) =>
                    {
                        ExchangeReplaceReport.Instance.Print(QueryResult, dteStart, dteEnd);
                        MotherForm.SetStatusBarMessage(string.Empty);
                        btnPrint.Enabled = true;
                    };

                    worker.RunWorkerAsync();
                    MotherForm.SetStatusBarMessage("取得報表資料中!");
                    btnPrint.Enabled = false;
                }
            };

            ButtonItem btnPrintAll = new ButtonItem("列印所有", "列印所有");

            btnPrintAll.Click += (sender, e) =>
            {
                if (this.Type.Equals(CalendarType.Teacher))
                {
                    List<CalendarRecord> QueryResult = new List<CalendarRecord>();

                    DateTime dteStart = SchoolYearSemesterOption.Instance.StartDate;
                    DateTime dteEnd = SchoolYearSemesterOption.Instance.EndDate;
                    List<string> SelectedClassNames = new List<string>();
                    List<string> SelectedTeacherNames = new List<string>();

                    BackgroundWorker worker = new BackgroundWorker();

                    worker.DoWork += (vsender, ve) =>
                    {
                        #region 找出調課記錄
                        List<CalendarRecord> ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null,
                        null, null, null, null, null);

                        List<CalendarRecord> ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null);

                        Dictionary<string, CalendarRecord> Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出代課記錄
                        List<CalendarRecord> RepRecords = Calendar.Instance.FindReplaceRecords(
                            SelectedTeacherNames, null, SelectedClassNames, null, dteStart, dteEnd);

                        List<CalendarRecord> AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, SelectedTeacherNames, SelectedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);
                        #endregion

                        QueryResult.AddRange(Records.Values);

                        List<CalendarRecord> RelatedQueryResult = new List<CalendarRecord>();

                        List<string> RelatedClassNames = new List<string>();
                        List<string> RelatedTeacherNames = new List<string>();

                        foreach (CalendarRecord record in Records.Values)
                        {
                            if (!string.IsNullOrWhiteSpace(record.ReplaceID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.AbsTeacherName);
                            }

                            if (!string.IsNullOrWhiteSpace(record.ExchangeID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.ExchangeCalendar.TeacherName);
                            }
                        }

                        RelatedTeacherNames = RelatedTeacherNames.Distinct().ToList();
                        RelatedClassNames = RelatedClassNames.Distinct().ToList();
                        QueryResult.Clear();

                        #region 找出相關調課記錄
                        ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, RelatedTeacherNames, RelatedClassNames, null,
                        null, null, null, null, null);

                        ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, RelatedTeacherNames, RelatedClassNames, null);

                        Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出相關代課記錄
                        RepRecords = Calendar.Instance.FindReplaceRecords(
                            RelatedTeacherNames, null, RelatedClassNames, null, dteStart, dteEnd);

                        AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, RelatedTeacherNames, RelatedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion
                    };

                    worker.RunWorkerCompleted += (vsender, ve) =>
                    {
                        ExchangeReplaceReport.Instance.Print(QueryResult, dteStart, dteEnd);
                        MotherForm.SetStatusBarMessage(string.Empty);
                        btnPrint.Enabled = true;
                    };

                    worker.RunWorkerAsync();
                    MotherForm.SetStatusBarMessage("取得報表資料中!");
                    btnPrint.Enabled = false;
                }
                else if (this.Type.Equals(CalendarType.Class))
                {
                    List<CalendarRecord> QueryResult = new List<CalendarRecord>();

                    DateTime dteStart = SchoolYearSemesterOption.Instance.StartDate;
                    DateTime dteEnd = SchoolYearSemesterOption.Instance.EndDate;
                    List<string> SelectedClassNames = new List<string>();
                    List<string> SelectedTeacherNames = new List<string>();

                    BackgroundWorker worker = new BackgroundWorker();

                    worker.DoWork += (vsender, ve) =>
                    {
                        #region 找出調課記錄
                        List<CalendarRecord> ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null,
                        null, null, null, null, null);

                        List<CalendarRecord> ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, SelectedTeacherNames, SelectedClassNames, null);

                        Dictionary<string, CalendarRecord> Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出代課記錄
                        List<CalendarRecord> RepRecords = Calendar.Instance.FindReplaceRecords(
                            SelectedTeacherNames, null, SelectedClassNames, null, dteStart, dteEnd);

                        List<CalendarRecord> AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, SelectedTeacherNames, SelectedClassNames, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);
                        #endregion

                        QueryResult.AddRange(Records.Values);

                        List<CalendarRecord> RelatedQueryResult = new List<CalendarRecord>();

                        List<string> RelatedClassNames = new List<string>();
                        List<string> RelatedTeacherNames = new List<string>();

                        foreach (CalendarRecord record in Records.Values)
                        {
                            if (!string.IsNullOrWhiteSpace(record.ReplaceID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.AbsTeacherName);
                            }

                            if (!string.IsNullOrWhiteSpace(record.ExchangeID))
                            {
                                RelatedClassNames.Add(record.ClassName);
                                RelatedTeacherNames.Add(record.TeacherName);
                                RelatedTeacherNames.Add(record.ExchangeCalendar.TeacherName);
                            }
                        }

                        RelatedTeacherNames = RelatedTeacherNames.Distinct().ToList();
                        RelatedClassNames = RelatedClassNames.Distinct().ToList();
                        QueryResult.Clear();

                        #region 找出相關調課記錄
                        ExchangeARecords = Calendar.Instance.FindExchangeRecords(
                        dteStart, dteEnd, RelatedTeacherNames, null, null,
                        null, null, null, null, null);

                        ExchangeBRecords = Calendar.Instance.FindExchangeRecords(
                        null, null, null, null, null,
                        dteStart, dteEnd, RelatedTeacherNames, null, null);

                        Records = new Dictionary<string, CalendarRecord>();

                        foreach (CalendarRecord ExchangeRecord in ExchangeARecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        foreach (CalendarRecord ExchangeRecord in ExchangeBRecords)
                            if (!Records.ContainsKey(ExchangeRecord.UID))
                                Records.Add(ExchangeRecord.UID, ExchangeRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion

                        #region 找出相關代課記錄
                        RepRecords = Calendar.Instance.FindReplaceRecords(
                            RelatedTeacherNames, null, null, null, dteStart, dteEnd);

                        AbsRecords = Calendar.Instance.FindReplaceRecords(
                            null, RelatedTeacherNames, null, null, dteStart, dteEnd);

                        foreach (CalendarRecord RepRecord in RepRecords)
                            if (!Records.ContainsKey(RepRecord.UID))
                                Records.Add(RepRecord.UID, RepRecord);

                        foreach (CalendarRecord AbsRecord in AbsRecords)
                            if (!Records.ContainsKey(AbsRecord.UID))
                                Records.Add(AbsRecord.UID, AbsRecord);

                        QueryResult.AddRange(Records.Values);
                        #endregion
                    };

                    worker.RunWorkerCompleted += (vsender, ve) =>
                    {
                        ExchangeReplaceReport.Instance.Print(QueryResult, dteStart, dteEnd);
                        MotherForm.SetStatusBarMessage(string.Empty);
                        btnPrint.Enabled = true;
                    };

                    worker.RunWorkerAsync();
                    MotherForm.SetStatusBarMessage("取得報表資料中!");
                    btnPrint.Enabled = false;
                }
            };

            btnPrint.SubItems.Add(btnPrintAll);

            ButtonItem btnSetting = new ButtonItem("設定", "設定");

            btnSetting.Click += (sender, e) =>
            {
                #region 讀取 Preference
                ConfigData configExchagne = K12.Data.School.Configuration["調代課通知單"];

                if (configExchagne != null)
                {
                    int _useTemplateNumber = 0;
                    int.TryParse(configExchagne["TemplateNumber"], out _useTemplateNumber);

                    string customize = configExchagne["CustomizeTemplate"];
                    byte[] _buffer = Resources.調代課通知單;

                    if (!string.IsNullOrEmpty(customize))
                        _buffer = Convert.FromBase64String(customize);
                    frmExchangeReplaceTemplateConfig frmConfig = new frmExchangeReplaceTemplateConfig(
                        _buffer,
                        _useTemplateNumber);

                    frmConfig.ShowDialog();
                }
                #endregion

                //switch (mCalendarType)
                //{
                //    case CalendarType.Teacher:
                //        new frmCalendarOption(CalendarOption.GetTeacherOption()).ShowDialog();
                //        break;
                //    case CalendarType.Class:
                //        new frmCalendarOption(CalendarOption.GetClassOption()).ShowDialog();
                //        break;
                //    case CalendarType.Classroom:
                //        new frmCalendarOption(CalendarOption.GetClassroomOption()).ShowDialog();
                //        break;
                //}
            };
            btnPrint.SubItems.Add(btnSetting);

            if (CalendarOption.PrintExtraButtons.Count > 0)
            {
                foreach (ButtonItem vButton in CalendarOption.PrintExtraButtons)
                    btnPrint.SubItems.Add(vButton);
            }

            ErrorProvider errProvier = new ErrorProvider();

            DateTime dt = new DateTime();

            lblName.Name = "lblTitle";
            lblName.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square;
            lblName.Font = new System.Drawing.Font("新細明體", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            lblName.Location = new Point(240, 13);
            lblName.AutoSize = true;

            txtStartDate.Font = new System.Drawing.Font("新細明體", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            txtStartDate.Location = new Point(380, 13);
            txtStartDate.Width = 40;
            txtStartDate.TextChanged += (sender, e) =>
            {
              string value = txtStartDate.Text;
                if (string.IsNullOrEmpty(value)) //沒有資料就不作任何檢查。
                    return;

                if (!DateTime.TryParse(value, out dt))
                {
                    errProvier.SetError(txtStartDate, "日期格式錯誤。");
                }
                else
                {
                    errProvier.Clear();
                }
            };
            txtStartDate.KeyPress += (sender, e) =>
            {
                if (e.KeyChar.Equals((char)Keys.Return))
                {
                    SchoolYearSemesterOption.Instance.StartDate = dt.StartOfWeek(DayOfWeek.Monday);
                    SchoolYearSemesterOption.Instance.EndDate = SchoolYearSemesterOption.Instance.StartDate.AddDays(6);
                    txtStartDate.Text = SchoolYearSemesterOption.Instance.StartDate.Month + "/" + SchoolYearSemesterOption.Instance.StartDate.Day;
                    CalendarEvents.RaiseWeekChangeEvent(this.Type,this.AssocID);
                }
            };

            lblEndDate.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square;
            lblEndDate.Font = new System.Drawing.Font("新細明體", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
            lblEndDate.Location = new Point(420, 13);
            lblEndDate.AutoSize = true;

            pnlCalendarControl.Controls.Add(btnPrint);
            pnlCalendarControl.Controls.Add(txtStartDate);
            pnlCalendarControl.Controls.Add(lblName);
            pnlCalendarControl.Controls.Add(lblEndDate);
            pnlCalendarControl.Controls.Add(btnPrevious);
            pnlCalendarControl.Controls.Add(btnCurrent);
            pnlCalendarControl.Controls.Add(btnNext);

            PanelEx pnlCalendarContent = new PanelEx();
            pnlCalendarContent.Dock = DockStyle.Fill;

            pnl.Controls.Add(pnlCalendarContent);
            pnl.Controls.Add(pnlCalendarControl);

            this.pnlContainer = pnlCalendarContent;
            this.pnlContainer.Resize += (sender, e) => Resize();
            this.cells = new Dictionary<string, DevComponents.DotNetBar.PanelEx>();
            this.decPeriods = new Dictionary<string, DecPeriod>();
            this.headerCells = new Dictionary<string, DevComponents.DotNetBar.PanelEx>();

            ContextMenu Menu = new ContextMenu();
            this.pnlContainer.ContextMenu = Menu;
            Menu.Popup += Menu_Popup;
            #endregion

            #region 星期節次
            Campus.Configuration.ConfigData config = Campus.Configuration.Config.User["CalendarOption"];

            string vWeekday = config["Weekday"];
            string vPeriods = config["PeriodList"];

            if (!string.IsNullOrWhiteSpace(vWeekday))
                this.weekday = K12.Data.Int.Parse(vWeekday);
            else
                this.weekday = 5;

            this.periods = Utility.GetPeriodList(vPeriods);
            this.RedrawGrid();
            #endregion
        }
예제 #29
0
 private DateTime ResolveStartDate ( DateTime currentDate, ZoomLevel period, UserData usr)
 {
     DateTime result;
     if (period == ZoomLevel.Week) {
         result = currentDate.StartOfWeek (usr.StartOfWeek);
     } else if (period == ZoomLevel.Month) {
         result = new DateTime (currentDate.Year, currentDate.Month, 1);
     } else {
         result = new DateTime (currentDate.Year, 1, 1);
     }
     return result;
 }