public EditTeacherViewModel()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var deg = (from d in cnt.Degrees select d);
         Degrees = new ObservableCollection<Degree>(deg);
         var fac = (from f in cnt.Faculties select f);
         Faculties = new ObservableCollection<Faculty>(fac);
         var titl = (from t in cnt.Titles select t);
         Titles = new ObservableCollection<Title>(titl);
         var emp = (from e in cnt.Employees select e);
         Employes = new ObservableCollection<Employe>(emp);
     }
 }
 // проверка накладок у преподавателя
 bool TeacherOverlapping(int teacherID, int number, int day, bool weektype)
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         // академическая нагрузка препода
         var academic_load = (from a in cnt.AcademicLoadSet where a.EmployeId == teacherID select a);
         // список всех ID занятий, которые он проводит
         List<int> teacher_regactions = new List<int>();
         foreach (var a in academic_load)
         {
             teacher_regactions.Add(a.RegulatoryActionId);
         }
         //var teacher_lessons = (from l in cnt.Lessons where teacher_regactions.Contains(l.RegulatoryActionId) select l);
         // занятия которые проходят в это время
         var teacher_lessons = (from l in cnt.Lessons where l.RingId == number && l.Day == day && l.Period == weektype select l);
         int lessons_count = 0;
         foreach (var l in teacher_lessons)
         {
             // если занятие совпадает по времени, и имеется в списке занятий преподавателя, то значит он его проводит о_О
             if (teacher_regactions.Contains(l.RegulatoryActionId)) ++lessons_count;
         }
         // если одновременно больше одного занятия, то произошла накладка
         if (lessons_count > 1) return true;
         return false;
     }
 }
 private void FillAuditoriumsList()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var aud = (from a in cnt.Auditoriums.Include("Department") select a).OrderBy(a => a.Building);
         Auditoriums = new ObservableCollection<Auditorium>(aud);
     }
 }
