Example #1
0
        public static bool Save(CourseDTO courseDto)
        {
            Database database = new Database();

            if (!database.OpenConnection())
            {
                // FIXME: throw exception;
                return(false);
            }

            // Insert items into database
            database.command.CommandText = "INSERT INTO courses(name) VALUES (@name)";

            // bind some shit
            database.command.Parameters.AddWithValue("name", courseDto.Name);

            int result = database.command.ExecuteNonQuery();

            database.CloseConnection();

            if (result > 0)
            {
                return(true);
            }
            return(false);
        }
Example #2
0
        public ActionResult <CourseDTO> Put(CourseDTO course)
        {
            if (course == null)
            {
                //return 400 bad reqeust.
                return(BadRequest());
            }

            if (course.CourseID <= 0)
            {
                //return 404 not found.
                return(NotFound());
            }

            var target = Repository.GetCourse(course.CourseID);

            if (target == null)
            {
                //return 404 not found.
                return(NotFound());
            }

            course = Repository.UpdateCourse(course);

            return(course);
        }
        public async Task <IHttpActionResult> Edit(CourseDTO courseDTO, int id)//se devuelve un modelo
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (courseDTO.CourseID != id)
            {
                return(BadRequest());
            }

            var flag = await courseService.GetById(id);

            if (flag == null)
            {
                return(NotFound());
            }

            try
            {
                var course = _mapper.Map <Course>(courseDTO);
                course = await courseService.Update(course);

                return(Ok(course));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        //public async Task<IActionResult> Edit(int id, [Bind("CourseID,Title,Credits")] Course course)
        public async Task<IActionResult> Edit(int id, CourseDTO courseDTO)

        {
            if (id != courseDTO.CourseID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                //try
                //{
                //    _context.Update(course);
                //    await _context.SaveChangesAsync();
                //}
                //catch (DbUpdateConcurrencyException)
                //{
                //    if (!CourseExists(course.CourseID))
                //    {
                //        return NotFound();
                //    }
                //    else
                //    {
                //        throw;
                //    }
                //}
                var course = mapper.Map<Course>(courseDTO);
                course = await _courseService.Update(course);
                return RedirectToAction(nameof(Index));
            }
            return View(courseDTO);
        }
Example #5
0
        private List <CourseDTO> loadXml(string path)
        {
            List <CourseDTO> _courseList = new List <CourseDTO>();
            XmlDocument      doc         = new XmlDocument();

            doc.Load(path);
            XmlNodeList nodes = doc.DocumentElement.SelectNodes("/models/model");

            foreach (XmlNode node in nodes)
            {
                CourseDTO course = new CourseDTO();
                course.Name        = node.SelectSingleNode("Name").InnerText;
                course.Description = node.SelectSingleNode("Description").InnerText;
                course.Objective   = node.SelectSingleNode("Objective").InnerText;
                course.Price       = node.SelectSingleNode("Price").InnerText;
                course.Caution     = node.SelectSingleNode("Cautions").InnerText;
                course.Remarks     = node.SelectSingleNode("Remarks").InnerText;
                _courseList.Add(course);
            }

            foreach (CourseDTO course in _courseList)
            {
                Console.WriteLine(course.Name);
            }
            return(_courseList);
        }
        public async Task <IHttpActionResult> Put(CourseDTO courseDTO, int id)//objet=> body/primitivo => url
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));//status code 400
            }
            if (courseDTO.CourseID != id)
            {
                return(BadRequest());
            }

            var flag = await courseService.GetById(id);

            if (flag == null)
            {
                return(NotFound());   //status code 404
            }
            try
            {
                var course = mapper.Map <Course>(courseDTO);
                course = await courseService.Update(course);

                return(Ok(courseDTO));//status code 200
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));//status code 500
            }
        }
