public async Task <IActionResult> CreateCourse(CreateCourseDto dto) { var validPeriod = ValidPeriod.Create(dto.BeginYear, dto.EndYear); if (validPeriod.IsFailure) { return(BadRequest(validPeriod.Error)); } var lowGrade = _context.Grades.Find(dto.LowGradeId); var highGrade = _context.Grades.Find(dto.HighGradeId); if (lowGrade == null || highGrade == null) { return(BadRequest("Invalid Grade range supplied")); } try { var course = new Course(dto.Title, dto.Description, validPeriod.Value, lowGrade, highGrade); _context.Courses.Attach(course); await _context.SaveChangesAsync(); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok()); }
public async Task AddCourseAsync_ShouldReturnExpectedCourseWithId() { // given (arrange) Filler <CreateCourseDto> courseFiller = new Filler <CreateCourseDto>(); CreateCourseDto courseDtoToAdd = courseFiller.Create(); Course courseToAdd = this.mapper.Map <Course>(courseDtoToAdd); Course databaseCourse = this.mapper.Map <Course>(courseToAdd); databaseCourse.Id = 1; databaseCourse.DateCreated = databaseCourse.DateUpdated = DateTime.UtcNow; this.appDbContextMock .Setup(db => db.CreateCourseAsync(It.IsAny <Course>())) .ReturnsAsync(databaseCourse); // when (act) var actualCourse = await subject.AddCourseAsync(courseDtoToAdd); // then (assert) actualCourse.Should().BeEquivalentTo(databaseCourse); appDbContextMock.Verify(db => db.CreateCourseAsync(It.IsAny <Course>()), Times.Once); appDbContextMock.VerifyNoOtherCalls(); }
public ActionResult <CourseDto> CreateCoursesForAuthor(Guid authorId, [FromBody] CreateCourseDto createCourseDto) { if (!_courseLibraryRepository.AuthorExists(authorId)) { return(NotFound("Author does not exist please check and try again")); } var createCourse = _mapper.Map <Course>(createCourseDto); _courseLibraryRepository.AddCourse(authorId, createCourse); var solution = _courseLibraryRepository.Save(); var courseReturn = _mapper.Map <CourseDto>(createCourse); if (solution) { return(CreatedAtRoute( "GetCourseForAuthor", new{ authorId = courseReturn.AuthorId, courseId = courseReturn.Id }, courseReturn)); } return(BadRequest("An error occurred unable to save changes")); }
public async Task <Result <CourseDto> > CreateCourseAsync(CreateCourseDto courseDto) { try { if (courseDto == null) { return(Result <CourseDto> .GetError(ErrorCode.ValidationError, "CourseDto is null")); } if (await IsCourseNameTakenAsync(courseDto.Name)) { return(Result <CourseDto> .GetError(ErrorCode.UnprocessableEntity, "Course already exists")); } var createdCourseEntity = _mapper.Map <Course>(courseDto); _unitOfWork.CourseRepository.Add(createdCourseEntity); await _unitOfWork.CommitAsync(); return(Result <CourseDto> .GetSuccess(_mapper.Map <CourseDto>(createdCourseEntity))); } catch { _unitOfWork.Rollback(); return(Result <CourseDto> .GetError(ErrorCode.InternalServerError, "Internal error")); } }
public ActionResult <CourseDto> CreateCourseForAuthor( [FromRoute] Guid authorId, [FromBody] CreateCourseDto courseDto ) { if (!AuthorRepository.Exists(authorId)) { return(NotFound()); } if (courseDto == null) { return(BadRequest()); } var course = CourseMapper.ToCourse(courseDto, authorId); CourseRepository.Create(course); _unitOfWork.Commit(); return(CreatedAtRoute( "GetCourseForAuthor", new { authorId, id = course.Id }, CourseMapper.ToCourseDto(course) )); }
public CourseDto CreateCourse(CreateCourseDto createCourseDto, string currentUserId) { CreateCourseValidator authorValidator = new CreateCourseValidator(); if (!authorValidator.Validate(createCourseDto).IsValid) throw new Exception("Check_Your_Fileds"); Course course = _mapper.Map<CreateCourseDto, Course>(createCourseDto); course.CreatedOn = DateTime.Now; course.CreatedBy = currentUserId; _unitOfWork.CourseRepository.Add(course); _unitOfWork.Save(); return _mapper.Map<Course, CourseDto>(course); }
public async Task <IActionResult> CreateCourse([FromForm] CreateCourseDto input) { try { var course = await _courseAppService.CreateCourse(input); return(Ok(course)); } catch (Exception e) { Console.WriteLine(e); throw; } }
public IActionResult Post([FromBody] CreateCourseDto model) { if (!ModelState.IsValid) { return(BadRequest("Invalid input")); } var result = repository.CreateCourse(model); if (result) { return(Ok("Course created successfully")); } return(StatusCode(StatusCodes.Status500InternalServerError)); }
public async Task CreateCourseAsync(CreateCourseDto course) { Course courseToDb = new() { Name = course.Name, GroupId = course.GroupId }; courseToDb = await _courseRepository.AddAsync(courseToDb); await _courseRepository.UnitOfWork.SaveChangesAsync(); var teachers = await CreateTeacherCourses(courseToDb.Id, course.TeacherIds); courseToDb.Teachers = teachers; _courseRepository.Update(courseToDb); await _courseRepository.UnitOfWork.SaveChangesAsync(); }
public async Task CreateCourse() { //Arrange var newCourse = new CreateCourseDto() { Name = "New_test_name" }; var existingCourse = new CreateCourseDto() { Name = "Exists_test_name" }; var courseRepositoryMock = new Mock <ICourseRepository>(); courseRepositoryMock.Setup(x => x.Add(It.IsAny <Course>())); courseRepositoryMock.Setup(x => x.IsCourseNameTakenAsync(newCourse.Name)) .ReturnsAsync(false); courseRepositoryMock.Setup(x => x.IsCourseNameTakenAsync(existingCourse.Name)) .ReturnsAsync(true); _unitOfWorkMock.Setup(x => x.CourseRepository).Returns(courseRepositoryMock.Object); var courseService = new CourseService( _unitOfWorkMock.Object, _mapper ); //Act var successResult = await courseService.CreateCourseAsync(newCourse); var courseNameExistResult = await courseService.CreateCourseAsync(existingCourse); var nullCourseResult = await courseService.CreateCourseAsync(null); //Assert Assert.NotNull(successResult.Data); Assert.Equal(newCourse.Name, successResult.Data.Name); Assert.Equal(ErrorCode.UnprocessableEntity, courseNameExistResult.Error.Code); Assert.Equal(ErrorCode.ValidationError, nullCourseResult.Error.Code); }
public ActionResult <CourseDto> CreateCourse(Guid authorId, CreateCourseDto createCourseDto) { if (!_courseRepository.AuthorExists(authorId)) { return(NotFound()); } var course = _mapper.Map <Course>(createCourseDto); _courseRepository.AddCourse(authorId, course); _courseRepository.Save(); var courseDto = _mapper.Map <CourseDto>(course); return(CreatedAtRoute("GetCoursesForAuthor", new { authorId = course.AuthorId, courseId = course.Id }, courseDto)); }
public ActionResult <IEnumerable <CreateCourseDto> > Post([FromBody] CreateCourseDto dto) { try { _addCommandCourse.Execute(dto); return(StatusCode(StatusCodes.Status201Created)); } catch (EntityNotFoundException e) { return(UnprocessableEntity(e.Message)); } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public async Task CreateCourse(CreateCourseDto course) { try { Log.Logger.Information("Initializing course creation for {0} at {1}", course.Name, DateTime.Now); var newEntity = _mapper.ProjectTo <Course>((IQueryable)course); await AddRangeAndSaveAsync(newEntity); Log.Logger.Information("Finalizing course creation for {0} at {1}", course.Name, DateTime.Now); } catch (Exception ex) { Log.Logger.Error("Exception launched when creating course {0} at {1}: {2}", course.Name, DateTime.Now, ex.Message); throw; } }
public ActionResult <CoursDto> CreateCourseForAthor(Guid authorId, CreateCourseDto course) { if (!_courseLibraryRepository.AuthorExists(authorId)) { return(NotFound()); } var courseEntity = _mapper.Map <Course>(course); _courseLibraryRepository.AddCourse(authorId, courseEntity); _courseLibraryRepository.Save(); var courseToReturn = _mapper.Map <CoursDto>(courseEntity); return(CreatedAtRoute("GetCourseForAuhtor", new { authorId = authorId, courseId = courseToReturn.Id }, courseToReturn)); }
public async Task AddCourseAsync_ShouldThrowExceptionForInvalidDataAnnotationRequirement() { // given (arrange) Filler <CreateCourseDto> courseFiller = new Filler <CreateCourseDto>(); CreateCourseDto invalidCourseToAddDto = courseFiller.Create(); invalidCourseToAddDto.Name = null; // when (act) var actualCourseTask = subject.AddCourseAsync(invalidCourseToAddDto); // then (assert) await Assert.ThrowsAsync <ValidationException>(() => actualCourseTask); appDbContextMock.VerifyNoOtherCalls(); }
public async Task <CourseDto> CreateCourseAsync(CreateCourseDto courseModel) { try { var createdCourseEntity = _mapper.Map <Course>(courseModel); _unitOfWork.CourseRepository.Add(createdCourseEntity); await _unitOfWork.CommitAsync(); return(_mapper.Map <CourseDto>(createdCourseEntity)); } catch { _unitOfWork.Rollback(); return(null); } }
public void CreateCourse(CreateCourseDto dto, out int id) { var createdCourse = new Course { SerialNumber = _serialNumberGenerator.Generate(), Title = dto.Title, Description = dto.Description, CreationDate = DateTime.UtcNow, SpendingTime = new Time { DayOfWeek = dto.DayOfWeek, StartHour = dto.StartHour, EndHour = dto.EndHour } }; _courseRepository.Insert(createdCourse); id = createdCourse.Id; }
public ActionResult <IEnumerable <CreateCourseDto> > Put(int id, [FromBody] CreateCourseDto dto) { dto.Id = id; try { _editCommandCourse.Execute(dto); return(NoContent()); } catch (EntityNotFoundException e) { if (e.Message == "Course doesn't exist.") { return(NotFound(e.Message)); } return(UnprocessableEntity(e.Message)); } catch (Exception) { return(StatusCode(500, "error")); } }
public async Task <Course> AddCourseAsync(CreateCourseDto courseDto) { var course = new Course { Name = courseDto.Name, Description = courseDto.Description, CourseType = courseDto.CourseType, CourseImageURL = courseDto.CourseImageURL }; try { this.ValidateCourseOnCreate(course); } catch (Exception ex) { logger.LogError(ex, "Attempted to add invalid course."); throw; } return(await this.db.CreateCourseAsync(course)); }
public async Task <ActionResult <CreateCourseDto> > PostCourse(CreateCourseDto courseDto) { if (!ModelState.IsValid) { return(BadRequest()); } var isCourseNameTaken = await _coursesService.IsCourseNameTakenAsync(courseDto.Name); if (isCourseNameTaken) { return(StatusCode(409, "Course already exists!")); } var createdCourse = await _coursesService.CreateCourseAsync(courseDto); if (createdCourse == null) { return(StatusCode(500)); } return(Ok(createdCourse)); }
public void Execute(CreateCourseDto request) { var editCourse = _context.Courses.Find(request); if (editCourse == null) { throw new EntityNotFoundException("Course"); } if (!_context.Teachers.Any(t => t.Id == request.TeacherId)) { throw new EntityNotFoundException("Teacher"); } //editCourse.Id = request.Id; editCourse.CourseName = request.CourseName; editCourse.Description = request.Description; editCourse.Location = request.Location; editCourse.CreatedAt = DateTime.Now; editCourse.TeacherId = request.TeacherId; _context.SaveChanges(); }
public void Execute(CreateCourseDto request) { if (_context.Courses.Any(c => c.CourseName == request.CourseName && c.Location == request.Location)) { throw new EntityNotFoundException(); } if (!_context.Teachers.Any(t => t.Id == request.TeacherId)) { throw new EntityNotFoundException("Teachers"); // Message -> Teacher doesn't exist } _context.Courses.Add(new Course { CourseName = request.CourseName, Description = request.Description, Location = request.Location, CreatedAt = DateTime.Now, TeacherId = request.TeacherId }); _context.SaveChanges(); }
public async Task <IActionResult> AddCourse([FromBody] CreateCourseDto createCourseDto) { if (createCourseDto == null) { return(BadRequest()); } if (await _courseService.CourseIsExist(createCourseDto.CourseName, createCourseDto.CourseNum)) { return(BadRequest("课程名称或者编号已存在")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var res = _mapper.Map <Course>(createCourseDto); _courseService.AddT(res); if (!await _courseService.Save()) { return(StatusCode(500, "添加课程信息失败")); } return(Created("", createCourseDto)); }
public async Task Create(CreateCourseDto input) { var @course = Course.Create(1, input.Name, input.Venue, input.Day, input.Time, input.TeacherId); await _courseRepository.InsertAsync(@course); }
public async Task <Course> CreateCourse(CreateCourseDto input) { if (input.EducatorId == null) { long[] a = new long[0]; input.EducatorId = a; } if (input.TenantId == null) { long[] b = new long[0]; input.TenantId = b; } if (input.EducatorId.Length > 0) { var isHaveRightEducator = await _checkEdition.HaveCreateCourseRight <Educator>(input.EducatorId); if (!isHaveRightEducator) { throw new Exception("No right to create course for educator !"); } } if (input.TenantId.Length > 0) { var isHaveRight = await _checkEdition.HaveCreateCourseRight <Tenant>(input.TenantId); if (!isHaveRight) { throw new Exception("No right to create course tenant !"); } } var imagePath = await _blobService.InsertFile(input.File); var course = new Course { Title = input.Title, Description = input.Description, Quota = input.Quota, Address = input.Address, OnlineVideo = input.OnlineVideo, Certificate = input.Certificate, CertificateOfParticipation = input.CertificateOfParticipation, DurationCount = input.DurationCount, DurationType = input.DurationType, Requirements = input.Requirements, Teachings = input.Teachings, Price = input.Price, IsActive = true, DiscountPrice = input.DiscountPrice, StartDate = input.StartDate, EndDate = input.EndDate, CategoryId = input.CategoryId, LocationId = input.LocationId, OwnerType = input.OwnerType, OwnerId = input.OwnerId, ShortDescription = input.ShortDescription, ImagePath = imagePath }; await _courseRepository.AddAsync(course); var count = (input.TenantId.Length > input.EducatorId.Length) ? input.TenantId.Length : input.EducatorId.Length; for (var i = 0; i < count; i++) { var givenCourse = new GivenCourse { CourseId = course.Id, }; if (input.TenantId.Length > i) { givenCourse.TenantId = input.TenantId[i]; } if (input.EducatorId.Length > i) { givenCourse.EducatorId = input.EducatorId[i]; } await _givenCourseRepository.AddAsync(givenCourse); } return(course); }
public ActionResult Post([FromBody] CreateCourseDto createCourseDto) { return(Ok(_courseService.CreateCourse(createCourseDto, CurrentUserId()))); }
public async Task <ActionResult> CreateCourse(CreateCourseDto createCourseDto) { return(Ok(await _courseService.CreateCourse(createCourseDto))); }
public void Create(CreateCourseDto course) { throw new NotImplementedException(); }
public async Task <bool> CreateCourse(CreateCourseDto course) { await _coursesRepository.CreateCourse(course); return(true); }
public async Task <ServiceResponse <GetCourseDto> > CreateCourse(CreateCourseDto createCourseDto) { ServiceResponse <GetCourseDto> serviceResponse = new ServiceResponse <GetCourseDto>(); User dbUser = await _context.Users .Include(c => c.InstructedCourses) .FirstOrDefaultAsync(c => c.Id == GetUserId()); if (dbUser == null || dbUser.UserType == UserTypeClass.Student) { serviceResponse.Success = false; serviceResponse.Message = "User is not in instructor list. If you think this is incorrect, please contact the devs."; return(serviceResponse); } if (createCourseDto.MaxGroupSize < 1 || createCourseDto.MinGroupSize > createCourseDto.MaxGroupSize) { serviceResponse.Success = false; serviceResponse.Message = "Minumum maxgroupsize should be 1 and minGroupsize should be less than or equal to maxgroupsize"; return(serviceResponse); } SemesterType semesterType = SemesterType.Spring; if (createCourseDto.CourseSemester.Equals("Spring")) { semesterType = SemesterType.Spring; } else if (createCourseDto.CourseSemester.Equals("Summer")) { semesterType = SemesterType.Summer; } else if (createCourseDto.CourseSemester.Equals("Fall")) { semesterType = SemesterType.Fall; } else { serviceResponse.Success = false; serviceResponse.Message = "Semester type is given wrong."; return(serviceResponse); } Course newCourse = new Course { Name = createCourseDto.Name, CourseSemester = semesterType, Year = createCourseDto.Year, CourseInformation = createCourseDto.CourseInformation, NumberOfSections = createCourseDto.NumberOfSections, LockDate = createCourseDto.LockDate, MinGroupSize = createCourseDto.MinGroupSize, MaxGroupSize = createCourseDto.MaxGroupSize, StartDate = DateTime.Now, IsSectionless = createCourseDto.IsSectionless, IsActive = createCourseDto.IsActive, IsLocked = createCourseDto.IsLocked, CourseDescription = createCourseDto.CourseDescription }; CourseUser founderInstructor = new CourseUser { User = dbUser, UserId = dbUser.Id, Course = newCourse, CourseId = newCourse.Id }; newCourse.Instructors.Add(founderInstructor); for (int i = 1; i <= createCourseDto.NumberOfSections; i++) { Section newSection = new Section { SectionNo = i, AffiliatedCourse = newCourse, AffiliatedCourseId = newCourse.Id }; newCourse.Sections.Add(newSection); } await _context.Courses.AddAsync(newCourse); await _context.SaveChangesAsync(); serviceResponse.Data = await AddExtraDtos(_mapper.Map <GetCourseDto>(newCourse)); return(serviceResponse); }