Example #4
0
        private void InstallApp()
        {
            StudyType Ochnaja = new StudyType
            {
                Name = "очная"
            };

            StudyType Zaochnaja = new StudyType
            {
                Name = "заочная"
            };

            StudyType unnamed3 = new StudyType
            {
                Name = "unnamed3"
            };

            StudyType unnamed4 = new StudyType
            {
                Name = "unnamed4"
            };

            Faculty IiVT = new Faculty
            {
                Name = "Информатика и вычислительная техника",
                Abbreviation = "ИиВТ",
            };

            FieldOfStudy Specialist = new FieldOfStudy
            {
                Name = "специалист"
            };

            FieldOfStudy Bakalavr = new FieldOfStudy
            {
                Name = "бакалавр"
            };

            FieldOfStudy Magistr = new FieldOfStudy
            {
                Name = "магистр"
            };

            LessonsType Lections = new LessonsType
            {
                Id = 1,
                Name = "лекция"
            };

            LessonsType Practics = new LessonsType
            {
                Id = 2,
                Name = "практика"
            };

            LessonsType Labs = new LessonsType
            {
                Id = 3,
                Name = "лабораторные"
            };

            LessonsSubType Comp = new LessonsSubType
            {
                Name = "компьютеры",
                LessonsTypeId = Labs.Id
            };

            LessonsSubType Stanki = new LessonsSubType
            {
                Name = "станки",
                LessonsTypeId = Labs.Id
            };

            Title prepod = new Title
            {
                Name = "преподаватель"
            };

            Faculty fac = new Faculty
            {
                Name = "факультет",
                Abbreviation = "фак"
            };

            Ring first = new Ring
            {
                Begin = "8:30",
                End = "9:50"
            };

            Ring second = new Ring
            {
                Begin = "10:00",
                End = "11:20"
            };

            Ring third = new Ring
            {
                Begin = "11:20",
                End = "12:50"
            };

            Ring fourth = new Ring
            {
                Begin = "13:30",
                End = "14:50"
            };

            Ring fifth = new Ring
            {
                Begin = "15:00",
                End = "16:20"
            };

            Ring sixth = new Ring
            {
                Begin = "16:30",
                End = "17:50"
            };

            Ring seventh = new Ring
            {
                Begin = "18:10",
                End = "19:30"
            };

            Auditorium a = new Auditorium
            {
                Building = 1,
                Number = "1-490",
                Seats = 50,
                OpeningDate = "",
                ClosingDate = "",
                DepartmentId = 1,
            };

            Degree d = new Degree
            {
                Name = "degree",
            };

            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                cnt.StudyTypes.AddObject(Ochnaja);
                cnt.StudyTypes.AddObject(Zaochnaja);
                cnt.StudyTypes.AddObject(unnamed3);
                cnt.StudyTypes.AddObject(unnamed4);
                cnt.Faculties.AddObject(IiVT);
                cnt.FieldsOfStudy.AddObject(Specialist);
                cnt.FieldsOfStudy.AddObject(Bakalavr);
                cnt.FieldsOfStudy.AddObject(Magistr);
                cnt.LessonsTypes.AddObject(Lections);
                cnt.LessonsTypes.AddObject(Practics);
                cnt.LessonsTypes.AddObject(Labs);
                cnt.LessonsSubTypes.AddObject(Comp);
                cnt.LessonsSubTypes.AddObject(Stanki);
                cnt.Titles.AddObject(prepod);
                cnt.Faculties.AddObject(fac);
                cnt.Rings.AddObject(first);
                cnt.Rings.AddObject(second);
                cnt.Rings.AddObject(third);
                cnt.Rings.AddObject(fourth);
                cnt.Rings.AddObject(fifth);
                cnt.Rings.AddObject(sixth);
                cnt.Rings.AddObject(seventh);
                cnt.Degrees.AddObject(d);
                //cnt.Auditoriums.AddObject(a);
                // И финальный аккорд - сохраняем все изменения в БД
                cnt.SaveChanges();
            }
        }
        // НЕ РАБОТАЕТ ДЛЯ ЗАОЧНИКОВ!!!!!!!!!!!!
        // проверка занятости преподавателя
        void CheckLesson()
        {
            int number;
            int day;
            int regaction = 0;

            if (SelectedLesson == null) return;

            ErrorInfo = string.Empty;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                if (SelectedLesson._Error || SelectedLesson._Flow)
                {
                    Employe teacher = null;
                    if (SelectedLesson._Error)
                        teacher = (from c in cnt.Employees where c.Name == SelectedCurriculum._Teacher select c).First(); //sel curr
                    else // т.е. это поток
                        teacher = (from c in cnt.Employees where c.Name == SelectedLesson._Teacher select c).First(); //sel curr
                    var teachersAcademicLoad = (from r in cnt.AcademicLoadSet where r.Employe.Id == teacher.Id select r);
                    bool flag = false;
                    foreach (var tAL in teachersAcademicLoad)
                    {
                        if (flag) break;
                        //выбираем мероприятия преподавателя
                        var teacherLessons = (from l in cnt.Lessons where tAL.RegulatoryAction.Id == l.RegulatoryAction.Id select l);
                        foreach (var tL in teacherLessons)
                        {
                            HelperClasses.indexToNumberDay(SelectedLessonIndex, out number, out day);
                            if (number == tL.RingId && day == tL.Day && tL.Period == upweek)
                            {
                                regaction = tL.RegulatoryActionId;
                                flag = true;
                                break;
                            }

                        }
                    }

                    //if (SelectedLesson._Flow) regaction = SelectedLesson._Regaction;

                    var res = (from r in cnt.Curriculums where r.RegulatoryActionId == regaction select r);
                    if (res.Count() == 1)
                    {
                        var firstRes = res.First();
                        ErrorInfo = "Внимание! " + currentTeacher + " уже ведёт пару в это время у группы " + firstRes.Group.GroupAbbreviation;
                    }
                    else if (res.Count() > 1)
                    {
                        ErrorInfo += "Внимание! Эта пара определена для потока! (";
                        string flowGroups = string.Empty;
                        foreach (var c in res)
                        {
                            flowGroups += c.Group.GroupAbbreviation + " ";
                        }
                        ErrorInfo += flowGroups.TrimEnd() + ")";
                    }
                }
            }
        }
 // проверяет, свободна ли аудитория в заданное время
 bool CheckAuditoriumEmpty(int audID, int regactionID, int number, int day, bool weektype)
 {
     if (audID == 1) return true; // это виртуальная аудитория
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var les = (from l in cnt.Lessons where l.AuditoriumId == audID && l.RingId == number && l.Day == day && l.Period == upweek && l.RegulatoryActionId != regactionID select l);
         if (les.Count() > 0) return false;
     }
     return true;
 }
        public void ShedLoadByGroup()
        {
            Curriculums.Clear();
            Lessons.Clear();
            HelpMessage = "Перетягивайте элементы на расписание";
            if (SelectedGroup == null) return;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                // узнаем форму обучения для группы
                var group = (from g in cnt.Groups where g.Id == selectedGroup.Id select g).First();
                int studytype = group.StudyTypeId;
                //поставим начало срока обучения
                if (group.EduPeriod.Count > 0) selecteddate = group.EduPeriod.First().Begin; // не обновится на форме..

                // получим учебный план группы
                IEnumerable<Curriculum> cur = (from lt in cnt.Curriculums.Include("RegulatoryAction").Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe") where lt.Group.Id == selectedGroup.Id select lt);
                foreach (Curriculum c in cur)
                {
                    var ra = c.RegulatoryAction;
                    var al = ra.AcademicLoad.First();
                    var e = al.Employe.Name;
                    var lt = ra.LessonsType.Name;
                    DisplayCurriculumLesson dispCurr = new DisplayCurriculumLesson()
                    {
                        _Subject = c.Subject.Name,
                        _Teacher = e,
                        _Type = lt,
                        _Regaction = ra.Id,
                        _Hours = ra.Hours,
                        // _Error = false,
                    };
                    Curriculums.Add(dispCurr);
                }

                // узнаем срок обучения группы чтобы не прокручивать расписание за его пределы
                // .. откуда только?..
                // ----------------------------------------

                // в зависимости от формы обучения выводим расписание
                // для заочников ищем по дате
                // для очников по дню недели

                int selectedWeekDayNumber = (int)selecteddate.DayOfWeek;
                DateTime startDay = selecteddate.AddDays(1 - selectedWeekDayNumber); // начнём неделю с понедельника (а не с воскресенья)
                DateTime endDay = startDay.AddDays(7);

                if (studytype == 1) // очная
                {
                    // заполняем табличку расписания для очников
                    for (int i = 1; i < 8; ++i) // lesson number
                    {
                        for (int j = 0; j < 7; ++j) // day
                        {
                            IEnumerable<Lesson> lessons = (from l in cnt.Lessons where l.RingId == i && l.Day == j && l.Period == upweek select l);
                            /// придумать вывод расписания от дня недели с определение типа недели (верх/низ)

                            /*j = (int)day.DayOfWeek - 1;
                            if (j < 0) j = 6;
                            days[j] = day.ToString("dddd d.MM.y");
                            OnPropertyChanged("Day" + (j + 1).ToString());*/
                            Collection<Lesson> filtered_lessons = new Collection<Lesson>();
                            foreach (var c in cur) // отбросим пары других групп
                            {
                                foreach (var l in lessons)
                                {
                                    if (c.RegulatoryActionId == l.RegulatoryActionId)
                                        filtered_lessons.Add(l);
                                }
                            }

                            DisplayCurriculumLesson dispLess = null;
                            if (filtered_lessons.Count() == 0)
                            {
                                dispLess = new DisplayCurriculumLesson();
                            }
                            else
                            {
                                var les = filtered_lessons.First();
                                var currsForLes = (from lt in cnt.Curriculums.Include("RegulatoryAction")
                                       .Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe")
                                                   where lt.RegulatoryActionId == les.RegulatoryActionId
                                                   select lt);
                                var curForLes = currsForLes.First();
                                var ra = curForLes.RegulatoryAction;
                                var al = ra.AcademicLoad.First();
                                var e = al.Employe.Name;
                                var lesstype = ra.LessonsType.Name;
                                var auditorium = (from a in cnt.Auditoriums where a.Id == les.AuditoriumId select a).First();
                                bool flow = false;
                                if (currsForLes.Count() > 1) flow = true;
                                dispLess = new DisplayCurriculumLesson()
                                {
                                    _Regaction = les.RegulatoryActionId,
                                    _Subject = curForLes.Subject.Name,
                                    _Teacher = e,
                                    _Type = lesstype,
                                    //_Error = false,
                                    _LessonID = les.Id,
                                    _Flow = flow,
                                    _Auditorium = "ауд. " + auditorium.Number,
                                    _AudID = auditorium.Id,
                                    _Day = les.Day,
                                    _Number = les.RingId,
                                };

                            }
                            Lessons.Add(dispLess);
                        }
                    }
                }
                else if (studytype == 2) // заочная
                {
                    // заполняем табличку расписания для заочников
                    for (int i = 1; i < 8; ++i) // lesson number
                    {
                        //for (int j = 0; j < 7; ++j) // day
                        int j = 0;
                        for (DateTime day = startDay; day < endDay; day = day.AddDays(1))
                        {
                            IEnumerable<Lesson> lessons = (from l in cnt.Lessons where l.RingId == i && /*l.Day == j*/ l.Date == day /*&& l.Period == upweek*/ select l);
                            j = (int)day.DayOfWeek - 1;
                            if (j < 0) j = 6;
                            days[j] = day.ToString("dddd d.MM.y");
                            OnPropertyChanged("Day" + (j + 1).ToString());
                            Collection<Lesson> filtered_lessons = new Collection<Lesson>();
                            foreach (var c in cur) // отбросим пары других групп
                            {
                                foreach (var l in lessons)
                                {
                                    if (c.RegulatoryActionId == l.RegulatoryActionId)
                                        filtered_lessons.Add(l);
                                }
                            }

                            DisplayCurriculumLesson dispLess = null;
                            if (filtered_lessons.Count() == 0)
                            {
                                dispLess = new DisplayCurriculumLesson();
                            }
                            else
                            {
                                var les = filtered_lessons.First();
                                var currsForLes = (from lt in cnt.Curriculums.Include("RegulatoryAction")
                                       .Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe")
                                                   where lt.RegulatoryActionId == les.RegulatoryActionId
                                                   select lt);
                                var curForLes = currsForLes.First();
                                var ra = curForLes.RegulatoryAction;
                                var al = ra.AcademicLoad.First();
                                var e = al.Employe.Name;
                                var lesstype = ra.LessonsType.Name;
                                var auditorium = (from a in cnt.Auditoriums where a.Id == les.AuditoriumId select a).First();
                                bool flow = false;
                                if (currsForLes.Count() > 1) flow = true;
                                dispLess = new DisplayCurriculumLesson()
                                {
                                    _Regaction = les.RegulatoryActionId,
                                    _Subject = curForLes.Subject.Name,
                                    _Teacher = e,
                                    _Type = lesstype,
                                    //_Error = false,
                                    _LessonID = les.Id,
                                    _Flow = flow,
                                    _Auditorium = "ауд. " + auditorium.Number,
                                    _AudID = auditorium.Id,
                                    _Day = les.Day,
                                    _Number = les.RingId,
                                };

                            }
                            Lessons.Add(dispLess);
                        }
                    }
                }
            }
        }
 public void PrevWeek()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         if (selectedGroup == null) return;
         var group = (from g in cnt.Groups where g.Id == selectedGroup.Id select g).First();
         if (group.EduPeriod.Count > 0) // если задан период обучения
         {
             if (selecteddate < group.EduPeriod.First().Begin || selecteddate > group.EduPeriod.First().End)
             {
                 SelectedDate = group.EduPeriod.First().Begin;
                 return;
             }
         }
     }
     SelectedDate = SelectedDate.AddDays(-7);
 }
 private void DelEmploye()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var emp = (from e in cnt.Employees where e.Id == selectedemploye.Id select e).First();
         cnt.DeleteObject(emp);
         cnt.SaveChanges();
         var emplist = (from e in cnt.Employees select e);
         Employes = new ObservableCollection<Employe>(emplist);
     }
 }
