Beispiel #1
1
        public IReadOnlyCollection<Week> GetByWeeks()
        {
            var weeks = new List<Week>(366 / 7 + 1);
            Week currentWeek = null;

            var currentDate = new DateTime(Year, 1, 1);

            do
            {
                if (currentDate.DayOfWeek == DayOfWeek.Monday ||
                    currentWeek == null)
                {
                    var dateForMonth = DateTime.DaysInMonth(currentDate.Year, currentDate.Month) - currentDate.Day < 3 ? currentDate.AddMonths(1) : currentDate;
                    currentWeek = new Week
                    {
                        Month = dateForMonth.ToString("MMMM", new CultureInfo("ru"))
                    };
                    weeks.Add(currentWeek);
                }

                var dayIndex = GetDayOfWeekIndex(currentDate.DayOfWeek);
                Day day;
                if (Days.TryGetValue(currentDate, out day))
                {
                    currentWeek.Days[dayIndex] = day;
                }
                currentWeek.Dates[dayIndex] = currentDate.Date;

                currentDate = currentDate.AddDays(1);
            } while (currentDate.Year == Year);

            return weeks;
        }
        public void LoadData()
        {
            XElement rootElement = _xml.Element(XName.Get("Credits"));

            foreach (XElement xmlHelper in rootElement.Element(XName.Get("UnderlyingHelpers")).Descendants(XName.Get("Helper")))
            {
                AllHelpers.Add(new Helper(xmlHelper));
            }

            foreach (XElement xmlWeek in rootElement.Descendants(XName.Get("Week")))
            {
                Week week = new Week();
                week.ID = xmlWeek.Attribute(XName.Get("id")).Value.ToInt();

                foreach (XElement xmlTopic in xmlWeek.Descendants(XName.Get("Topic")))
                {
                    int topicID = xmlTopic.Attribute(XName.Get("id")).Value.ToInt();
                    string topicDescription = xmlTopic.Value;

                    KeyValuePair<int, string> topic = new KeyValuePair<int, string>(topicID, topicDescription);
                    week.Topics.Add(topic);
                }

                foreach (XElement xmlStudent in xmlWeek.Descendants(XName.Get("Student")))
                {
                    Student student = new Student();
                    student.ID = xmlStudent.Attribute(XName.Get("id")).Value.ToInt();
                    student.FirstName = xmlStudent.Element(XName.Get("FirstName")).Value;
                    student.LastName = xmlStudent.Element(XName.Get("LastName")).Value;

                    KeyValuePair<Week, Student> weekStudent = new KeyValuePair<Week, Student>(week, student);
                    Students.Add(weekStudent);
                }
            }
        }
 public TeamOfWeekViewModel(
     int season,
     TeamOfWeek[] teamOfWeek)
 {
     Leaders = new TeamOfWeekLeadersViewModel(teamOfWeek);
     Season = season;
     Weeks = new List<Week>();
     foreach (var turn in teamOfWeek.GroupBy(x => x.Turn))
     {
         var q = from t in turn
                 from playerScore in t.PlayerScores
                 group playerScore by new
                 {
                     playerScore.Key,
                     playerScore.Value.PlayerId,
                     playerScore.Value.Name
                 } into g
                 let maxValue = g.OrderByDescending(x => x.Value.Pins).FirstOrDefault()
                 orderby maxValue.Value.Pins descending
                 select new PlayerScore(g.Key.PlayerId, g.Key.Name, maxValue.Value.Team, maxValue.Value.TeamLevel)
                 {
                     Pins = maxValue.Value.Pins,
                     Score = maxValue.Value.Score,
                     Series = maxValue.Value.Series,
                     Medals = g.SelectMany(x => x.Value.Medals).ToList()
                 };
         var week = new Week(turn.Key, q.ToList());
         Weeks.Add(week);
     }
 }
Beispiel #4
0
        public static WeekList GetWeeksData()
        {
            WeekList weeks = null;

            using (var db = new DataBase("sp_GetWeekData", null))
            {
                var reader = db.ExecuteReader();

                if (reader.HasRows)
                {
                    weeks = new WeekList();

                    while (reader.Read())
                    {
                        var week = new Week();

                        week.Id = reader.GetValueOrDefault<int>("ID");
                        week.YearWeekNumber = reader.GetValueOrDefault<int>("WeekNo");
                        week.Year = reader.GetValueOrDefault<int>("WeekNoYear");
                        week.Month = reader.GetValueOrDefault<int>("WeekNoMonth");
                        week.Day = reader.GetValueOrDefault<int>("WeekNoDay");
                        week.MondayDate = reader.GetValueOrDefault<DateTime>("WeekNoStartDate");

                        weeks.Add(week);
                    }
                }
            }

            return weeks;
        }
 internal MonthOnDayOfWeekUnit(Schedule schedule, int duration, Week week, DayOfWeek dayOfWeek)
 {
     _duration = duration;
     _week = week;
     _dayOfWeek = dayOfWeek;
     Schedule = schedule;
     At(0, 0);
 }
        public void test_week_with_days_with_no_tasks()
        {
            Week week = new Week("Week 1");
            Day  day  = new Day("Monday 2017-04-03");

            week.AddDay(day);

            var tasks = act(week);

            Assert.That(!tasks.Any());
        }
Beispiel #7
0
 public ScheduleDay(Week week, Day day, IEnumerable <ScheduleRoom> rooms, SettingShedule setting, DateTime firstDate)
 {
     //times
     Week = week;
     Day  = day;
     //settings
     InitializeSettingOfDay(setting, day);
     //main
     InitializeDatesOfDay(firstDate, setting.CountWeeksShedule, setting.CountEducationalWeekBySem);
     Lessons = InitializeLessonsOfDay(rooms.ToList(), setting.CountLessonsOfDay, setting.FirstLessonsOfWeekDay).ToList();
 }
Beispiel #8
0
        public List <Day> GiveDatesOfWeekWithFirstShift(Week week)
        {
            var days = GiveDatesOfWeek(week);

            for (int i = 0; i < 7; i++)
            {
                days[i].Shifts.Add(new Shift());
            }

            return(days);
        }
Beispiel #9
0
        public async Task <CalendarData> GetMonthDays(int year, int month)
        {
            //Set if is necessary set the day for weather information
            bool weatherInfoNeeded = DateTime.Now.Month == month && DateTime.Now.Year == year;

            DateTime firstMonthDay = new DateTime(year, month, 1);
            int      lastMonthDay  = DateTime.DaysInMonth(year, month);

            CalendarData data = new CalendarData()
            {
                Weeks = new List <Week>()
            };
            int weekDay = (int)firstMonthDay.DayOfWeek == 0 ? 7 : (int)firstMonthDay.DayOfWeek;

            Week week = new Week()
            {
                Days = new Day[7]
            };

            for (int i = 1; i <= lastMonthDay; i++)
            {
                if (weekDay > 7)
                {
                    weekDay = 1;
                    data.Weeks.Add(week);
                    week = new Week()
                    {
                        Days = new Day[7]
                    };
                }

                week.Days[weekDay - 1] = new Day()
                {
                    WeekDay = i
                };

                if (i == DateTime.Now.Day && weatherInfoNeeded)
                {
                    data.ActualDayWeek         = data.Weeks.Count;
                    data.ActualDayWeekPosition = weekDay - 1;
                }

                weekDay++;
            }
            //Add last week
            data.Weeks.Add(week);

            if (weatherInfoNeeded)
            {
                data = await _openWeatherService.GetWeather(data);
            }

            return(data);
        }