Example #7
0
        public async Task <CourseDTO> GetCourseAsync(int courseId)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accountProvider.AccountInfo.Token);

                try
                {
                    var respnse = await client.GetAsync(AccountProvider.BASEURL + "/api/Courses/" + courseId);

                    if (respnse.StatusCode != HttpStatusCode.OK)
                    {
                        return(null);
                    }

                    var stringResult = await respnse.Content.ReadAsStringAsync();

                    CourseDTO result = JsonConvert.DeserializeObject <CourseDTO>(stringResult);


                    return(result);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
Example #8
0
        public CourseDTO UpdateCourse(CourseDTO course)
        {
            var changedObj = Database.Courses.Where(p => p.CourseId == course.CourseID).FirstOrDefault();

            if (changedObj == null || changedObj.CourseId != course.CourseID)
            {
                throw new KeyNotFoundException("Could not find a matching course in the system.");
            }

            changedObj.CourseId     = course.CourseID;
            changedObj.Name         = course.Name;
            changedObj.Credits      = course.Credits;
            changedObj.DepartmentId = course.DepartmentID;

            Database.Courses.Attach(changedObj);

            var entry = Database.Entry(changedObj);

            entry.Property(e => e.Name).IsModified         = true;
            entry.Property(e => e.Credits).IsModified      = true;
            entry.Property(e => e.DepartmentId).IsModified = true;

            Database.SaveChanges();

            return(course);
        }
        public async Task <IHttpActionResult> PostCourse(CourseDTO courseDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var courseModel = AutoMapper.Mapper.Map <CourseDTO, Course>(courseDTO);

            courseModel.CourseId = GuidGenerator.GetGuid();
            db.Courses.Add(courseModel);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CourseExists(courseModel.CourseId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = courseModel.CourseId }, courseModel));
        }
Example #10
0
        public TeamResponseDTO GetOneByUuid(string uuid)
        {
            TeamResponseDTO response = this._autoMapper.Map <TeamResponseDTO>(this.FindOneByUUID(uuid));

            if (response == null)
            {
                throw new EntityAlreadyExistsException($"Team with uuid {uuid} doesn't exist!", GeneralConsts.MICROSERVICE_NAME);
            }

            TeacherDTO teacher = this._httpClientService.SendRequest <TeacherDTO>(HttpMethod.Get, "http://localhost:40001/api/users/teachers/" + response.teacher.uuid, new UserPrincipal(_httpContextAccessor.HttpContext).token).Result;

            if (teacher == null)
            {
                throw new EntityAlreadyExistsException($"Teacher with uuid {response.teacher.uuid} doesn't exist!", GeneralConsts.MICROSERVICE_NAME);
            }
            response.teacher = teacher;

            CourseDTO course = this._httpClientService.SendRequest <CourseDTO>(HttpMethod.Get, "http://localhost:40005/api/courses/" + response.course.uuid, new UserPrincipal(_httpContextAccessor.HttpContext).token).Result;

            if (course == null)
            {
                throw new EntityAlreadyExistsException($"Course with uuid {response.course.uuid} doesn't exist!", GeneralConsts.MICROSERVICE_NAME);
            }
            response.course = course;

            return(response);
        }
        public string Post([FromBody] CourseDTO courseDTO)
        {
            ValidatorResult validatorResult = CourseValidator.IsValidCourse(courseDTO);

            if (!validatorResult.IsValid)
            {
                HttpContext.Response.StatusCode = 422;
                return(JsonConvert.SerializeObject(validatorResult.ValidationMessage));
            }

            Course course = new Course()
            {
                Name        = courseDTO.Name,
                Description = courseDTO.Description,
                Length      = courseDTO.Length,
                StartDate   = courseDTO.StartDate,
                EndDate     = courseDTO.EndDate
            };

            //Add to DB
            try
            {
                northwindContext.Add(course);
                northwindContext.SaveChanges();
                HttpContext.Response.StatusCode = 200;
                return(JsonConvert.SerializeObject("The course is successfully saved."));
            }
            catch (Exception e)
            {
                HttpContext.Response.StatusCode = 520;
                return(JsonConvert.SerializeObject(e.Message));
            }
        }