Example #10
0
 private void EditEmploye()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var emp = (from e in cnt.Employees where e.Id == selectedemploye.Id select e).First();
         emp.Name = selectedemploye.Name;
         emp.DegreeId = selectedemploye.DegreeId;
         emp.FacultyId = selectedemploye.FacultyId;
         emp.TitleId = selectedemploye.TitleId;
         //cnt.Refresh(System.Data.Objects.RefreshMode.ClientWins, emp);
         cnt.SaveChanges();
         var emplist = (from e in cnt.Employees select e);
         Employes = new ObservableCollection<Employe>(emplist);
     }
 }
Example #11
0
 private void AddEmploye()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         Employe emp = new Employe();
         emp.Name = selectedemploye.Name;
         emp.DegreeId = selectedemploye.DegreeId;
         emp.FacultyId = selectedemploye.FacultyId;
         emp.TitleId = selectedemploye.TitleId;
         cnt.Employees.AddObject(emp);
         cnt.SaveChanges();
         var emplist = (from e in cnt.Employees select e);
         Employes = new ObservableCollection<Employe>(emplist);
     }
 }
 public void Import()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         foreach (var g in readedgroups)
         {
             if (g.Add)
             {
                 Group newGroup = new Group()
                 {
                     GroupAbbreviation = g.groupCode,
                     Cource = g.course,
                     StudCount = g.studentAmount,
                     SpecialtyAbbreviation = g.specCode,
                     StudyTypeId = g.studyForm,
                     FieldOfStudyId = g.studyDirection,
                     FacultyId = 1,
                 };
                 cnt.Groups.AddObject(newGroup);
             }
         }
         cnt.SaveChanges();
     }
 }
        public void Import()
        {
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                foreach (var g in readedauditoriums)
                {
                    if (g.Add)
                    {
                        var deps = (from lt in cnt.Departments where lt.Id == g.Chair select lt);
                        if (deps.Count() == 0) continue;

                        Auditorium newAudit = new Auditorium()
                        {
                            Building = g.Corpus,
                            Department  = deps.First(),
                            Seats = g.Capacity,
                             Number = g.CorAndNum,
                             OpeningDate = "",
                             ClosingDate = "",
                        };
                        cnt.Auditoriums.AddObject(newAudit);
                    }
                }
                cnt.SaveChanges();
            }
        }