Beispiel #10
0
        public void ToStringNullValuesWithoutExceptionTest()
        {
            Week week = new Week(testDay);

            week.ToString();
            week.ToString((string)null);
            week.ToString(null, CultureInfo.InvariantCulture);
            week.ToString("G", (IFormatProvider)null);
            week.ToString("G", (string)null);
            week.ToString(null, null, null);
        }
Beispiel #11
0
        public ActionResult Create([Bind(Include = "Id,Name,Start,End,Active")] Week week)
        {
            if (ModelState.IsValid)
            {
                db.Weeks.Add(week);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(week));
        }
        public void StartOfWeekIsMonday(string date)
        {
            // Arrange
            Week week = new Week(DateTime.Parse(date));

            // Act
            DateTime startOfWeek = week.StartOfWeek;

            // Assert
            Assert.That(startOfWeek.DayOfWeek, Is.EqualTo(DayOfWeek.Monday));
        }
        public void WeekConformsToISO8601(string date, string expectedWeek)
        {
            // Arrange
            Week week = new Week(DateTime.Parse(date));

            // Act
            string sortableWeek = week.ToString();

            // Assert
            Assert.That(sortableWeek, Is.EqualTo(expectedWeek));
        }
        public void EndOfWeekIsSunday(string date)
        {
            // Arrange
            Week week = new Week(DateTime.Parse(date));

            // Act
            DateTime endOfWeek = week.EndOfWeek;

            // Assert
            Assert.That(endOfWeek.DayOfWeek, Is.EqualTo(DayOfWeek.Sunday));
        }
Beispiel #15
0
        public void CompletedGoalsCount_IsCorrect_AfterAddingCompleteGoal()
        {
            Week       week = new Week(sampleDate);
            WeeklyGoal goal = new WeeklyGoal("", 1);

            goal.DaysCompleted[0] = true;

            week.Goals.Add(goal);

            Assert.That(week.CompletedGoalsCount, Is.EqualTo(1));
        }
Beispiel #16
0
        public void EnAuCultureTest()
        {
            CultureInfo cultureInfo = new CultureInfo("en-AU");
            //	cultureInfo.DateTimeFormat.CalendarWeekRule = CalendarWeekRule.FirstFourDayWeek;
            TimeCalendar calendar = new TimeCalendar(new TimeCalendarConfig {
                Culture = cultureInfo
            });
            Week week = new Week(new DateTime(2011, 4, 1, 9, 0, 0), calendar);

            Assert.Equal(week.Start, new DateTime(2011, 3, 28));
        }         // EnAuCultureTest
        private Week BuildTestWeek(int daysNumber)
        {
            Week week = new Week("Week 1");
            var  days = Enumerable.Range(0, daysNumber).Select(s => new Day("Monday 2016-05-01"));

            foreach (var day in days)
            {
                week.AddDay(day);
            }

            return(week);
        }
Beispiel #18
0
        public void Should_cast_from_Minute(double minuteValue, double expectedValue)
        {
            var minuteInstance = new SystemOfUnits.Time.Minute(minuteValue);

            Week actual = minuteInstance;

            Assert.IsAssignableFrom <Week>(actual);

            var actualValue = actual.Value;

            Assert.AreEqual(expectedValue, actualValue, Consts.DeltaAssert);
        }
        public Week Insert(Week week)
        {
            const string sqlFixed = "insert into week (year, week, hash) values({0}, {1}, '{2}')";
            var          result   = sqlitedb.ExecuteNonQuery(String.Format(sqlFixed, week.Year, week.WeekNr, week.Hash));

            if (result == 1)
            {
                Week resultWeek = GetWeek(week.Year, week.WeekNr);
                return(resultWeek);
            }
            return(null);
        }
Beispiel #20
0
        public async Task <IActionResult> Create([Bind("Id,StartDate,EndDate")] Week week)
        {
            if (ModelState.IsValid)
            {
                week.Id = Guid.NewGuid();
                _context.Add(week);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(week));
        }
Beispiel #21
0
        public void Should_cast_from_Second(double secondValue, double expectedValue)
        {
            var secondInstance = new SystemOfUnits.Time.Second(secondValue);

            Week actual = secondInstance;

            Assert.IsAssignableFrom <Week>(actual);

            var actualValue = actual.Value;

            Assert.AreEqual(expectedValue, actualValue, Consts.DeltaAssert);
        }
Beispiel #22
0
        public void Should_cast_from_Year(double yearValue, double expectedValue)
        {
            var yearInstance = new SystemOfUnits.Time.Year(yearValue);

            Week actual = yearInstance;

            Assert.IsAssignableFrom <Week>(actual);

            var actualValue = actual.Value;

            Assert.AreEqual(expectedValue, actualValue, Consts.DeltaAssert);
        }
Beispiel #23
0
 public void SaveWeek(Week newWeek)
 {
     try
     {
         _dbContext.Weeks.Add(newWeek);
         _dbContext.SaveChanges();
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
     }
 }
Beispiel #24
0
        public void CompletedGoalsCount_IsZero_AfterRemovingGoal()
        {
            Week       week = new Week(sampleDate);
            WeeklyGoal goal = new WeeklyGoal("", 1);

            goal.DaysCompleted[0] = true;

            week.Goals.Add(goal);
            week.Goals.Remove(goal);

            Assert.That(week.CompletedGoalsCount, Is.Zero);
        }
Beispiel #25
0
        public IHttpActionResult PostWeek(Week week)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Week.Add(week);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = week.Id }, week));
        }
        private Uri BuildUri(Week week = Week.Even)
        {
            if (week == Week.Both)
            {
                throw new Exception("Can't build the uri for both weeks.");
            }

            int    table = 6 + (int)week;
            string url   = String.Format("http://gesahui.de/home/stundenplan/stupla_untis/{0}/{1}/{1}{2}.htm", table.ToString().PadLeft(2, '0'), kindChar, timetableIndex.ToString("D5"));

            return(new Uri(url));
        }
Beispiel #27
0
        private void  GenerateRoundTwo()
        {
            System.Collections.ArrayList temp = new System.Collections.ArrayList();
            // I've simply to copy round one and switch sides
            for (int week = 0; week < this.weeks.Count; week++)
            {
                Week w = ((Week)this.weeks[week]).copyAndSwitch(System.Convert.ToString(this.weeks.Count + week + 1));
                temp.Add(w);
            }

            weeks.AddRange(temp);
        }
Beispiel #28
0
        private void AgendaListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null)
            {
                return;
            }
            Week selectedWeek = e.SelectedItem as Week;

            (sender as ListView).SelectedItem = null;

            DisplayAlert("Hi", "You Tapped " + selectedWeek.Day, "Ok");
        }