Example #12
0
        public async Task <ActionResult> DeleteCourse(int id)
        {
            string currentUserId = System.Web.HttpContext.Current.User.Identity.GetUserId();

            if (currentUserId == null)
            {
                return(new HttpUnauthorizedResult());
            }
            CourseDTO courseDTO = await CourseService.GetAsync(id);

            ViewBag.SpecialityName = courseDTO.Speciality.SpecialityName;
            ViewBag.ParentId       = courseDTO.SpecialityId;
            ViewBag.Action         = "SpecialityCourses";
            if (courseDTO != null)
            {
                OperationDetails operationDetails = await CourseService.DeleteAsync(id, currentUserId);

                if (operationDetails.Succedeed)
                {
                    return(PartialView("Report", operationDetails));
                }
                else
                {
                    ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
                    return(PartialView("Report", operationDetails));
                }
            }
            ViewBag.Message = "Non valid";
            return(PartialView("~/Views/Admin/Course/DeleteCourse.cshtml", courseDTO));
        }
Example #13
0
        // Delete a course.
        public async Task <ActionResult> DeleteCourse(int?id)
        {
            // Check id.
            if (!int.TryParse(id.ToString(), out int intId))
            {
                return(RedirectToAction("Index"));
            }
            // Get CourseDTO object.
            CourseDTO courseDTO = await CourseService.GetAsync(intId);

            if (courseDTO == null)
            {
                return(RedirectToAction("Index"));
            }
            ViewBag.SpecialityName = courseDTO.Speciality.SpecialityName;
            ViewBag.ParentId       = courseDTO.SpecialityId;
            // AutoMapper Setup.
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <CourseDTO, CourseViewModel>()
                .ForMember("Id", opt => opt.MapFrom(obj => obj.CourseId))
                .ForMember("Name", opt => opt.MapFrom(obj => obj.CourseTitle));
            });
            IMapper         iMapper = config.CreateMapper();
            CourseViewModel source  = iMapper.Map <CourseDTO, CourseViewModel>(courseDTO);

            return(PartialView("~/Views/Admin/Course/DeleteCourse.cshtml", source));
        }
Example #14
0
        public SectionArchiveResponseDTO GetLatestVersionBySectionoUUID(string sectionUUID)
        {
            SectionArchiveResponseDTO response = this._autoMapper.Map <SectionArchiveResponseDTO>(this.FindLatestVersionBySectionUUID(sectionUUID));

            if (response == null)
            {
                return(response);
            }

            UserDTO moderator = this._httpClientService.SendRequest <UserDTO>(HttpMethod.Get, "http://localhost:40001/api/users/" + response.moderator.uuid, new UserPrincipal(_httpContextAccessor.HttpContext).token).Result;

            if (moderator == null)
            {
                throw new EntityAlreadyExistsException($"Moderator with uuid {response.moderator.uuid} doesn't exist!", GeneralConsts.MICROSERVICE_NAME);
            }
            response.moderator = moderator;

            CourseDTO course = this._httpClientService.SendRequest <CourseDTO>(HttpMethod.Get, "http://localhost:40005/api/courses/" + response.course.uuid, new UserPrincipal(_httpContextAccessor.HttpContext).token).Result;

            if (course == null)
            {
                throw new EntityAlreadyExistsException($"Course with uuid {response.course.uuid} doesn't exist!", GeneralConsts.MICROSERVICE_NAME);
            }
            response.course = course;

            return(response);
        }
Example #15
0
        public void EditCourse(CourseDTO course)
        {
            string         login   = HttpContext.Session.GetString("User_Login");
            CoursesService service = new CoursesService(services);

            service.EditCourse(course, login);
        }