Example #14
0
        public void GroupSearch()
        {
            Groups.Clear();
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {

                IEnumerable<Group> cur = null;
                if (zaoch && och) cur = (from g in cnt.Groups.Include("Faculty").Include("StudyType").Include("FieldOfStudy") where (SqlFunctions.PatIndex("%" + GroupSeachField + "%", g.GroupAbbreviation) > 0) select g);
                else if (zaoch) cur = (from g in cnt.Groups.Include("Faculty").Include("StudyType").Include("FieldOfStudy") where (SqlFunctions.PatIndex("%" + GroupSeachField + "%", g.GroupAbbreviation) > 0) && g.StudyTypeId == 2 select g);
                else if (och) cur = (from g in cnt.Groups.Include("Faculty").Include("StudyType").Include("FieldOfStudy") where (SqlFunctions.PatIndex("%" + GroupSeachField + "%", g.GroupAbbreviation) > 0) && g.StudyTypeId == 1 select g);
                else return;

                Groups = new ObservableCollection<Group>(cur);
            }
        }
Example #15
0
        private void FillLessonsList()
        {
            lessons.Clear();
            for (int i = 0; i < 49; ++i)
            {
                lessons.Add(new DisplayCurriculumLesson());
            }

            if (selectedTeacher == null) return;

            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                var les = (from l in cnt.Lessons.Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.Curriculum") where l.Period == upweek select l);
                foreach (var l in les)
                {
                    foreach (var a in l.RegulatoryAction.AcademicLoad)
                    {
                        if (a.EmployeId == selectedTeacher.Id)
                        {
                            int i = HelperClasses.numberDayToIndex(l.Day,l.RingId);
                            lessons[i]._Subject = l.RegulatoryAction.Curriculum.First().Subject.Name;
                            lessons[i]._Type = l.RegulatoryAction.LessonsType.Name;
                            lessons[i]._Auditorium = "ауд. " + l.Auditorium.Number;
                            foreach (var c in l.RegulatoryAction.Curriculum)
                            {
                                lessons[i]._Group += c.Group.GroupAbbreviation + " ";
                            }
                            break;
                        }
                    }
                }
            }

            Lessons = new ObservableCollection<DisplayCurriculumLesson>(lessons);
        }