Beispiel #29
0
 static void AddEvent(Week day)
 {
     if (string.IsNullOrWhiteSpace(events[((int)day - 1)]))
     {
         Console.Write("Input event:");
         events[(int)day - 1] = Console.ReadLine();
     }
     else
     {
         Console.WriteLine("U already have event at this day: " + events[(int)day - 1]);
     }
 }
Beispiel #30
0
        public ActionResult Save(WeekValuesFormViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View("WeekValuesForm", viewModel));
            }

            if (viewModel.WeekValues.Id == 0)
            {
                _context.WeekValues.Add(viewModel.WeekValues);
                try
                {
                    _context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    Console.WriteLine(e);
                }

                var week = new Week();
                week = viewModel.Week;
                week.WeekValuesId = viewModel.WeekValues.Id;
                week.CalculatePattern(viewModel.WeekValues);
                week.CalculateProfit();

                _context.Weeks.Add(week);
            }
            else
            {
                // For the FK
                viewModel.Week.WeekValuesId = viewModel.WeekValues.Id;

                viewModel.Week.CalculatePattern(viewModel.WeekValues);
                viewModel.Week.CalculateProfit();

                var weekValuesInDB = _context.WeekValues.Single(w => w.Id == viewModel.WeekValues.Id);
                var weekInDB       = _context.Weeks.Single(w => w.Id == viewModel.Week.Id);

                weekValuesInDB.Map(viewModel.WeekValues);
                weekInDB.Map(viewModel.Week);
            }

            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                Console.WriteLine(e);
            }

            return(RedirectToAction("Index", "Weeks"));
        }
Beispiel #31
0
        /// <summary> проверить не будет переполнен день если добавить количество занятий равное CountPut </summary>
        public bool LimitLessonsNotExceeded(IEnumerable <string> groups, Week week, Day day, int CountPut)
        {
            foreach (string group in groups)
            {
                if (CountLessonsGroup(group, week, day) + CountPut > MaxPossibleCountLessons)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #32
0
 public bool Equals(Week other)
 {
     if (ReferenceEquals(null, other))
     {
         return false;
     }
     if (ReferenceEquals(this, other))
     {
         return true;
     }
     return other.WeekNumber == WeekNumber;
 }
Beispiel #33
0
 public void NextWeek_Executed(object sender)
 {
     if (DateFrom != null && DateTo != null)
     {
         _currentDate = _currentDate.AddDays(7);
         DateFrom     = _currentDate.ToString("dd/MM/yyyy");
         DateTo       = _currentDate.AddDays(7).ToString("dd/MM/yyyy");
         CurrentWeek  = new Week(_currentDate);
         _currentWeekNumber++;
         GenerateTable(null, null);
     }
 }
Beispiel #34
0
        public ViewDocumentWindow(Project project)
        {
            _dbHelper           = project.DbHelper;
            _timeTableCaretaker = project.TimeTableCaretaker;

            InitializeComponent();
            DataContext = this;
            var state = _timeTableCaretaker.GetState();

            FirstWeek  = state.FirstWeek;
            SecondWeek = state.SecondWeek;
        }
Beispiel #35
0
        public Week GetWeekByNumber(int weeknumber)
        {
            var year           = Convert.ToInt16(DateTime.Now.ToString("yyyy"));
            var firstDayOfYear = new DateTime(year, 1, 1);
            var totalDays      = (weeknumber - 1) * 7 - 1;
            var firstDayOfWeek = firstDayOfYear.AddDays(totalDays);
            var week           = new Week {
                From = firstDayOfWeek, Weeknumber = weeknumber
            };

            return(week);
        }
Beispiel #36
0
        // GET: Clock
        public ActionResult Index(string userName)
        {
            string cName =
                (userName.IsNullOrWhiteSpace()) ? System.Environment.UserName : userName;

            var userInDb = _context.Employees.SingleOrDefault(e => e.Name == cName);

            if (userInDb == null)
            {
                var newUser = new Employee
                {
                    Name         = cName,
                    PositionId   = 6,
                    SupervisorId = 1,
                    WorkHours    = "8:30|5:30",
                    OnProbation  = false
                };
                _context.Employees.Add(newUser);
                _context.SaveChanges();
                userInDb = newUser;
            }

            var week = new Week();

            //clock punches for this employee, today
            var punches = _context.ClockPunches
                          .Include(p => p.PunchType)
                          .Where(p => p.Employee.Id == userInDb.Id &&
                                 DbFunctions.TruncateTime(p.PunchEventTime) ==
                                 DbFunctions.TruncateTime(DateTime.Now));

            //clock punches for this employee, this week
            var punchesWeek = _context.ClockPunches
                              .Include(p => p.PunchType).AsEnumerable()
                              .Where(p => p.EmployeeId == userInDb.Id &&
                                     p.PunchEventTime.Date >= week.Start.Date &&
                                     p.PunchEventTime.Date <= week.End.Date);

            var dt = new Pivot().PivotTable(punchesWeek);

            var viewModel = new EmployeePunchViewModel
            {
                Employee         = userInDb,
                ClockPunches     = punches,
                ClockPunchesWeek = punchesWeek,
                Week             = week,
                PunchesThisWeek  = dt
            };

            Console.WriteLine(userInDb);
            return(View(viewModel));
        }
        public async Task <IActionResult> ScheduleBig(int WeekId, string group)
        {
            try
            {
                Week week = await db.Weeks.Include(day => day.ScheduleDays).ThenInclude(les => les.Lessons).FirstOrDefaultAsync(w => w.Id == WeekId);

                if (group.Contains("+"))
                {
                    for (byte a = 0; a < week.ScheduleDays.Count; a++)
                    {
                        List <Lesson> wk = new List <Lesson>();
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("-")).ToList());
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("*")).ToList());
                        foreach (var l in wk)
                        {
                            week.ScheduleDays[a].Lessons.Remove(l);
                        }
                    }
                }
                if (group.Contains("-"))
                {
                    for (byte a = 0; a < week.ScheduleDays.Count; a++)
                    {
                        List <Lesson> wk = new List <Lesson>();
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("+")).ToList());
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("*")).ToList());
                        foreach (var l in wk)
                        {
                            week.ScheduleDays[a].Lessons.Remove(l);
                        }
                    }
                }
                if (group.Contains("*"))
                {
                    for (byte a = 0; a < week.ScheduleDays.Count; a++)
                    {
                        List <Lesson> wk = new List <Lesson>();
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("-")).ToList());
                        wk.AddRange(week.ScheduleDays[a].Lessons.Where(les => les.Name.Contains("+")).ToList());
                        foreach (var l in wk)
                        {
                            week.ScheduleDays[a].Lessons.Remove(l);
                        }
                    }
                }
                return(View("ScheduleBigResult", week));
            }
            catch (Exception exp)
            {
                return(View("Warning", exp));
            }
        }