Example #16
0
        /// <summary>
        /// Updates the given course.
        /// </summary>
        /// <exception cref="AppObjectNotFoundException">Thrown if we can't find the course.</exception>
        /// <param name="ID">The ID of the course to update.</param>
        /// <param name="courseVM">The course update viewmodel.</param>
        /// <returns>Returns a course DTO for the updated course.</returns>
        public CourseDTO UpdateCourse(int ID, CourseUpdateViewModel courseVM)
        {
            Course courseToUpdate = _context.Courses.Where(c => c.ID == ID).SingleOrDefault();

            if (courseToUpdate == null)
            {
                throw new AppObjectNotFoundException();
            }

            courseToUpdate.StartDate   = courseVM.StartDate;
            courseToUpdate.EndDate     = courseVM.EndDate;
            courseToUpdate.MaxStudents = courseVM.MaxStudents;
            _context.SaveChanges();

            //Create the return object
            string courseName = _context.CourseTemplates.Where(c => c.TemplateID == courseToUpdate.TemplateID).Select(c => c.Name).SingleOrDefault();

            CourseDTO courseDTO = new CourseDTO
            {
                ID           = courseToUpdate.ID,
                Name         = courseName,
                MaxStudents  = courseToUpdate.MaxStudents,
                Semester     = courseToUpdate.Semester,
                StartDate    = courseToUpdate.StartDate,
                StudentCount = _context.StudentEnrollment.Count(se => se.CourseID == courseToUpdate.ID)
            };

            return(courseDTO);
        }
Example #17
0
        public static CourseDTO GetById(int id)
        {
            Database database = new Database();

            if (!database.OpenConnection())
            {
                // FIXME: throw exception;
                return(null);
            }

            database.command.CommandText = "SELECT * FROM courses WHERE id = @id AND deleted_at IS NULL";

            database.command.Parameters.AddWithValue("id", id);

            MySqlDataReader result = database.command.ExecuteReader();

            CourseDTO item = new CourseDTO();

            while (result.Read())
            {
                item.Id        = result.GetInt16(0);        // ID
                item.Name      = result.GetString(1);       // Name
                item.CreatedAt = result.GetDateTime(2);     // CreatedAt
                try {
                    item.DeletedAt = result.GetDateTime(3); // DeletedAt
                } catch (Exception) {}
                try {
                    item.DeletedBy = result.GetInt32(4); // DeletedBy
                } catch (Exception) {}
            }

            database.CloseConnection();

            return(item);
        }