Example #16
0
 public void LoadAuditoriums()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         IEnumerable<Auditorium> audit = null;
         if (selectedbuilding > 0)
         {
             audit = (from r in cnt.Auditoriums.Include("Department") where r.Building == selectedbuilding select r);
         }
         else
         {
             audit = (from r in cnt.Auditoriums.Include("Department") select r);
         }
         Auditoriums = new ObservableCollection<Auditorium>(audit);
     }
 }
Example #17
0
 private void FillTeachersList()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var tea = (from t in cnt.Employees select t).OrderBy(t => t.Name);
         Teachers = new ObservableCollection<Employe>(tea);
     }
 }
Example #18
0
        public void SaveShed()
        {
            bool saved_ok = true;
            int lessonNumber = 0;
            ErrorInfo = string.Empty;

            //
            int i = 0;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                // узнаем форму обучения для группы
                int studytype = (from g in cnt.Groups where g.Id == selectedGroup.Id select g.StudyTypeId).First();

                foreach (var l in lessons) // проходим по расписанию на экране
                {
                    var res = (from c in cnt.Curriculums where c.RegulatoryActionId == l._Regaction select c);
                    if (res.Count() > 1)
                    {
                        // это поток, проверить все группы..
                        int day;
                        int number;
                        //MessageBox.Show("index = " + i);
                        HelperClasses.indexToNumberDay(i, out number, out day);
                        if (l._Number != number || l._Day != day) // мы передвинули день?
                            saved_ok = CheckFlowOk(res.First().RegulatoryActionId, number, day);
                        //MessageBox.Show("flow number "+number.ToString()+" day "+day.ToString());
                    }
                }
                ++i;

                if (!saved_ok)
                {
                    ErrorInfo = "В расписании имеются накладки! Исправте их и попробуйте снова!";
                    return;
                }

                int students;
                foreach (var s in lessons) // проходим по расписанию на экране
                {
                    if (s._Regaction != 0) // если в ячейке есть пара
                    {
                        //Console.WriteLine(s._Regaction.ToString());

                        var checklessons = (from l in cnt.Lessons where l.RegulatoryActionId == s._Regaction && l.Period == upweek select l);

                        /// !!!!а нужна ли эта проверка???????????????????????
                        /// можно просто всегда добавлять новую пару и предупредить о превышении часов если что...
                        if (checklessons.Count() == 0) // если пары с таким ID ещё не было в расписании
                        {
                            //var regaction = (from r in cnt.RegulatoryActions where r.Id == s._Regaction select r).First();
                            //Console.WriteLine("1) Number = {0} Day = {1}", (int)(lessonNumber / 7) + 1, lessonNumber % 7);

                            Lesson newLesson = new Lesson();
                            newLesson.RingId = (lessonNumber / 7) + 1;
                            newLesson.RegulatoryActionId = s._Regaction;
                            newLesson.Period = upweek;
                            newLesson.AuditoriumId = s._AudID != 0 ? s._AudID : 1;
                            if (studytype == 1) // очник
                            {
                                newLesson.Day = (lessonNumber % 7); // для заочников пока убрал
                                //Date = WeekDayNumberToDay(lessonNumber % 7), // для заочников получаем дату занятия
                                newLesson.Date = DateTime.Now; // дата не может быть пустой!! запишем что нибудь туда..
                            }
                            else if (studytype == 2) // заочник
                            {
                                newLesson.Date = HelperClasses.WeekDayNumberToDay(lessonNumber % 7, selecteddate); // для заочников получаем дату занятия
                            }
                            var aud = (from a in cnt.Auditoriums where a.Id == newLesson.AuditoriumId select a).First();
                            if (!CheckAuditoriumEmpty(newLesson.AuditoriumId, newLesson.RegulatoryActionId, newLesson.RingId, newLesson.Day, upweek) ||
                                !AuditoriumSizeOk(newLesson.RegulatoryActionId, aud, out students))
                            {
                                ErrorInfo += "Аудитория не подходит!";
                                newLesson.AuditoriumId = 1;
                            }
                            cnt.Lessons.AddObject(newLesson);
                        }
                        else // если мы её уже назанчали
                        {
                            var les = checklessons.First();
                            //Console.WriteLine("2) Number = {0} Day = {1}", (int)(lessonNumber / 7) + 1, lessonNumber % 7);
                            les.RingId = (lessonNumber / 7) + 1;
                            les.RegulatoryActionId = s._Regaction;
                            les.Period = upweek;
                            les.AuditoriumId = s._AudID;
                            //MessageBox.Show(s._AudID.ToString());
                            if (studytype == 1) // очник
                            {
                                les.Day = (lessonNumber % 7);
                                les.Date = DateTime.Now;
                            }
                            else if (studytype == 2) // заочник
                            {
                                les.Date = HelperClasses.WeekDayNumberToDay(lessonNumber % 7,selecteddate);
                            }
                            var aud = (from a in cnt.Auditoriums where a.Id == les.AuditoriumId select a).First();
                            if (!CheckAuditoriumEmpty(les.AuditoriumId, les.RegulatoryActionId, les.RingId, les.Day, upweek) ||
                                !AuditoriumSizeOk(les.RegulatoryActionId, aud, out students))
                            {
                                ErrorInfo += "Аудитория не подходит!";
                                les.AuditoriumId = 1;
                            }
                            cnt.Refresh(System.Data.Objects.RefreshMode.ClientWins, les);
                        }
                        cnt.SaveChanges();

                    }
                    ++lessonNumber;
                }
            }

            if (saved_ok) ShedLoadByGroup();
        }
 public void Import()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         foreach (var g in readeddepartment)
         {
             if (g.Add)
             {
                 Department newDepartment = new Department()
                 {
                     Abbreviation = g.Name,
                     Name = g.Name,
                     //Id = g.Id,
                     FacultyId = 1,
                 };
                 cnt.Departments.AddObject(newDepartment);
             }
         }
         cnt.SaveChanges();
         Department virtualDepartment = new Department()
         {
             Abbreviation = "VIRT",
             Name = "Virtual",
             FacultyId = 1,
         };
         cnt.Departments.AddObject(virtualDepartment);
         Auditorium virtualAudit = new Auditorium()
         {
             Building = 1,
             Number = "VIRTUAL",
             Seats = 9999999,
             Department = virtualDepartment,
             OpeningDate = "",
             ClosingDate = "",
         };
         cnt.Auditoriums.AddObject(virtualAudit);
         cnt.SaveChanges();
     }
 }