Beispiel #38
0
        }         // Clear

        // ----------------------------------------------------------------------
        private void SelectPeriod(PeriodSelectType periodSelectType)
        {
            int offset = 0;

            switch (periodSelectType)
            {
            case PeriodSelectType.Previous:
                offset = -1;
                break;

            case PeriodSelectType.Current:
                ResetWorkingPeriod();
                return;

            case PeriodSelectType.Next:
                offset = 1;
                break;
            }

            switch (WorkingTimePeriod)
            {
            case TimePeriodMode.Year:
                Year year = new Year(WorkingPeriodStartDate);
                SetWorkingPeriod(year.AddYears(offset));
                break;

            case TimePeriodMode.Halfyear:
                Halfyear halfyear = new Halfyear(WorkingPeriodStartDate);
                SetWorkingPeriod(halfyear.AddHalfyears(offset));
                break;

            case TimePeriodMode.Quarter:
                Quarter quarter = new Quarter(WorkingPeriodStartDate);
                SetWorkingPeriod(quarter.AddQuarters(offset));
                break;

            case TimePeriodMode.Month:
                Month month = new Month(WorkingPeriodStartDate);
                SetWorkingPeriod(month.AddMonths(offset));
                break;

            case TimePeriodMode.Week:
                Week week = new Week(WorkingPeriodStartDate);
                SetWorkingPeriod(week.AddWeeks(offset));
                break;

            case TimePeriodMode.Day:
                Day day = new Day(WorkingPeriodStartDate);
                SetWorkingPeriod(day.AddDays(offset));
                break;
            }
        }         // SelectPeriod
Beispiel #39
0
        /// <summary>
        /// Recalculates the start date of all tasks in the list.  Relies on the GetSortedList()
        /// function to ensure that all tasks on which task T is dependent on are
        /// calculated before T is reached.  Recalculating dates becomes a simple matter
        /// of asking the task's dependencies for their start dates, and choosing the
        /// latest date.
        /// </summary>
        /// <param name="tasks">The array/tree hybrid data structure that contains the
        /// tasks to recalculate.</param>
        /// <param name="earliestDate">The earliest date for any task.</param>
        /// <param name="week">The working week to base date calculations on.</param>
        public void RecalculateDates(List <ITask> tasks, DateTime earliestDate, Week week)
        {
            // Ensure that the list is sorted topologically before we begin.  This means
            // that all tasks will have the correct start and end dates before any
            // dependent tasks have their dates calculated
            var list = GetSortedList(tasks);

            // Recalculate the start date for all tasks in the list
            foreach (var task in list)
            {
                task.RecalculateDates(earliestDate, week);
            }
        }
 public MonthOnDayOfWeekUnit(Schedule schedule, int duration, Week week, DayOfWeek dayOfWeek)
 {
     Schedule = schedule;
     Duration = duration;
     Week = week;
     DayOfWeek = dayOfWeek;
     if (Week == Week.Last)
         Schedule.CalculateNextRun = x => {
             var nextRun = x.Date.First().Last(DayOfWeek);
             return (x > nextRun) ? x.Date.First().AddMonths(Duration).Last(DayOfWeek) : nextRun;
         };
     else
         Schedule.CalculateNextRun = x => {
             var nextRun = x.Date.First().ToWeek(Week).ThisOrNext(DayOfWeek);
             return (x > nextRun) ? x.Date.First().AddMonths(Duration).ToWeek(Week).ThisOrNext(DayOfWeek) : nextRun;
         };
 }
Beispiel #41
0
 /// <summary>
 /// 保存
 /// </summary>
 public override void Save()
 {
     if(!m_Loaded)//新增
     {
         Week week=new Week();
         SaveToDb(this, week,true);
     }
     else//修改
     {
         Week week=new Week(weekId);
         if(week.IsNew)
             throw new AppException("该数据已经不存在了");
         SaveToDb(this, week,false);
     }
 }
 static void Main(string[] args)
 {
     Week w = new Week();
     Console.WriteLine(w.Monday.DayOfWeek.ToString());
     Console.ReadKey();
 }
