Example #1
0
        public ActionResult NewTeacher(ListTeacherViewModel model)
        {
            // Agrega un nuevo profesor al sistema
            try
            {
                if (ModelState.IsValid) // Checkea los DataAnnotations de ListTeacherViewModel, o sea los [Required]
                {
                    // Si es un modelo válido, agregar el nuevo profe a la base
                    using (Models.DBContainer db = new Models.DBContainer())
                    {
                        Teacher teacher = new Teacher();
                        teacher.first_name = model.first_name;
                        teacher.last_name  = model.last_name;
                        teacher.active     = model.active;

                        db.Teachers.Add(teacher);
                        db.SaveChanges();
                    }
                    return(RedirectToAction("ListTeachers", "Admin"));
                }
                return(View(model));
            }
            catch (Exception exc)
            {
                throw new Exception(exc.Message);
            }
        }
Example #2
0
 public ActionResult EditTeacher(int id)
 {
     // Muestra los datos del profe a editar
     try
     {
         ListTeacherViewModel model = new ListTeacherViewModel();
         using (Models.DBContainer db = new Models.DBContainer())
         {
             Teacher teacher = db.Teachers.Find(id);
             if (teacher == null)
             {
                 TempData["Alert"] = "An error occurred, try again later";
                 return(RedirectToAction("ListTeachers"));
             }
             model.id_teacher = teacher.id_teacher;
             model.first_name = teacher.first_name;
             model.last_name  = teacher.last_name;
             model.active     = teacher.active;
         }
         return(View(model));
     }
     catch (Exception exc)
     {
         throw new Exception(exc.Message);
     }
 }
Example #3
0
 private void PopulateDropDownList()
 {
     // Rellena el DropDownList con los nombres de los profesores
     try
     {
         List <DropDownListTeacherViewModel> lst_teachers;
         using (Models.DBContainer db = new Models.DBContainer())
         {
             lst_teachers = (from teacher in db.Teachers
                             select new DropDownListTeacherViewModel
             {
                 id_teacher = teacher.id_teacher,
                 name = teacher.first_name + " " + teacher.last_name
             }).ToList();
         }
         List <SelectListItem> lst_items = lst_teachers.ConvertAll(i =>
         {
             return(new SelectListItem()
             {
                 Text = i.name,
                 Value = i.id_teacher.ToString(),
                 Selected = false
             });
         });
         ViewBag.items = lst_items;
     }
     catch (Exception exc)
     {
         throw new Exception(exc.Message);
     }
 }
Example #4
0
 public ActionResult EditSubject(int id)
 {
     // Carga los datos de la materia a modificar
     try
     {
         ListSubjectViewModelAdmin model = new ListSubjectViewModelAdmin();
         using (Models.DBContainer db = new Models.DBContainer())
         {
             Subject subject = db.Subjects.Find(id);
             if (subject == null)
             {
                 TempData["Alert"] = "An error occurred, try again later";
                 return(RedirectToAction("ListSubjects"));
             }
             model.id_subject  = subject.id_subject;
             model.name        = subject.name;
             model.description = subject.desc;
             model.capacity    = subject.capacity;
             model.time_from   = subject.time_from;
             model.time_to     = subject.time_to;
             model.id_teacher  = subject.id_teacher;
         }
         PopulateDropDownList();
         return(View(model));
     }
     catch (Exception exc)
     {
         throw new Exception(exc.Message);
     }
 }
Example #5
0
 public ActionResult ListSubjects()
 {
     // Lista todas las materias del sistema
     try
     {
         List <ListSubjectViewModelAdmin> lst_subjects;
         using (Models.DBContainer db = new Models.DBContainer())
         {
             // Obtengo la lista de todas las materias
             lst_subjects = (from subject in db.Subjects
                             select new ListSubjectViewModelAdmin
             {
                 id_subject = subject.id_subject,
                 name = subject.name,
                 description = subject.desc,
                 time_from = subject.time_from,
                 time_to = subject.time_to,
                 capacity = subject.capacity,
                 id_teacher = subject.id_teacher
             }).ToList();
         }
         return(View(lst_subjects));
     }
     catch
     {
         TempData["Alert"] = "An error occurred, try again later";
         return(RedirectToAction("Index", "Home"));
     }
 }