Example #20
0
 // проверяет, подходит ли аудитория по размеру для заданного занятия
 bool AuditoriumSizeOk(int regactionID, Auditorium auditorium, out int need_seats)
 {
     need_seats = 0;
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var res = (from c in cnt.Curriculums.Include("Group") where c.RegulatoryActionId == regactionID select c);
         foreach (var c in res)
         {
             need_seats += c.Group.StudCount;
         }
     }
     if (need_seats > auditorium.Seats)
     {
         return false;
     }
     return true;
 }
Example #21
0
        // оценка расписания в пределах [0..1], больше - лучше
        double GetScheduleMark()
        {
            double score = 0;
            double max_score = 1;
            int windows_count = 0;
            int groups_count = 0;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                // если пар меньше чем по плану то распиание не составлено и не может иметь хорошую оценку
                int lessonsByCur = 0;
                int lessonsInDB = 0;
                var regaction = (from r in cnt.RegulatoryActions select r);
                foreach (var r in regaction)
                {
                    int lesByCur = 0;
                    if (r.Hours < 80)
                        lesByCur = 4;
                    if (r.Hours < 60)
                        lesByCur = 3;
                    if (r.Hours < 40)
                        lesByCur = 2;
                    if (r.Hours < 20)
                        lesByCur = 1;
                    lessonsByCur += lesByCur;
                }
                var les = (from l in cnt.Lessons select l);
                lessonsInDB = les.Count();

                var grps = (from g in cnt.Groups select g.Id);
                foreach (var g in grps)
                {
                    windows_count += GroupWindows(g);
                }

                groups_count = grps.Count();
                max_score = lessonsInDB * 5 + groups_count * 14; // всего 5 критериев
                if (lessonsByCur > lessonsInDB)
                {
                    //return 0;
                    max_score = -max_score;
                }
                //начинаем проверки
                foreach (var l in les)
                {
                    // если аудитория используется только этим занятием => ++score
                    if (CheckAuditoriumEmpty(l.AuditoriumId, l.RegulatoryActionId, l.RingId, l.Day, l.Period)) ++score;
                    // достаточно ли мест?
                    int seats;
                    if (AuditoriumSizeOk(l.RegulatoryActionId, l.Auditorium, out seats)) ++score;
                    // если это лабы, то есть ли оборудование для них в аудитории
                    ++score; // пока нет информации о типе аудитории
                    // преподаватель ведёт в это время только эту пару
                    if (!TeacherOverlapping(l.RegulatoryAction.AcademicLoad.First().EmployeId,l.RingId,l.Day,l.Period)) ++score;
                    // свободна ли группа?
                    if (!GroupOverlapping(l.RegulatoryAction.Curriculum.First().GroupId,l.RingId,l.Day,l.Period)) ++score;
                }

            }
            return (score + (groups_count * 14 - windows_count))/max_score;
        }