Beispiel #43
0
        public override Course GetDownloadableContent(string courseName)
        {
            //get the lecture url
            string course_url = LectureUrlFromName(courseName);

            Course courseContent = new Course(courseName);
            Console.WriteLine("* Collecting downloadable content from " + course_url);

            //get the course name, and redirect to the course lecture page
            //string vidpage = get_page(course_url);
            string vidpage = _client.DownloadString(course_url);

            HtmlDocument htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(vidpage);

            // ParseErrors is an ArrayList containing any errors from the Load statement
            if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Any())
            {
                // Handle any parse errors as required
            }
            else
            {
                if (htmlDoc.DocumentNode != null)
                {
                    //# extract the weekly classes
                    HtmlNodeCollection weeks = htmlDoc.DocumentNode.SelectNodes("//div[contains(concat(' ', @class, ' '), ' chapter ')]");

                    if (weeks != null)
                    {
                        Regex regexpSubs = new Regex("data-transcript-translation-url=(?:&#34;|\")([^\"&]*)(?:&#34;|\")");
                        Regex splitter = new Regex("data-streams=(?:&#34;|\").*1.0[0]*:");
                        Regex extra_youtube = new Regex("//w{0,3}.youtube.com/embed/([^ ?&]*)[?& ]");

                        // for each weekly class, go to the page and find the actual content there.
                        int i = 1;
                        foreach (HtmlNode week in weeks)
                        {
                            Console.WriteLine();
                            Console.WriteLine("* Week " + i + " of " + weeks.Count);

                            //HtmlNode a = week.SelectSingleNode("a");

                            //string weekLink = a.Attributes["href"].Value; //.InnerText.Trim();
                            //string weekPage = _client.DownloadString(BASE_URL + weekLink);

                            //HtmlDocument weekDoc = new HtmlDocument();
                            //weekDoc.LoadHtml(weekPage);

                            //HtmlNode h3txt = weekDoc.DocumentNode.SelectSingleNode("//h3[contains(concat(' ', @class, ' '), ' headline ')]");
                            string h3txt = week.SelectSingleNode(".//h3/a").InnerText.Trim();
                            string weekTopic = Utilities.sanitise_filename(h3txt);
                            weekTopic = Utilities.TrimPathPart(weekTopic, Max_path_part_len);

                            Week weeklyContent = new Week(weekTopic);
                            weeklyContent.WeekNum = i++;

                            //HtmlNodeCollection weekSteps = weekDoc.DocumentNode.SelectNodes("//li[contains(concat(' ', @class, ' '), ' step ')]");
                            HtmlNodeCollection weekSteps = week.SelectNodes(".//ul//a");
                            int j = 1;
                            foreach (HtmlNode weekStep in weekSteps)
                            {
                                Utilities.DrawProgressBar(j, weekSteps.Count, 20, '=');

                                Dictionary<string, string> resourceLinks = new Dictionary<string, string>();

                                string weekStepAnchorHref = weekStep.Attributes["href"].Value;

                                //string stepNumber = weekStepAnchor.SelectSingleNode("span/div").InnerText;
                                string stepName = weekStep.InnerText; // weekStepAnchor.SelectSingleNode("div/div/h5").InnerText;
                                //string stepType = weekStepAnchor.SelectSingleNode("div/div/span").InnerText;
                                string stepType = null;
                                string weekNumber = weeklyContent.WeekNum.ToString().PadLeft(2, '0');
                                string videoNumber = j.ToString().PadLeft(2, '0'); //stepNumber.Trim().Split('.')[1].PadLeft(2, '0');

                                stepName.RemoveColon();
                                stepName = Utilities.sanitise_filename(stepName);
                                stepName = Utilities.TrimPathPart(stepName, Max_path_part_len);

                                string classname = string.Join("-", weekNumber, videoNumber, stepName);

                                //string weekStepAnchorHref = weekStepAnchor.Attributes["href"].Value;

                                List<string> video_id = new List<string>();

                                //TODO: Downloading non-video content is hard. It's handled by JavaScript and changes the page content on-the-fly.
                                string weekStepPage = _client.DownloadString(BASE_URL + weekStepAnchorHref);
                                /*HtmlDocument weekDoc = new HtmlDocument();
                                  weekDoc.LoadHtml(weekStepPage);

                                  HtmlNodeCollection weekSectionContentTabs = weekDoc.DocumentNode.SelectNodes("//div[contains(concat(' ', @id, ' '), ' seq_contents')]");

                                  string test = weekSectionContentTabs.First().InnerText;
                                  string decoded = HttpUtility.HtmlDecode(test);
                                 */
                                MatchCollection matchCollection = splitter.Matches(weekStepPage);
                                foreach (Match match in matchCollection)
                                {
                                    video_id.Add(weekStepPage.Substring(match.Index + match.Length, YOUTUBE_VIDEO_ID_LENGTH));
                                }

                                /*Deal with Subtitles
                                 *         subsUrls += [BASE_URL + regexpSubs.search(container).group(2) + "?videoId=" + id + "&language=en"
                                 *         if regexpSubs.search(container) is not None else ''
                                 *         for id, container in zip(video_id[-len(id_container):], id_container)]
                                 */

                                //Find other YouTube videos embeded
                                MatchCollection collection = extra_youtube.Matches(weekStepPage);
                                foreach (Match match in collection)
                                {
                                    video_id.Add(weekStepPage.Substring(match.Index + match.Length, YOUTUBE_VIDEO_ID_LENGTH));
                                }

                                List<string> video_links = new List<string>();
                                if (video_id.Count < 1)
                                {
                                    //string id_container = splitter.Split(weekStepPage)[0];
                                    //if (string.Equals(weekStepPage, id_container, StringComparison.OrdinalIgnoreCase))
                                    //{
                                    //RegEx.Split will return the original string if nothing found, so if they are the same, there is no video
                                    stepType = "html";
                                }
                                else
                                {
                                    video_links = video_id.Select(v => "http://youtube.com/watch?v=" + v).ToList();
                                    stepType = "video";
                                }

                                if (stepType == "video")
                                {
                                    foreach (string videoLink in video_links)
                                    {
                                        resourceLinks.Add(videoLink, null);
                                    }

                                }
                                else
                                {
                                    //TODO: For now, we skip non-video content. Another day. :)
                                    resourceLinks.Add(BASE_URL + weekStepAnchorHref, Path.ChangeExtension(classname, "html")); // "index.html");
                                }

                                ClassSegment weekClasses = new ClassSegment(classname);
                                weekClasses.ClassNum = j++;
                                weekClasses.ResourceLinks = resourceLinks;

                                weeklyContent.ClassSegments.Add(weekClasses);

                            }

                            courseContent.Weeks.Add(weeklyContent);

                        }
                        return courseContent;
                    }
                }
            }
            return null;
        }
        private void Fetch(Week week, WeekData weekData)
        {
            DataMapper.Map(week, weekData);

            weekData.CreatedByUser = new UserData();
            DataMapper.Map(week.CreatedByUser, weekData.CreatedByUser);

            weekData.ModifiedByUser = new UserData();
            DataMapper.Map(week.ModifiedByUser, weekData.ModifiedByUser);
        }
        public WeekData Update(WeekData data)
        {
            using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities>
                         .GetManager(Database.ApplicationConnection, false))
            {
                var week =
                    new Week
                    {
                        WeekId = data.WeekId
                    };

                ctx.ObjectContext.Weeks.Attach(week);

                DataMapper.Map(data, week);

                ctx.ObjectContext.SaveChanges();

                return data;
            }
        }
        public WeekData Insert(WeekData data)
        {
            using (var ctx = Csla.Data.ObjectContextManager<ApplicationEntities>
                           .GetManager(Database.ApplicationConnection, false))
            {
                var week = new Week();

                DataMapper.Map(data, week);

                ctx.ObjectContext.AddToWeeks(week);

                ctx.ObjectContext.SaveChanges();

                data.WeekId = week.WeekId;

                return data;
            }
        }
Beispiel #47
0
 private void Map(FormCollection source, Week destination)
 {
     destination.StartDate = DateTime.Parse(source["Description"]);
     destination.EndDate = DateTime.Parse(source["Name"]);
     destination.Period = int.Parse(source["Period"]);
     destination.Year = int.Parse(source["Year"]);
 }
Beispiel #48
0
 public static string GetWeekHeader(int weekNum, List<Week> weeks, Week currentWeek, string currentWeekClass)
 {
     if ((weeks == null))
     {
         return "n/a";
     }
     StringBuilder header = new StringBuilder();
     header.Append("<div");
     string weekLabel = weeks[weekNum].WeekLabel;
     if (weekLabel == currentWeek.WeekLabel)
     {
         header.Append(" class=\'" + currentWeekClass + "\'>");
     }
     else
     {
         header.Append(">");
     }
     header.Append(weekLabel);
     header.Append("</div>");
     return header.ToString();
 }