Example #18
0
        public ActionResult Delete(int id)
        {
            CourseDTO tmpCourse = courseService.Get(id);

            if (tmpCourse != null)
            {
                try
                {
                    courseService.Delete(tmpCourse.CoursID);
                    return(Json("OK"));
                }
                catch (Exception ex)
                {
                    Exception firstEx = ex;
                    while (firstEx.InnerException != null)
                    {
                        firstEx = firstEx.InnerException;
                    }
                    if (firstEx is System.Data.SqlClient.SqlException sqlEx && sqlEx.Number == 547)
                    {
                        Response.StatusCode = (int)System.Net.HttpStatusCode.Conflict;
                        return(Json(new
                        {
                            status = System.Net.HttpStatusCode.Conflict,
                            exeption = "Ошибка удаления",
                            message = "Невозможно удалить запись, так как на нее ссылаются другие источники"
                        }));
                    }
                    return(new HttpStatusCodeResult(System.Net.HttpStatusCode.Conflict, ex.Message));
                }
            }

            return(Json("BAD"));
        }
        public async Task <IHttpActionResult> Post(CourseDTO courseDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));//status code 400
            }
            //var course = new CourseDTO
            //{
            //    CourseID = courseDTO.CourseID,
            //    Title = courseDTO.Title,
            //    Credits = courseDTO.Credits
            //};

            try
            {
                var course = mapper.Map <Course>(courseDTO);
                course = await courseService.Insert(course);

                return(Ok(courseDTO));//status code 200
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));//status code 500
            }
        }
        public IHttpActionResult GetCardsForSubscribedCourse(string courseLink, int numberOfCards, string userLogin)
        {
            try
            {
                CourseDTO currentCourse = moderation.FindCourseByLinking(courseLink);

                IEnumerable <Statistics> courseStatistics = statistics.GetCourseStatistics(userLogin, currentCourse.Id);

                if (numberOfCards > courseStatistics.Count())
                {
                    numberOfCards = courseStatistics.Count();
                }

                List <CardDTO> cards = quiz.GetCardsForSubscription(numberOfCards, courseStatistics);

                return(Ok(cards));
            }
            catch (ArgumentNullException ex)
            {
                var message = $"Course with link = {courseLink} not found. {ex.Message}";
                return(BadRequest(message));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #21
0
        public ActionResult GetFreeCourse()
        {
            using (ELearningDB db = new ELearningDB())
            {
                var freeCourse        = db.Courses.Where(x => x.Price == 0).OrderByDescending(x => x.Comments.Select(c => c.Rate).Sum() / x.Comments.Select(c => c.Rate).Count()).ThenByDescending(x => x.CourseDetails.Count()).Take(3).ToList();
                List <CourseDTO> data = new List <CourseDTO>();
                foreach (var item in freeCourse)
                {
                    var lstCmtID = db.Comments.Where(x => x.CourseID == item.ID).Select(a => a.ID);
                    var lstRep   = db.Replies.Where(x => lstCmtID.Contains(x.CommentID)).ToList();

                    CourseDTO l = new CourseDTO();
                    l.ID          = item.ID;
                    l.Name        = item.Name;
                    l.Capacity    = item.Capacity;
                    l.NumOfPeo    = db.CourseDetails.Where(x => x.CourseID == item.ID).Count();
                    l.Description = item.Description;
                    l.Image       = item.Image;
                    l.Status      = item.Status;
                    l.Price       = item.Price;
                    l.Schedule    = item.Schedule;
                    l.Condition   = item.Condition;
                    l.Type        = item.Type;
                    l.UserID      = item.UserID;
                    l.Comments    = item.Comments.Count() + lstRep.Count();
                    l.Username    = item.NguoiDung.HoVaTen;
                    data.Add(l);
                }
                return(Json(data, JsonRequestBehavior.AllowGet));
            }
        }
Example #22
0
        //GET: Admin/Shop/DeleteCourse/id
        public ActionResult DeleteCourse(int id)
        {
            CourseVM model;

            using (Db db = new Db()) {
                CourseDTO dto = db.Courses.Find(id);
                model = new CourseVM(dto);

                db.Courses.Remove(dto);
                db.SaveChanges();
            }

            DirectoryInfo originalDirectory =
                new DirectoryInfo(string.Format("{0}Courses\\",
                                                Server.MapPath(@"\")));

            string pathString1 = Path
                                 .Combine(originalDirectory.ToString()
                                          + model.Name);

            string path = string
                          .Format("{0}\\{1}", pathString1, model.VideoName);

            string pathString3 = Path
                                 .Combine(originalDirectory.ToString() +
                                          model.Name + "\\Chapters");

            if (Directory.Exists(pathString1))
            {
                Directory.Delete(pathString1, true);
            }

            return(RedirectToAction("Courses"));
        }
Example #23
0
        public void AddCourse(CourseDTO course)
        {
            List <CourseDTO> _courseList = loadXml(_path);

            _courseList.Add(course);
            saveXml(_path, _courseList);
        }
        public IActionResult UpdateCourse([FromRoute] int courseId, [FromBody] CourseDTO dto)
        {
            int successTransactionValue = (int)TransactionStatus.SUCCESS;

            return(this.NoContent(() =>
                                  _CourseRepo.Update(courseId, dto).Equals(successTransactionValue), _Logger));
        }
Example #25
0
        public async Task <bool> Insert(CourseDTO newCourse)
        {
            if (newCourse != null)
            {
                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap <CourseDTO, Course>();
                });
                IMapper iMapper = config.CreateMapper();

                var model = iMapper.Map <CourseDTO, Course>(newCourse);
                model.CreationTime = DateTime.Now;

                if (await courseRepository.CreateAsync(model))
                {
                    string createdCourseID = (await courseRepository
                                              .GetAllAsync()
                                              .FirstOrDefaultAsync(x => x.Name == newCourse.Name))?
                                             .ID;
                    await EnrollStudentInCourse(newCourse.TeacherID, createdCourseID);

                    return(true);
                }

                return(false);
            }
            else
            {
                return(false);
            }
        }
        public ActionResult FullCourse(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new Exception("id doesn't exist");
            }
            CourseDTO       courseDto = courseService.GetCourse(Convert.ToInt32(id));
            CourseViewModel course    = new CourseViewModel
            {
                CourseId         = courseDto.CourseId,
                ForTerm          = courseDto.ForTerm,
                CourseName       = courseDto.CourseName,
                Description      = courseDto.Description,
                IsDeleted        = courseDto.IsDeleted,
                CourseEnd        = courseDto.CourseEnd.ToString().Split(' ')[0],
                CourseStart      = courseDto.CourseStart.ToString().Split(' ')[0],
                Image            = courseDto.Image,
                ImageName        = courseDto.ImageName,
                NumberOfStudents = courseDto.NumberOfStudents,
                Topics           = courseDto.Topics,
                Lecturer         = courseDto.Lecturer,
                Students         = courseDto.Students
            };

            return(View(course));
        }
Example #27
0
        public async Task <IActionResult> CreateCourse([FromBody] CourseDTO course)
        {
            var institude = unitOfWork.GetRepository <Institute>().Get(s => s.UserId == UserIdRequested()).FirstOrDefault();

            var dataInsert = mapper.Map <CourseDTO, Course>(course);

            dataInsert.InstituteId = institude.Id;
            var courseInserted = await unitOfWork.GetRepository <Course>().InsertAsync(dataInsert);

            //foreach (var item in course.Trainers)
            //{
            //    var courseTrainerItem = new CourTra()
            //    {
            //        CourseId = courseInserted.Id,
            //        TrainerId = item,
            //    };
            //    await unitOfWork.GetRepository<CourTra>().InsertAsync(courseTrainerItem);
            //}

            //foreach (var item in course.Reliances)
            //{
            //    var courseRelianceItem = new CourRel()
            //    {
            //        CourseId = courseInserted.Id,
            //        RelianceId = item,
            //    };
            //    await unitOfWork.GetRepository<CourRel>().InsertAsync(courseRelianceItem);
            //}

            return(ApiResponder.RespondSuccessTo(HttpStatusCode.Ok, courseInserted));
        }
Example #28
0
        public static bool Update(CourseDTO courseDto)
        {
            // TODO: Doe de shit
            Database database = new Database();

            if (!database.OpenConnection())
            {
                // FIXME: throw exception;
                return(false);
            }

            // Insert items into database
            database.command.CommandText = "UPDATE courses SET name=@name WHERE ID = @id";

            // bind some shit
            database.command.Parameters.AddWithValue("name", courseDto.Name);
            database.command.Parameters.AddWithValue("id", courseDto.Id);

            int result = database.command.ExecuteNonQuery();

            database.CloseConnection();

            if (result > 0)
            {
                return(true);
            }
            return(false);
        }
        public async Task <ActionResult <CourseDTO> > Post(CourseDTO model)
        {
            try
            {
                if (model == null)
                {
                    return(BadRequest("No entity provided"));
                }
                var exists = await _db.AnyAsync <Instructor>(a => a.Id.Equals(model.InstructorId));

                if (!exists)
                {
                    return(NotFound("Could not find related entity"));
                }
                var id = await _db.CreateAsync <CourseDTO, Course>(model);

                if (id < 1)
                {
                    return(BadRequest("Unable to add the entity"));
                }
                var dto = await _db.SingleAsync <Course, CourseDTO>(s =>
                                                                    s.Id.Equals(id));

                if (dto == null)
                {
                    return(BadRequest("Unable to add the entity"));
                }
                var uri = _linkGenerator.GetPathByAction("Get", "Courses", new { id });
                return(Created(uri, dto));
            }
            catch
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Failed to add entity"));
            }
        }
Example #30
0
        public void DeleteScheduledTest(TestDTO test, CourseDTO course)
        {
            ScheduledEvent scheduledLection = db.ScheduledEvents.Find(x => x.Test.TestID == test.TestID && x.Course.CourseID == course.CourseID).FirstOrDefault();

            db.ScheduledEvents.Delete(scheduledLection.ScheduledEventID);
            db.Save();
        }
Example #31
0
        /// <summary>
        /// Updates the given course. 
        /// </summary>
        /// <exception cref="AppObjectNotFoundException">Thrown if we can't find the course.</exception>
        /// <param name="ID">The ID of the course to update.</param>
        /// <param name="courseVM">The course update viewmodel.</param>
        /// <returns>Returns a course DTO for the updated course.</returns>
        public CourseDTO UpdateCourse(int ID, CourseUpdateViewModel courseVM)
        {
            Course courseToUpdate = _context.Courses.Where(c => c.ID == ID).SingleOrDefault();

            if (courseToUpdate == null)
                throw new AppObjectNotFoundException();

            courseToUpdate.StartDate = courseVM.StartDate;
            courseToUpdate.EndDate = courseVM.EndDate;
            courseToUpdate.MaxStudents = courseVM.MaxStudents;
            _context.SaveChanges();

            //Create the return object
            string courseName = _context.CourseTemplates.Where(c => c.TemplateID == courseToUpdate.TemplateID).Select(c => c.Name).SingleOrDefault();

            CourseDTO courseDTO = new CourseDTO
            {
                ID = courseToUpdate.ID,
                Name = courseName,
                MaxStudents = courseToUpdate.MaxStudents,
                Semester = courseToUpdate.Semester,
                StartDate = courseToUpdate.StartDate,
                StudentCount = _context.StudentEnrollment.Count(se => se.CourseID == courseToUpdate.ID)
            };

            return courseDTO;
        }
        /// <summary>
        /// adds a new instance of a course to the database
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public CourseDTO AddNewCourse(CourseViewModel model)
        {
            //check if course already in database
          
            //add the course
            var newCourse = new Course
            {

                TemplateID = model.TemplateID,
                Semester = model.Semester,
                StartDate = model.StartDate,
                EndDate = model.EndDate,
                MaxStudents = model.MaxStudents
            };

            _db.Courses.Add(newCourse);
            _db.SaveChanges();

            //find the Name of the course
            var courseTemplate = (from ct in _db.CourseTemplates
                              where ct.TemplateID == model.TemplateID
                              select ct).SingleOrDefault();

            var result = new CourseDTO
            {
                ID = newCourse.ID,
                Name = courseTemplate.Name,
                StartDate = newCourse.StartDate,
                StudentCount = 0
            };

            return result;
        }
        /// <summary>
        /// Updates a specific course by a given id.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public CourseDTO UpdateCourse(int id, CourseUpdateViewModel model)
        {
            // Validate
            var courseEntity = _db.Courses.SingleOrDefault(x => x.ID == id);
            if(courseEntity == null)
            {
                throw new AppObjectNotFoundException();
            }
            //make changes to the entity object and save changes to database
            courseEntity.StartDate = model.StartDate;
            courseEntity.EndDate = model.EndDate;

            if(model.MaxStudents != 0)
            {
                courseEntity.MaxStudents = model.MaxStudents;
            }

            _db.SaveChanges();
            // Return
            var courseTemplate = _db.CourseTemplates.SingleOrDefault(x => x.TemplateID == courseEntity.TemplateID);
            if (courseTemplate == null)
            {
                //return 500 internal server error
                throw new ApplicationException("");
            }
            var count = _db.CourseStudents.Count(x => x.CourseID == courseEntity.ID);
            var result = new CourseDTO
            {
                ID = courseEntity.ID,
                Name = courseTemplate.Name,
                StartDate = courseEntity.StartDate,
                StudentCount = count
            };
            return result;
        }