Example #22
0
 // проверка, свободны ли все группы из потока
 bool CheckFlowOk(int regaction, int number, int day)
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var currs = (from r in cnt.Curriculums where r.RegulatoryActionId == regaction select r);
         foreach (var cur in currs)
         {
             //проверим, свободно ли время для каждой группы из потока
             int groupId = cur.GroupId;
             var currsForFlowGroup = (from c in cnt.Curriculums where c.GroupId == groupId select c);
             foreach (var currForFlowGroup in currsForFlowGroup)
             {
                 var res = (from l in cnt.Lessons where l.RingId == number && l.Day == day && l.Period == upweek && currForFlowGroup.RegulatoryActionId == l.RegulatoryActionId select l);
                 if (res.Count() > 0)
                 {
                     return false;
                 }
             }
         }
     }
     return true;
 }
Example #23
0
 // проверка накладок у группы
 bool GroupOverlapping(int groupID, int number, int day, bool weektype)
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var cur = (from c in cnt.Curriculums where c.GroupId == groupID select c.GroupId);
         var les = (from l in cnt.Lessons where l.RingId == number && l.Day == day &&
                    l.Period == weektype && cur.Contains(l.RegulatoryActionId) select l);
         if (les.Count() > 1) return true;
         return false;
     }
 }
Example #24
0
        // возвращает номера клеток, когда преподаватель занят
        List<int> CheckTeacher(int weekType, string teacherName)
        {
            //int found = 0;
            int number;
            int day;
            List<int> busyLessons = new List<int>();
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                //ищем преподавателя по имени
                var teacher = (from c in cnt.Employees where c.Name == teacherName select c).First();
                //смотрим какие мероприятия его
                var teachersAcademicLoad = (from r in cnt.AcademicLoadSet where r.Employe.Id == teacher.Id select r);
                foreach (var tAL in teachersAcademicLoad)
                {
                    //выбираем мероприятия преподавателя
                    var teacherLessons = (from l in cnt.Lessons where tAL.RegulatoryAction.Id == l.RegulatoryAction.Id select l);
                    foreach (var tL in teacherLessons)
                    {
                        for (int i = 0; i < 49; ++i)
                        {
                            HelperClasses.indexToNumberDay(i, out number, out day);
                            if (number == tL.RingId && day == tL.Day && tL.Period == upweek)
                            {
                                var res = (from r in cnt.Curriculums where r.RegulatoryActionId == tL.RegulatoryActionId select r);
                                if (res.Count() == 1)
                                {
                                    if (SelectedGroup.Id != res.First().GroupId)
                                        busyLessons.Add(i);
                                }
                                else if (res.Count() > 1)
                                {
                                    bool inFlow = false; // не предупреждать, если это поток с выбранной группой
                                    foreach (var c in res)
                                    {
                                        if (SelectedGroup.Id == c.GroupId) inFlow = true;
                                    }
                                    if (!inFlow) busyLessons.Add(i); //found = tL.RegulatoryActionId;
                                }
                            }
                        }

                    }
                }
            }
            return busyLessons;
        }
Example #25
0
        // количество окон группы
        int GroupWindows(int groupID)
        {
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                int windows_count = 0;
                bool weektype = true;
                for (int k = 0; k < 2; ++k)
                {
                    bool[,] timetable = new bool[7, 7];
                    int i;
                    int j;
                    for (i = 0; i < 7; ++i)
                        for (j = 0; j < 7; ++j)
                            timetable[i, j] = false;

                    var cur = (from c in cnt.Curriculums where c.GroupId == groupID select c.RegulatoryActionId);
                    // проверка верхней и нижней недели
                    var les = (from l in cnt.Lessons where l.Period == weektype && cur.Contains(l.RegulatoryActionId) select l);
                    foreach (var l in les)
                    {
                        timetable[l.RingId - 1, l.Day] = true;
                    }
                    for (j = 0; j < 7; ++j)
                    {
                        bool start = false;
                        bool end = false;
                        for (i = 0; i < 7; ++i)
                        {
                            if (timetable[i, j])
                            {
                                if (!start)
                                {
                                    start = true;
                                }
                                if (end)
                                {
                                    ++windows_count;
                                    break;
                                }
                            }
                            else
                            {
                                if (start)
                                {
                                    end = true;
                                }
                            }
                        }
                    }
                    weektype = !weektype;
                }
                return windows_count;
            }
        }