Beispiel #49
0
        public static Instant NextValid(
            this Instant instant,
            Month month = Month.Every,
            Week week = Week.Every,
            Day day = Day.Every,
            WeekDay weekDay = WeekDay.Every,
            Hour hour = Hour.Zeroth,
            Minute minute = Minute.Zeroth,
            Second second = Second.Zeroth,
            [CanBeNull] CalendarSystem calendarSystem = null,
            [CanBeNull] DateTimeZone timeZone = null)
        {
            // Never case, if any are set to never, we'll never get a valid date.
            if ((month == Month.Never) ||
                (week == Week.Never) ||
                (day == Day.Never) ||
                (weekDay == WeekDay.Never) ||
                (hour == Hour.Never) ||
                (minute == Minute.Never) ||
                (second == Second.Never))
                return Instant.MaxValue;

            if (calendarSystem == null)
                calendarSystem = CalendarSystem.Iso;
            if (timeZone == null)
                timeZone = DateTimeZone.Utc;
            Debug.Assert(calendarSystem != null);
            Debug.Assert(timeZone != null);

            // Move to next second.
            instant = instant.CeilingSecond();

            // Every second case.
            if ((month == Month.Every) &&
                (day == Day.Every) &&
                (weekDay == WeekDay.Every) &&
                (hour == Hour.Every) &&
                (minute == Minute.Every) &&
                (second == Second.Every) &&
                (week == Week.Every))
                return instant;

            // Get days and months.
            int[] days = Days(day).OrderBy(dy => dy).ToArray();
            int[] months = month.Months().ToArray();

            // Remove months where the first day isn't in the month.
            int firstDay = days.First();
            if (firstDay > 28)
            {
                // 2000 is a leap year, so February has 29 days.
                months = months.Where(mn => calendarSystem.GetDaysInMonth(2000, mn) >= firstDay).ToArray();
                if (months.Length < 1)
                    return Instant.MaxValue;
            }

            // Get zoned date time.
            ZonedDateTime zdt = new ZonedDateTime(instant, timeZone, calendarSystem);
            int y = zdt.Year;
            int m = zdt.Month;
            int d = zdt.Day;
            int h = zdt.Hour;
            int n = zdt.Minute;
            int s = zdt.Second;

            int[] weeks = week.Weeks().ToArray();

            IsoDayOfWeek[] weekDays = weekDay.WeekDays().ToArray();
            int[] hours = hour.Hours().OrderBy(i => i).ToArray();
            int[] minutes = minute.Minutes().OrderBy(i => i).ToArray();
            int[] seconds = second.Seconds().ToArray();

            do
            {
                foreach (int currentMonth in months)
                {
                    if (currentMonth < m)
                        continue;
                    if (currentMonth > m)
                    {
                        d = 1;
                        h = n = s = 0;
                    }
                    m = currentMonth;
                    foreach (int currentDay in days)
                    {
                        if (currentDay < d)
                            continue;
                        if (currentDay > d)
                            h = n = s = 0;
                        d = currentDay;

                        // Check day is valid for this month.
                        if (d > calendarSystem.GetDaysInMonth(y, m))
                            break;

                        // We have a potential day, check week and week day
                        zdt = timeZone.AtLeniently(new LocalDateTime(y, m, d, h, n, s, calendarSystem));
                        if ((week != Week.Every) &&
                            (!weeks.Contains(zdt.WeekOfWeekYear)))
                            continue;
                        if ((weekDay != WeekDay.Every) &&
                            (!weekDays.Contains(zdt.IsoDayOfWeek)))
                            continue;

                        // We have a date match, check time.
                        foreach (int currentHour in hours)
                        {
                            if (currentHour < h) continue;
                            if (currentHour > h)
                                n = s = 0;
                            h = currentHour;
                            foreach (int currentMinute in minutes)
                            {
                                if (currentMinute < n) continue;
                                if (currentMinute > n)
                                    s = 0;
                                n = currentMinute;
                                foreach (int currentSecond in seconds)
                                {
                                    if (currentSecond < s) continue;
                                    return
                                        timeZone.AtLeniently(
                                            new LocalDateTime(y, m, d, h, n, currentSecond, calendarSystem)).ToInstant();
                                }
                                n = s = 0;
                            }
                            h = n = s = 0;
                        }
                        d = 1;
                    }
                    d = 1;
                    h = n = s = 0;
                }
                y++;

                // Don't bother checking max year.
                if (y >= calendarSystem.MaxYear)
                    return Instant.MaxValue;

                // Start next year
                m = d = 1;
                h = n = s = 0;
            } while (true);
        }
        /// <summary>
        /// Get's the next valid second after the current .
        /// </summary>
        /// <param name="dateTime">The date time (fractions of a second are removed).</param>
        /// <param name="month">The month.</param>
        /// <param name="week">The week.</param>
        /// <param name="day">The day.</param>
        /// <param name="weekDay">The week day.</param>
        /// <param name="hour">The hour.</param>
        /// <param name="minute">The minute.</param>
        /// <param name="second">The second.</param>
        /// <param name="calendar">The calendar.</param>
        /// <param name="calendarWeekRule">The calendar week rule.</param>
        /// <param name="firstDayOfWeek">The first day of week.</param>
        /// <param name="inclusive">if set to <c>true</c> can return the time specified, otherwise, starts at the next second..</param>
        /// <returns>
        /// The next valid date (or <see cref="DateTime.MaxValue"/> if none).
        /// </returns>
        public static DateTime NextValid(
                this DateTime dateTime,
                Month month = Month.Every,
                Week week = Week.Every,
                Day day = Day.Every,
                WeekDay weekDay = WeekDay.Every,
                Hour hour = Hour.Zeroth,
                Minute minute = Minute.Zeroth,
                Second second = Second.Zeroth,
                Calendar calendar = null,
                CalendarWeekRule calendarWeekRule = CalendarWeekRule.FirstFourDayWeek,
                DayOfWeek firstDayOfWeek = DayOfWeek.Sunday,
                bool inclusive = false)
        {
            // Never case, if any are set to never, we'll never get a valid date.
            if ((month == Month.Never) || (week == Week.Never) ||
                (day == Day.Never) || (weekDay == WeekDay.Never) || (hour == Hour.Never) ||
                (minute == Minute.Never) ||
                (second == Second.Never))
                return DateTime.MaxValue;

            if (calendar == null)
                calendar = CultureInfo.CurrentCulture.Calendar;

            // Set the time to this second (or the next one if not inclusive), remove fractions of a second.
            dateTime = new DateTime(
                    dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
            if (!inclusive)
                dateTime = calendar.AddSeconds(dateTime, 1);

            // Every second case.
            if ((month == Month.Every) && (day == Day.Every) && (weekDay == WeekDay.Every) && (hour == Hour.Every) &&
                (minute == Minute.Every) && (second == Second.Every) &&
                (week == Week.Every))
                return calendar.AddSeconds(dateTime, 1);

            // Get days and months.
            IEnumerable<int> days = day.Days().OrderBy(dy => dy);
            IEnumerable<int> months = month.Months();

            // Remove months where the first day isn't in the month.
            int firstDay = days.First();
            if (firstDay > 28)
            {
                // 2000 is a leap year, so February has 29 days.
                months = months.Where(mn => calendar.GetDaysInMonth(2000, mn) >= firstDay);
                if (months.Count() < 1)
                    return DateTime.MaxValue;
            }

            // Get remaining date components.
            int y = calendar.GetYear(dateTime);
            int m = calendar.GetMonth(dateTime);
            int d = calendar.GetDayOfMonth(dateTime);

            int h = calendar.GetHour(dateTime);
            int n = calendar.GetMinute(dateTime);
            int s = calendar.GetSecond(dateTime);

            IEnumerable<int> weeks = week.Weeks();
            IEnumerable<DayOfWeek> weekDays = weekDay.WeekDays();
            IEnumerable<int> hours = hour.Hours().OrderBy(i => i);
            IEnumerable<int> minutes = minute.Minutes().OrderBy(i => i);
            IEnumerable<int> seconds = second.Seconds();
            
            do
            {
                foreach (int currentMonth in months)
                {
                    if (currentMonth < m)
                        continue;
                    if (currentMonth > m)
                    {
                        d = 1;
                        h = n = s = 0;
                    }
                    m = currentMonth;
                    foreach (int currentDay in days)
                    {
                        if (currentDay < d)
                            continue;
                        if (currentDay > d)
                            h = n = s = 0;
                        d = currentDay;

                        // Check day is valid for this month.
                        if ((d > 28) && (d > calendar.GetDaysInMonth(y, m)))
                            break;

                        // We have a potential day, check week and week day
                        dateTime = new DateTime(y, m, d, h, n, s);
                        if ((week != Week.Every) &&
                            (!weeks.Contains(dateTime.WeekNumber(calendar, calendarWeekRule, firstDayOfWeek))))
                            continue;
                        if ((weekDay != WeekDay.Every) &&
                            (!weekDays.Contains(calendar.GetDayOfWeek(dateTime))))
                            continue;

                        // We have a date match, check time.
                        foreach (int currentHour in hours)
                        {
                            if (currentHour < h) continue;
                            if (currentHour > h)
                                n = s = 0;
                            h = currentHour;
                            foreach (int currentMinute in minutes)
                            {
                                if (currentMinute < n) continue;
                                if (currentMinute > n)
                                    s = 0;
                                n = currentMinute;
                                foreach (int currentSecond in seconds)
                                {
                                    if (currentSecond < s) continue;
                                    return new DateTime(y, m, d, h, n, currentSecond, calendar);
                                }
                                n = s = 0;
                            }
                            h = n = s = 0;
                        }
                        d = 1;
                    }
                    d = 1;
                    h = n = s = 0;
                }
                y++;

                // Don't bother checking max year.
                if (y > 9998)
                    return DateTime.MaxValue;

                // Start next year
                m = d = 1;
                h = n = s = 0;
            } while (true);
        }
Beispiel #51
0
 //从后台获取数据
 internal static void LoadFromDAL(WeekInfo pWeekInfo, Week  pWeek)
 {
     pWeekInfo.weekId = pWeek.WeekId;
      		pWeekInfo.weekName = pWeek.WeekName;
     pWeekInfo.Loaded=true;
 }
Beispiel #52
0
        //Main_8_4_2
        public static void Main_8_4_2()
        {
            //��GetName��ȡö�ٳ������Ƶ�����
            foreach (string item in Enum.GetNames(typeof(Week)))
            {
                Console.WriteLine(item.ToString());
            }

            //��GetValues��ȡö�ٳ���ֵ������
            foreach (Week item in Enum.GetValues(typeof(Week)))
            {
                Console.WriteLine("{0} : {1}", item.ToString("D"), item.ToString());
            }

            //��IsDefined�������жϷ��Ż�������������ö��
            if (Enum.IsDefined(typeof(Week), "Fri"))
            {
                Console.WriteLine("Today is {0}.", Week.Fri.ToString("G"));
            }

            //���������߷��������ַ���ת��Ϊ��Ч��ö������
            Week myday = (Week)Enum.Parse(typeof(Week), "Mon", true);
            Console.WriteLine(myday);
            //��ͬ����ֵ�ĵ�Чӳ��
            Week theDay = (Week)Enum.Parse(typeof(Week), "7");
            Console.WriteLine(theDay.ToString());

            //��GetUnderlyingType������������
            Console.WriteLine(Enum.GetUnderlyingType(typeof(Week)));

            //ö�����ͺ��������͵��໥ת��
            //ö��ת��Ϊ����
            int i = (int)Week.Sun;
            //������ת��Ϊö��
            Week day = (Week)Enum.Parse(typeof(Week), "10");
            Console.WriteLine(day.ToString());
            Week da2y = (Week)3;
            da2y++;
            Console.WriteLine(da2y.ToString());

            //��ͬö�����͵��໥ת��
            MusicType mtToday = MusicType.Jazz;
            Week today = (Week)mtToday;
            Console.WriteLine(today.ToString());

            //ö�����ͺͽӿ����͵�ת��
            IConvertible iConvert = (IConvertible)MusicType.Jazz;
            Int32 x = iConvert.ToInt32(CultureInfo.CurrentCulture);
            Console.WriteLine(x);

            //ö�ٵij�ʼ��
            Week myweek = new Week();
            Console.WriteLine(myweek.ToString("G"));

            Console.WriteLine("***************************************");

            WithZero wz = new WithZero();
            Console.WriteLine(wz.ToString("G"));

            WithNonZero wnz = new WithNonZero();
            Console.WriteLine(wnz.ToString("G"));
            //ִ�н��
            //Zero
            //0
        }
		private void InsertWeek(DateTime start, int index = -1)
		{
			var week = new Week(start);
			week.Days[0].Entries = AddCalendarEntries(week, DayOfWeek.Monday);
			week.Days[1].Entries = AddCalendarEntries(week, DayOfWeek.Tuesday);
			week.Days[2].Entries = AddCalendarEntries(week, DayOfWeek.Wednesday);
			week.Days[3].Entries = AddCalendarEntries(week, DayOfWeek.Thursday);
			week.Days[4].Entries = AddCalendarEntries(week, DayOfWeek.Friday);
			week.Days[5].Entries = AddCalendarEntries(week, DayOfWeek.Saturday);
			week.Days[6].Entries = AddCalendarEntries(week, DayOfWeek.Sunday);
			if (index == -1)
				weeks.Add(week);
			else
				weeks.Insert(index, week);
		}
Beispiel #54
0
 private void LoadFromId(int weekId)
 {
     if (CachedEntityCommander.IsTypeRegistered(typeof(WeekInfo)))
     {
         WeekInfo weekInfo=Find(GetList(), weekId);
         if(weekInfo==null)
             throw new AppException("未能在缓存中找到相应的键值对象");
         Copy(weekInfo, this);
     }
     else
     {	Week week=new Week( weekId);
         if(week.IsNew)
         throw new AppException("尚未初始化");
        	LoadFromDAL(this, week);
     }
 }
 internal static DateTime ToWeek(this DateTime current, Week week)
 {
     switch (week)
     {
         case Week.Second:
             return current.First().AddDays(7);
         case Week.Third:
             return current.First().AddDays(14);
         case Week.Fourth:
             return current.First().AddDays(21);
         case Week.Last:
             return current.Last().AddDays(-7);
     }
     return current.First();
 }
Beispiel #56
0
 public void SetMemento(TimeTableMemento memento)
 {
     FirstWeek = memento.FirstWeek;
     SecondWeek = memento.SecondWeek;
     ExcelHelper = memento.ExcelHelper;
 }
Beispiel #57
0
        static void Main(string[] args)
        {
            int exit = 0;
            Week w = new Week();
            WeekFlag wf = new WeekFlag();
            char[] delimiterChars = { ' ', ',', '.' };

            while (exit == 0)
            {
                Console.WriteLine("В какие дни у вас есть занятия?");
                string days_source = Console.ReadLine();
                string days = days_source.ToUpper();

                string[] days_split = days.Split(delimiterChars);

                for (int i = 0; i < days_split.Length; i++)
                {
                    switch (days_split[i])
                    {
                        case "ПОНЕДЕЛЬНИК":
                            w = Week.Monday;
                            wf = WeekFlag.Monday;
                            break;

                        case "ВТОРНИК":
                            w = Week.Tuesday;
                            wf = WeekFlag.Tuesday;
                            break;

                        case "СРЕДА":
                            w = Week.Wednesday;
                            wf = WeekFlag.Wednesday;
                            break;

                        case "ЧЕТВЕРГ":
                            w = Week.Thursday;
                            wf = WeekFlag.Thursday;
                            break;

                        case "ПЯТНИЦА":
                            w = Week.Friday;
                            wf = WeekFlag.Friday;
                            break;

                        case "СУББОТА":
                            w = Week.Saturday;
                            wf = WeekFlag.Saturday;
                            break;

                        case "ВОСКРЕСЕНЬЕ":
                            w = Week.Sunday;
                            wf = WeekFlag.Sunday;
                            break;

                        default:
                            break;
                    }

                    switch (w)
                    {
                        case Week.Monday:
                            Console.WriteLine("У вас есть занятия в понедельник");
                            break;
                        case Week.Tuesday:
                            Console.WriteLine("У вас есть занятия во вторник");
                            break;
                        case Week.Wednesday:
                            Console.WriteLine("У вас есть занятия в среду");
                            break;
                        case Week.Thursday:
                            Console.WriteLine("У вас есть занятия в четверг");
                            break;
                        case Week.Friday:
                            Console.WriteLine("У вас есть занятия в пятницу");
                            break;
                        case Week.Saturday:
                            Console.WriteLine("У вас есть занятия в субботу");
                            break;
                        case Week.Sunday:
                            Console.WriteLine("У вас есть занятия в воскресенье");
                            break;
                        case Week.Empty:
                        default:
                            break;
                    }

                    if ((wf.HasFlag(WeekFlag.Monday)))
                    {
                        Console.WriteLine("У вас есть занятия в понедельник");
                    }
                    if ((wf.HasFlag(WeekFlag.Tuesday)))
                    {
                        Console.WriteLine("У вас есть занятия во вторник");
                    }
                    if ((wf.HasFlag(WeekFlag.Wednesday)))
                    {
                        Console.WriteLine("У вас есть занятия в среду");
                    }
                    if ((wf.HasFlag(WeekFlag.Thursday)))
                    {
                        Console.WriteLine("У вас есть занятия в четверг");
                    }
                    if ((wf.HasFlag(WeekFlag.Friday)))
                    {
                        Console.WriteLine("У вас есть занятия в пятницу");
                    }
                    if ((wf.HasFlag(WeekFlag.Saturday)))
                    {
                        Console.WriteLine("У вас есть занятия в субботу");
                    }
                    if ((wf.HasFlag(WeekFlag.Sunday)))
                    {
                        Console.WriteLine("У вас есть занятия в воскресенье");
                    }
                }

                Console.ReadKey();
                Console.WriteLine("Чтобы повторить введите 1, для выхода введите 2");

                int choice1 = Convert.ToInt32(Console.ReadLine());
                if (choice1 == 1)
                {
                    exit = 0;
                }
                if (choice1 == 2)
                {
                    exit = 1;
                }
            }
        }
		private IList<OpenSprinklerApp.CalendarDayPanel.Entry> AddCalendarEntries(Week week, DayOfWeek dayOfWeek)
		{
			if (Programs == null)
				return new List<OpenSprinklerApp.CalendarDayPanel.Entry>();
			var day = new List<OpenSprinklerApp.CalendarDayPanel.Entry>();
			var d = week.Start.AddDays((dayOfWeek == DayOfWeek.Sunday ? 6 : ((int)dayOfWeek - 1))).Day;
			int i = 1;
			TimeSpan lastEndTime = TimeSpan.Zero;
			foreach (var program in Programs)
			{
				var e = new OpenSprinklerApp.CalendarDayPanel.Entry();
				e.Title = i.ToString();
				if(!program.Enabled)
				{
					e.Color = Colors.Gray;
				}
				else
				{
					e.Color = StationColors[(i - 1) % StationColors.Length];
				}
				e.Start = program.Start;
				e.Duration = program.Duration;
				if (lastEndTime > e.Start && IsSequential)
					e.Start = lastEndTime;
				if(program.SkipDays == OpenSprinklerNet.SkipDays.None ||		
					program.SkipDays == OpenSprinklerNet.SkipDays.Odd && d % 2 == 1 ||
					program.SkipDays == OpenSprinklerNet.SkipDays.Even && d % 2 == 0)
				{
					day.Add(e);
					if(program.Enabled)
						lastEndTime = e.Start + e.Duration;
				}

				i++;
			}
			return day;

			day.Add(new CalendarDayPanel.Entry()
			{
				Title = "1",
				Color = Colors.Red,
				Start = TimeSpan.FromHours(2),
				Duration = TimeSpan.FromMinutes(15)
			});
			if (d % 2 == 1)
			{
				day.Add(new CalendarDayPanel.Entry()
				{
					Title = "2",
					Color = Colors.Green,
					Start = TimeSpan.FromHours(3.5),
					Duration = TimeSpan.FromMinutes(45)
				});
				day.Add(new CalendarDayPanel.Entry()
				{
					Title = "3",
					Color = Colors.Blue,
					Start = TimeSpan.FromHours(9),
					Duration = TimeSpan.FromMinutes(10)
				});
				day.Add(new CalendarDayPanel.Entry()
				{
					Title = "4",
					Color = Colors.Orange,
					Start = TimeSpan.FromHours(12),
					Duration = TimeSpan.FromHours(1)
				});
			}
			day.Add(new CalendarDayPanel.Entry()
			{
				Title = "5",
				Color = Colors.Blue,
				Start = TimeSpan.FromHours(20),
				Duration = TimeSpan.FromHours(3)
			});
			return day;
		}
 public Shedule(Week week = null, String group = "")
 {
     this.Week = week;
     this.Group = group;
 }
Beispiel #60
0
 //数据持久化
 internal static void SaveToDb(WeekInfo pWeekInfo, Week  pWeek,bool pIsNew)
 {
     pWeek.WeekId = pWeekInfo.weekId;
      		pWeek.WeekName = pWeekInfo.weekName;
     pWeek.IsNew=pIsNew;
     string UserName = SubsonicHelper.GetUserName();
     try
     {
         pWeek.Save(UserName);
     }
     catch(Exception ex)
     {
         LogManager.getInstance().getLogger(typeof(WeekInfo)).Error(ex);
         if(ex.Message.Contains("插入重复键"))//违反了唯一键
         {
             throw new AppException("此对象已经存在");//此处等待优化可以从唯一约束中直接取出提示来,如果没有的话,默认为原始的出错提示
         }
         throw new AppException("保存失败");
     }
     pWeekInfo.weekId = pWeek.WeekId;
     //如果缓存存在,更新缓存
     if (CachedEntityCommander.IsTypeRegistered(typeof(WeekInfo)))
     {
         ResetCache();
     }
 }