Example #6
0
 public ActionResult ListTeachers()
 {
     // Lista todos los profesores de la base de datos
     try
     {
         List <ListTeacherViewModel> lst_teachers;
         using (Models.DBContainer db = new Models.DBContainer())
         {
             // Obtengo la lista de todos los profes
             lst_teachers = (from teacher in db.Teachers
                             select new ListTeacherViewModel
             {
                 id_teacher = teacher.id_teacher,
                 first_name = teacher.first_name,
                 last_name = teacher.last_name,
                 active = teacher.active
             }).ToList();
         }
         return(View(lst_teachers));
     }
     catch
     {
         TempData["Alert"] = "An error occurred, try again later";
         return(RedirectToAction("Index", "Home"));
     }
 }
Example #7
0
        public ActionResult EditTeacher(ListTeacherViewModel model)
        {
            // Edita al profe y lo persiste en la base de datos
            try
            {
                if (ModelState.IsValid)
                {
                    using (Models.DBContainer db = new Models.DBContainer())
                    {
                        Teacher teacher = db.Teachers.Find(model.id_teacher);
                        if (teacher == null)
                        {
                            TempData["Alert"] = "An error occurred, try again later";
                            return(RedirectToAction("ListTeachers"));
                        }
                        teacher.first_name = model.first_name;
                        teacher.last_name  = model.last_name;
                        teacher.active     = model.active;

                        db.Entry(teacher).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    return(RedirectToAction("ListTeachers", "Admin"));
                }
                return(View(model));
            }
            catch (Exception exc)
            {
                throw new Exception(exc.Message);
            }
        }
Example #8
0
        public ActionResult ListSubjects()
        {
            // Muestra la lista de materias para que el estudiante se inscriba
            try
            {
                List <ListSubjectViewModelStudent> lst_subjects;
                using (Models.DBContainer db = new Models.DBContainer())
                {
                    int id_student = ((Student)Session["User"]).id_student;

                    // Obtengo la lista de las materias a las que está inscripto el estudiante
                    List <int> lst_student_subjects = (from sub_stu in db.Subjects_Students
                                                       where sub_stu.id_student == id_student
                                                       select sub_stu.id_subject).ToList();


                    // Obtengo la lista de todas las materias en las que el estudiante no esté inscripto,
                    // filtrando las que sean de un profesor no activo y ordenándolas alfabéticamente
                    lst_subjects = (from subject in db.Subjects
                                    join teacher in db.Teachers
                                    on subject.id_teacher equals teacher.id_teacher
                                    where teacher.active == true &&
                                    !lst_student_subjects.Contains(subject.id_subject)
                                    orderby subject.name
                                    select new ListSubjectViewModelStudent
                    {
                        id_subject = subject.id_subject,
                        name = subject.name,
                        time_from = subject.time_from,
                        time_to = subject.time_to,
                        capacity = subject.capacity,
                        teacher_name = teacher.last_name + ", " + teacher.first_name
                    }).ToList();

                    // Ahora que tengo la lista de todas las materias a mostrar en el view,
                    // relleno el campo remaining_places a cada una
                    foreach (var subject in lst_subjects)
                    {
                        subject.remaining_places = subject.capacity - GetInscriptionsCount(subject.id_subject);
                    }

                    // Ahora que cada materia tiene su cupo calculado, filtro y saco las
                    // materias que no tengan cupo
                    lst_subjects = (from item in lst_subjects
                                    where item.remaining_places != 0
                                    select item).ToList();
                }
                return(View(lst_subjects));
            }
            catch
            {
                TempData["Alert"] = "An error occurred, try again later";
                return(RedirectToAction("Index", "Home"));
            }
        }
Example #9
0
 private int GetInscriptionsCount(int id_subject)
 {
     // Obtiene la cantidad de inscriptos en una materia
     try
     {
         using (Models.DBContainer db = new Models.DBContainer())
         {
             return((from sub_stu in db.Subjects_Students
                     where sub_stu.id_subject == id_subject
                     select sub_stu).Count());
         }
     }
     catch
     {
         throw new Exception("Couldn't retrieve number of inscriptions");
     }
 }
Example #10
0
        public ActionResult EditSubject(ListSubjectViewModelAdmin model)
        {
            // Modifica la materia y la persiste en la base de datos
            try
            {
                if (ModelState.IsValid)
                {
                    using (Models.DBContainer db = new Models.DBContainer())
                    {
                        Subject subject = db.Subjects.Find(model.id_subject);
                        if (subject == null)
                        {
                            TempData["Alert"] = "An error occurred, try again later";
                            return(RedirectToAction("ListSubjects"));
                        }
                        subject.name       = model.name;
                        subject.desc       = model.description;
                        subject.capacity   = model.capacity;
                        subject.time_from  = model.time_from;
                        subject.time_to    = model.time_to;
                        subject.id_teacher = model.id_teacher;

                        if (subject.time_to <= subject.time_from)
                        {
                            // Horario no válido
                            ViewData["Error"] = "Ending time must be strictly greater than starting time";
                            PopulateDropDownList();
                            return(View(model));
                        }

                        db.Entry(subject).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    return(RedirectToAction("ListSubjects", "Admin"));
                }
                // Si el modelo no es válido, tengo que volver a la misma pantalla, con
                // lo cual hay que rellenar de nuevo el DropDownList
                PopulateDropDownList();
                return(View(model));
            }
            catch (Exception exc)
            {
                throw new Exception(exc.Message);
            }
        }
Example #11
0
        public ActionResult Login(string DNI, string file_number, string username, string password)
        {
            try
            {
                using (Models.DBContainer db = new Models.DBContainer())
                {
                    object dbUser;

                    if (username != "")
                    {
                        // Uso linq para obtener el admin
                        dbUser = (from user in db.Admins
                                  where user.username == username && user.password == password
                                  select user).FirstOrDefault();
                    }
                    else
                    {
                        // Uso linq para obtener el student
                        dbUser = (from user in db.Students
                                  where user.DNI == DNI && user.file_number == file_number
                                  select user).FirstOrDefault();
                    }

                    if (dbUser == null)
                    {
                        ViewData["Error"] = "Incorrect data";
                        return(View());
                    }

                    // El usuario existe, lo guardo en Session
                    Session["User"] = dbUser;
                }

                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception exc)
            {
                // Si hubo un error, capturo el mensaje del mismo para mostrarlo en la vista
                ViewData["Error"] = exc.Message;
                return(View());
            }
        }
Example #12
0
        public ActionResult NewSubject(ListSubjectViewModelAdmin model)
        {
            // Crea una nueva materia y la guarda en el sistema
            try
            {
                if (ModelState.IsValid)
                {
                    using (Models.DBContainer db = new Models.DBContainer())
                    {
                        Subject subject = new Subject();
                        subject.name       = model.name;
                        subject.desc       = model.description;
                        subject.capacity   = model.capacity;
                        subject.time_from  = model.time_from;
                        subject.time_to    = model.time_to;
                        subject.id_teacher = model.id_teacher;

                        if (subject.time_to <= subject.time_from)
                        {
                            // Horario no válido
                            ViewData["Error"] = "Ending time must be strictly greater than starting time";
                            PopulateDropDownList();
                            return(View(model));
                        }

                        db.Subjects.Add(subject);
                        db.SaveChanges();
                    }
                    return(RedirectToAction("ListSubjects", "Admin"));
                }
                // Si el modelo no es válido, tengo que volver a la misma pantalla, con
                // lo cual hay que rellenar de nuevo el DropDownList
                PopulateDropDownList();
                return(View(model));
            }
            catch (Exception exc)
            {
                throw new Exception(exc.Message);
            }
        }
Example #13
0
 public ActionResult DeleteSubject(int id)
 {
     // Elimina la materia cuyo id_subject es id
     try
     {
         using (Models.DBContainer db = new Models.DBContainer())
         {
             Subject subject = db.Subjects.Find(id);
             if (subject == null)
             {
                 TempData["Alert"] = "An error occurred, try again later";
                 return(RedirectToAction("ListSubjects"));
             }
             db.Subjects.Remove(subject);
             db.SaveChanges();
         }
         return(RedirectToAction("ListSubjects", "Admin"));
     }
     catch (Exception exc)
     {
         throw new Exception(exc.Message);
     }
 }
Example #14
0
 public ActionResult DeleteTeacher(int id)
 {
     // Elimina al profesor del sistema
     try
     {
         using (Models.DBContainer db = new Models.DBContainer())
         {
             Teacher teacher = db.Teachers.Find(id);
             if (teacher == null)
             {
                 TempData["Alert"] = "An error occurred, try again later";
                 return(RedirectToAction("ListTeachers"));
             }
             db.Teachers.Remove(teacher);
             db.SaveChanges();
         }
         return(RedirectToAction("ListTeachers", "Admin"));
     }
     catch (Exception exc)
     {
         throw new Exception(exc.Message);
     }
 }
Example #15
0
        public ActionResult Subject(int id)
        {
            // Muestra la información de la materia de acuerdo al id
            try
            {
                ListSubjectViewModelStudent subject_view_model;
                using (Models.DBContainer db = new Models.DBContainer())
                {
                    int id_student = ((Student)Session["User"]).id_student;

                    // Veo si el alumno ya está inscripto en la materia revisando los registros
                    // de la tabla Subjects_Students
                    var course = (from sub_stu in db.Subjects_Students
                                  where sub_stu.id_student == id_student && sub_stu.id_subject == id
                                  select sub_stu).FirstOrDefault();

                    if (course != null)
                    {
                        // El estudiante ya está inscripto, mandar a la lista de materias con un mensaje
                        TempData["Alert"] = "You're already enrolled in this subject";
                        return(RedirectToAction("ListSubjects", "Student"));
                    }

                    // Obtengo información de la materia para después chequear que
                    // sea una materia de un profesor activo y que cuente con cupo
                    var info_subject = (from teacher in db.Teachers
                                        join subject in db.Subjects
                                        on teacher.id_teacher equals subject.id_teacher
                                        where subject.id_subject == id
                                        select new { teacher.active, subject.capacity }).FirstOrDefault();

                    if (info_subject == null)
                    {
                        TempData["Alert"] = "An error occurred, try again later";
                        return(RedirectToAction("ListSubjects", "Student"));
                    }

                    // Reviso que la materia pertenezca a un profesor activo
                    if (!info_subject.active)
                    {
                        TempData["Alert"] = "The course is not available in this moment, try again later";
                        return(RedirectToAction("ListSubjects", "Student"));
                    }

                    // Reviso que la materia tenga cupo disponible
                    int inscriptions_count = GetInscriptionsCount(id);
                    if (inscriptions_count >= info_subject.capacity)
                    {
                        // No hay cupo
                        TempData["Alert"] = "The course is full, try again later";
                        return(RedirectToAction("ListSubjects", "Student"));
                    }

                    // Si paso todos los filtros, mostrar la información de la materia
                    // con el botón para inscribirse
                    subject_view_model = (from subject in db.Subjects
                                          join teacher in db.Teachers
                                          on subject.id_teacher equals teacher.id_teacher
                                          where subject.id_subject == id
                                          select new ListSubjectViewModelStudent
                    {
                        id_subject = subject.id_subject,
                        name = subject.name,
                        description = subject.desc,
                        time_from = subject.time_from,
                        time_to = subject.time_to,
                        capacity = subject.capacity,
                        remaining_places = subject.capacity - inscriptions_count,
                        teacher_name = teacher.last_name + ", " + teacher.first_name
                    }).FirstOrDefault();
                }

                if (subject_view_model == null)
                {
                    TempData["Alert"] = "An error occurred, try again later";
                    return(RedirectToAction("Index", "Home"));
                }

                return(View(subject_view_model));
            }
            catch
            {
                TempData["Alert"] = "An error occurred, try again later";
                return(RedirectToAction("Index", "Home"));
            }
        }
Example #16
0
        public ActionResult Enroll(int id_subject)
        {
            // Recibe por post el id de la materia y trata de inscribirte a la misma
            try
            {
                using (Models.DBContainer db = new Models.DBContainer())
                {
                    int id_student = ((Student)Session["User"]).id_student;

                    // Esto es lo mismo de un metodo anterior que esta arriba... hacer alguna funcion para no repetir el codigo
                    // Veo si el alumno ya está inscripto en la materia revisando los registros
                    // de la tabla Subjects_Students
                    var course = (from sub_stu in db.Subjects_Students
                                  where sub_stu.id_student == id_student && sub_stu.id_subject == id_subject
                                  select sub_stu).FirstOrDefault();

                    if (course != null)
                    {
                        // El estudiante ya está inscripto, mandar a la lista de materias con un mensaje
                        ViewData["EnrollMessage"] = "You're already enrolled in this subject";
                        ViewData["TypeMessage"]   = "alert-warning";
                        return(View());
                    }

                    // Obtengo la lista de los horarios de todas las materias en las que el
                    // estudiante se inscribió
                    var lst_schedules = (from subject in db.Subjects
                                         join sub_stu in db.Subjects_Students
                                         on subject.id_subject equals sub_stu.id_subject
                                         where sub_stu.id_student == id_student
                                         select new Schedule
                    {
                        time_from = subject.time_from,
                        time_to = subject.time_to
                    }).ToList();

                    // Obtengo el horario de la materia a la cual se desea inscribir
                    var subject_schedule = (from subject in db.Subjects
                                            where subject.id_subject == id_subject
                                            select new Schedule
                    {
                        time_from = subject.time_from,
                        time_to = subject.time_to
                    }).FirstOrDefault();

                    if (subject_schedule == null)
                    {
                        ViewData["EnrollMessage"] = "An error occurred, try again later";
                        ViewData["TypeMessage"]   = "alert-danger";
                        return(View());
                    }

                    // Recorro la lista de horarios de las inscripciones del estudiante
                    // buscando si hay algun solapamiento de horarios
                    foreach (var schedule in lst_schedules)
                    {
                        if (StartsInMiddle(schedule, subject_schedule) ||
                            StartsInMiddle(subject_schedule, schedule))
                        {
                            ViewData["EnrollMessage"] = "This course overlaps with any other subject that you already enrolled. You can't enroll in this course";
                            ViewData["TypeMessage"]   = "alert-info";
                            return(View());
                        }
                    }

                    // Si llegó hasta acá significa que no hay horarios solapados...
                    // Inscribirlo en la materia

                    Subject_Student new_subject_student = new Subject_Student();
                    new_subject_student.id_student = ((Student)Session["User"]).id_student;
                    new_subject_student.id_subject = id_subject;

                    db.Subjects_Students.Add(new_subject_student);
                    db.SaveChanges();
                }
                ViewData["EnrollMessage"] = "The enrollment has been successful";
                ViewData["TypeMessage"]   = "alert-success";
                return(View());
            }
            catch
            {
                ViewData["EnrollMessage"] = "An error occurred, try again later";
                ViewData["TypeMessage"]   = "alert-danger";
                return(View());
            }
        }