Example #26
0
 void PrepairTestData()
 {
     using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
     {
         var aud = (from a in cnt.Auditoriums select a);
         StreamWriter outfile = new StreamWriter("dstu.cfg", false);
         var prof = (from e in cnt.Employees select e);
         foreach (var p in prof)
         {
             outfile.WriteLine();
             outfile.WriteLine("#prof");
             outfile.WriteLine("	id = " + p.Id);
             //outfile.WriteLine("	name = " + p.Name);
             outfile.WriteLine("	name = " + p.Id);
             outfile.WriteLine("#end");
         }
         var cource = (from s in cnt.Subjects select s);
         foreach (var c in cource)
         {
             outfile.WriteLine();
             outfile.WriteLine("#course");
             outfile.WriteLine("	id = " + c.Id);
             //outfile.WriteLine("	name = " + c.Name);
             outfile.WriteLine("	name = " + c.Id);
             outfile.WriteLine("#end");
         }
         foreach (var a in aud)
         {
             outfile.WriteLine();
             outfile.WriteLine("#room");
             //outfile.WriteLine("	name = " + a.Number);
             outfile.WriteLine("	name = a" + a.Id);
             outfile.WriteLine("	lab = false");
             outfile.WriteLine("	size = " + a.Seats);
             outfile.WriteLine("#end");
         }
         var group = (from g in cnt.Groups select g);
         foreach (var g in group)
         {
             outfile.WriteLine();
             outfile.WriteLine("#group");
             outfile.WriteLine("	id = " + g.Id);
             //outfile.WriteLine("	name = " + g.GroupAbbreviation);
             outfile.WriteLine("	name = " + g.Id);
             outfile.WriteLine("	size = " + g.StudCount);
             outfile.WriteLine("#end");
         }
         var clas = (from c in cnt.Curriculums.Include("RegulatoryAction") select c);
         foreach (var c in clas)
         {
             outfile.WriteLine();
             outfile.WriteLine("#class");
             outfile.WriteLine("	professor = " + c.RegulatoryAction.AcademicLoad.First().EmployeId);
             outfile.WriteLine("	course = " + c.SubjectId);
             outfile.WriteLine("	duration = 1");
             outfile.WriteLine("	group = " + c.GroupId);
             //outfile.WriteLine("	lab = false");
             outfile.WriteLine("#end");
         }
         outfile.Close();
     }
 }
        public void Import()
        {
            int lines_count = readedstrings.Where(x => x.Add).Count();
            int i = 0;
            using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
            {
                int depId = ReadedStrings.First().KafedraId;
                //Department department = (from lt in cnt.Departments where lt.Id == depId select lt).First();
                foreach (var res in ReadedStrings.Where(x => x.Add))
                {
                    if (res.SubjectType == 0) continue;
                    //LessonsType lessontype = (from lt in cnt.LessonsTypes where lt.Id == res.SubjectType select lt).First();
                    RegulatoryAction regaction = new RegulatoryAction()
                    {
                        LessonsTypeId = res.SubjectType,
                        Hours = res.Time,
                        DepartmentId = depId,
                    };
                    cnt.RegulatoryActions.AddObject(regaction);

                    IEnumerable<Employe> teachers = (from e in cnt.Employees where e.Name == res.Name2 select e);
                    Employe teacher = null;
                    if (teachers.Count() == 0)
                    {
                        //нет такого преподавателя, добавим его
                        teacher = new Employe()
                        {
                            Name = res.Name2,
                            FacultyId = 1,
                            TitleId = 1,
                            DegreeId = 1,
                        };
                        cnt.Employees.AddObject(teacher);
                        //cnt.SaveChanges();
                    }
                    else teacher = teachers.First();

                    AcademicLoad academicload = new AcademicLoad()
                    {
                        RegulatoryAction = regaction,
                        Employe = teacher
                    };
                    cnt.AcademicLoadSet.AddObject(academicload);

                    ///
                    IEnumerable<Subject> subjects = (from e in cnt.Subjects where e.Name == res.Subject select e);
                    Subject subject = null;
                    if (subjects.Count() == 0)
                    {
                        //нет такого предмета, добавим его
                        subject = new Subject()
                        {
                            Name = res.Subject,
                            Abbreviation = "",
                        };
                        cnt.Subjects.AddObject(subject);
                        Console.WriteLine("subj not found = " + res.Subject);
                    }
                    else
                    {
                        subject = subjects.First();
                        Console.WriteLine("subj found = " + subject.Name);
                    }
                    ///

                    ///
                    string [] splitedGroups = res.Groups.Split(';');
                    foreach (var splitedGroup in splitedGroups)
                    {
                        string trimedGroup = splitedGroup.Trim();
                        Console.WriteLine(res.Groups + "       " + trimedGroup);
                        IEnumerable<Group> groups = (from e in cnt.Groups.Include("EduPeriod") where e.GroupAbbreviation == trimedGroup select e);
                        Group group = null;
                        if (groups.Count() == 0)
                        {
                            Console.WriteLine("group not found = " + trimedGroup);
                            continue;
                        }
                        else
                        {
                            group = groups.First();
                            Console.WriteLine("group found = " + trimedGroup);
                            if (group.EduPeriod.Count == 0)
                            {
                                EduPeriod e = new EduPeriod
                                {
                                    Begin = DateTime.Parse(res.Date.Substring(0, 10)),
                                    End = DateTime.Parse(res.Date.Substring(10, 10)),
                                    GroupId = group.Id,
                                };
                                cnt.EduPeriods.AddObject(e);
                            }
                        }
                        ///

                        Curriculum curr = new Curriculum()
                        {
                            RegulatoryAction = regaction,
                            Subject = subject,
                            Group = group,
                        };
                        cnt.Curriculums.AddObject(curr);
                        cnt.SaveChanges();
                    }
                    ++i;
                    Message = "Выполняется импорт нагрузки. Добавлено " + i + " из " + lines_count;
                    DoEvents();
                }
                //cnt.SaveChanges();
            }
        }