Beispiel #1
0
        public async Task <LessonDto> UpdateLesson(Guid lessonId, LessonDto lessonDto, CancellationToken cancellationToken = default)
        {
            if (lessonId == Guid.Empty)
            {
                throw new ArgumentNullException("", Resource.IdIsEmpty);
            }
            if (lessonDto is null)
            {
                throw new ArgumentNullException("", Resource.ModelIsEmpty);
            }
            var lesson = await _timetableRepository.GetByIdAsync(lessonId);

            if (lesson.Id != lessonDto.Id)
            {
                throw new ArgumentException();
            }
            var newLesson = _mapper.Map <Lesson>(lessonDto);
            await _timetableRepository.UpdateAsync(lessonId, newLesson, cancellationToken);

            return(newLesson is null ? throw new ArgumentNullException("", Resource.UpdateError) : _mapper.Map <LessonDto>(newLesson));
        }
Beispiel #2
0
        public async Task <IActionResult> Post([FromBody] LessonDto lessonDto)
        {
            if (ModelState.IsValid)
            {
                LogicResponse response = new LogicResponse();
                response = _lessonLogic.Create(lessonDto);

                if (response.Success)
                {
                    lessonDto.Id = Convert.ToInt32(response.Message);
                    return(Created($"/Courses/{lessonDto.CourseId}/Modules/{lessonDto.ModuleId}/Lessons/{lessonDto.Id}", lessonDto));
                }
                else
                {
                    return(BadRequest(response.Message));
                }
            }
            else
            {
                return(BadRequest(ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage));
            }
        }
        public IHttpActionResult Get(int?id)
        {
            if (id == null)
            {
                return(BadRequest());
            }
            Lesson lessonEntity = _repo.GetLessonById((int)id);

            if (lessonEntity == null)
            {
                return(NotFound());
            }
            var lesson = new LessonDto()
            {
                Id                = lessonEntity.Id,
                Date              = lessonEntity.Date,
                CourseId          = lessonEntity.CourseId,
                studentActivities = new List <StudentActivityDto>()
            };

            return(Ok(lesson));
        }
Beispiel #4
0
        public LogicResponse Create(LessonDto lessonDto)
        {
            LogicResponse response = new LogicResponse();
            Course        course   = _courseRepository.GetById(lessonDto.CourseId);
            Module        module   = _moduleRepository.Get(lessonDto.CourseId, lessonDto.ModuleId);

            if (course == null)
            {
                response.Success = false;
                response.Message = "No se encontró el curso";
                return(response);
            }
            if (module == null)
            {
                response.Success = false;
                response.Message = "No se encontró el módulo";
                return(response);
            }

            Lesson lesson = _mapper.Map <LessonDto, Lesson>(lessonDto);

            lesson.Module = module;

            try
            {
                int id = _lessonRepository.Create(lesson);
                response.Success = true;
                response.Message = id.ToString();
                return(response);
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = "Error al almacenar la clase";
                return(response);
            }
        }
Beispiel #5
0
        public async Task <ActionResult <LessonDto> > CreateLesson(
            [FromRoute] Guid classroomId,
            [FromBody] LessonDto lessonDto
            )
        {
            var user = (ApplicationUser)HttpContext.Items["ApplicationUser"];

            Debug.Assert(user != null, nameof(user) + " != null");

            try
            {
                var classroom = await _classroomService.FindAsync(classroomId);

                var authorization = await _authorizationService.AuthorizeAsync(User, classroom, "IsOwner");

                if (!authorization.Succeeded)
                {
                    return(Forbid());
                }

                var lesson = lessonDto.ToLesson();
                lesson = await _lessonService.CreateAsync(lesson);

                await _classroomService.AddLessonAsync(classroom, lesson);

                lesson = await _lessonService.LoadTeachersAsync(lesson);

                await _lessonService.AddTeacherAsync(lesson, user);

                return(Ok(lesson.ToDto()));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(BadRequest());
            }
        }
        public IActionResult Edit(Guid id, [Bind("Id,StudentId,TrainerId,DateTime,Hour,Minutes,IsCompleted", Prefix = "Data")] LessonDto lesson)
        {
            ResultHandler <LessonDto> resultHandler = new ResultHandler <LessonDto>();

            if (id != lesson.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    resultHandler = _lessonService.Update(lesson);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LessonExists(lesson.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StudentId"] = new SelectList(_studentService.GetList().Data, "Id", "LastName");
            ViewData["TrainerId"] = new SelectList(_trainerService.GetList().Data, "Id", "LastName");

            ResultViewModel <LessonDto> lessonViewModel =
                AutoMapper.Mapper.Map <ResultHandler <LessonDto>, ResultViewModel <LessonDto> >(resultHandler);

            return(View(lessonViewModel));
        }
Beispiel #7
0
        public LessonDto Get(string id)
        {
            LessonDto lesson = null;

            using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand("GetLesson", sqlConnection))
                {
                    sqlCommand.CommandType = CommandType.StoredProcedure;

                    sqlCommand.Parameters.Add("@id", SqlDbType.Int).Value = id;

                    sqlConnection.Open();

                    using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (sqlDataReader.Read())
                        {
                            string name    = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Name"));
                            string content = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Content"));

                            lesson = new LessonDto()
                            {
                                Id      = id.ToString(),
                                Content = content,
                                Name    = name,
                            };
                        }

                        sqlDataReader.Close();
                    }
                }
            }

            return(lesson);
        }
Beispiel #8
0
        public LessonDto Get(string id)
        {
            LessonDto lesson = lessonServiceClient.Get(id);

            return(lesson);
        }
Beispiel #9
0
 public void Create(LessonDto lesson, string courseId)
 {
     lessonServiceClient.Create(lesson, courseId);
 }
Beispiel #10
0
 public virtual void Edit(LessonDto entity)
 {
     _entities.Entry(entity).State = EntityState.Modified;//??
 }
Beispiel #11
0
 public void InsertNewLesson(LessonDto lesson)
 {
     _lessonAppService.Insert(lesson);
 }
Beispiel #12
0
        public async Task <JsonResult> AddEditGrade(LessonDto model)
        {
            using (var txscope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        txscope.Dispose();
                        //return RedirectToAction("AddEditGrade", model.Id);
                        RedirectToAction("AddEditLesson", model.Id);
                    }

                    if (model.Id == 0)
                    {
                        var lessonObj = Mapper.Map <Lessons>(model);
                        lessonObj.IsActive = true;
                        var result = await _lessonService.InsertAsync(lessonObj, Accessor, User.GetUserId());

                        if (result != null)
                        {
                            //StaffLog
                            if (User.IsInRole(UserRoles.Staff))
                            {
                                await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.CreateNewLesson }, Accessor, User.GetUserId());
                            }
                            txscope.Complete();
                            return(Json(new { success = true, responseText = ResponseConstants.CreateNewLesson }));
                        }
                    }
                    else if (model != null)
                    {
                        var result = await _lessonService.GetSingleAsync(x => x.Id == model.Id);

                        result.Name = model.Name;
                        await _lessonService.UpdateAsync(result, Accessor, User.GetUserId());

                        //StaffLog
                        if (User.IsInRole(UserRoles.Staff))
                        {
                            await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.UpdateLesson }, Accessor, User.GetUserId());
                        }
                        txscope.Complete();
                        return(Json(ResponseConstants.UpdateLesson));
                    }
                    else
                    {
                        txscope.Dispose();
                        return(Json(ResponseConstants.SomethingWrong));
                    }

                    txscope.Dispose();
                    return(Json(ResponseConstants.SomethingWrong));
                }
                catch (Exception ex)
                {
                    txscope.Dispose();
                    ErrorLog.AddErrorLog(ex, "CreateLesson");
                    return(Json(ResponseConstants.SomethingWrong));
                }
            }
        }
Beispiel #13
0
 public Object Put([FromBody] LessonDto lesson)
 {
     return(this.teacherApplicationService.UpdateHeaderAssistance(lesson));
 }
        public async Task <ApiResponse <LessonDto> > OrderLessonAsync(Guid studentId, OrderLessonDto lesson)
        {
            if (studentId == null || studentId == Guid.Empty)
            {
                return(new ApiResponse <LessonDto>()
                       .SetAsFailureResponse(Errors.Lesson.StudentIdForLessonIsEmpty()));
            }

            var tutorPlannedLessons = await _lessonRepository.GetPlannedForTutor(lesson.TutorId);

            foreach (var tutorPlannedLesson in tutorPlannedLessons)
            {
                if (tutorPlannedLesson.Term != lesson.Term)
                {
                    double timeDifferenceBetweenLessons = tutorPlannedLesson.Term.Subtract(lesson.Term).TotalMinutes;
                    if (timeDifferenceBetweenLessons < 30)
                    {
                        return(new ApiResponse <LessonDto>()
                               .SetAsFailureResponse(Errors.Lesson.TooShortTimePeriodBetweenLessons()));
                    }
                }

                else
                {
                    return(new ApiResponse <LessonDto>()
                           .SetAsFailureResponse(Errors.Lesson.TutorAlreadyBookedForLessonProposedTime()));
                }
            }

            var newLesson = new Lesson
            {
                Length        = lesson.Length,
                Location      = lesson.Location,
                Term          = lesson.Term,
                TopicCategory = new LessonTopicCategory
                {
                    Id           = lesson.TopicCategory.Id,
                    CategoryName = lesson.TopicCategory.CategoryName
                },
                TutorId = lesson.TutorId
            };

            var orderedLesson = await _lessonRepository.AddAsync(newLesson);

            var orderedLessonDto = new LessonDto
            {
                Id = orderedLesson.Id,
                AcceptedByTutor    = orderedLesson.AcceptedByTutor,
                CanceledByTutor    = orderedLesson.CanceledByTutor,
                CancelledByStudent = orderedLesson.CancelledByStudent,
                Length             = orderedLesson.Length,
                Location           = orderedLesson.Location,
                StudentId          = orderedLesson.StudentId,
                Term          = orderedLesson.Term,
                TopicCategory = new LessonTopicCategoryDto
                {
                    Id           = orderedLesson.TopicCategory.Id,
                    CategoryName = orderedLesson.TopicCategory.CategoryName
                },
                TutorId = orderedLesson.TutorId
            };

            return(new ApiResponse <LessonDto>
            {
                Result = orderedLessonDto
            });
        }
Beispiel #15
0
        public void CreateNewDto(LessonDto entityDto)
        {
            var item = Mapper.Map <Lesson>(entityDto);

            CreateNew(item);
        }
Beispiel #16
0
        public void UpdateDto(LessonDto entityDto)
        {
            var lesson = Mapper.Map <Lesson>(entityDto);

            Update(lesson);
        }
        public async Task <ActionResult <LessonDto> > PutLesson(int id, LessonInputDto input)
        {
            DateTime?datetime = null;
            var      users    = await _context.Users.Where(x => x.FullName != null).ToListAsync();

            var lesson = await _context.Lessons.FindAsync(id);

            lesson.Date         = DateTimeString.TryParsingDate(input.Date, false);
            lesson.Time         = DateTimeString.TryParsingDate(input.Time, true);
            lesson.InChargeId   = input.InChargeId;
            lesson.CourseId     = input.CourseId;
            lesson.LessonPeriod = input.LessonPeriod;
            lesson.Note         = input.Note;
            lesson.Status       =
                Domain.Enums.LessonStatus.NotStarted;
            lesson.UpdatedUserId         = input.UserId;
            lesson.UpdatedDate           = DateTime.Now;
            _context.Entry(lesson).State = EntityState.Modified;
            var user = await _context.Users.FirstOrDefaultAsync(x => x.Id == input.UserId);

            var log = new Log()
            {
                DateTime     = DateTime.Now,
                TypeFullName = typeof(Lesson).FullName,
                Content      = "@userName@updateAction@objTitle",
                TypeId       = lesson.Id,
                UserId       = user.Id
            };

            _context.Logs.Add(log);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LessonExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            var result = new LessonDto()
            {
                Id           = lesson.Id,
                Date         = lesson.Date.HasValue ? lesson.Date.Value.ToString("G") : "",
                Time         = lesson.Time.HasValue ? lesson.Time.Value.ToString("T") : "",
                TimeInTimes  = lesson.Time.HasValue && lesson.Date.HasValue ? ((DateTime.Now.Date - lesson.Date.Value).TotalHours + (DateTime.Now.Hour - lesson.Time.Value.Hour)).ToString() : "0",
                CourseId     = lesson.CourseId.HasValue ? lesson.CourseId.Value : 0,
                InChargeId   = lesson.InChargeId,
                InChargeName = users.SingleOrDefault(y => y.Id == lesson.InChargeId).FullName,
                LessonPeriod = lesson.LessonPeriod,
                Note         = lesson.Note,
                Status       = lesson.Status
            };

            return(result);
        }
        public async Task CeateLessonAsync()
        {
            //Arrange
            Theme theme = new Theme
            {
                Name = "ExampleName",
                Id   = 5
            };

            Mentor mentor = new Mentor
            {
                Id = 2
            };

            StudentGroup studentGroup = new StudentGroup
            {
                Id = 3
            };

            List <VisitDto> visitsDto = new List <VisitDto>()
            {
            };
            List <Visit> visits = new List <Visit>()
            {
            };

            var createdLesson = new LessonDto()
            {
                Id             = 7,
                ThemeName      = "ExampleName",
                MentorId       = 2,
                StudentGroupId = 3,
                LessonDate     = DateTime.Parse("2020-11-18T15:00:00.384Z"),
                LessonVisits   = visitsDto
            };

            var createLessonDto = new CreateLessonDto
            {
                ThemeName      = "ExampleName",
                MentorId       = 2,
                StudentGroupId = 3,
                LessonDate     = DateTime.Parse("2020-11-18T15:00:00.384Z"),
                LessonVisits   = visitsDto
            };

            var lessonRepositoryMock = new Mock <ILessonRepository>();

            lessonRepositoryMock.Setup(x => x.Add(It.IsAny <Lesson>()))
            .Callback <Lesson>(x => {
                x.Id             = 7;
                x.LessonDate     = DateTime.Parse("2020-11-18T15:00:00.384Z");
                x.MentorId       = 2;
                x.StudentGroupId = 3;
                x.ThemeId        = 5;
                x.Mentor         = mentor;
                x.StudentGroup   = studentGroup;
                x.Theme          = theme;
                x.Visits         = visits;
            });

            var themeRepositoryMock = new Mock <IThemeRepository>();

            themeRepositoryMock.Setup(x => x.Add(It.IsAny <Theme>()))
            .Callback <Theme>(x =>
            {
                x.Id   = 5;
                x.Name = "ExampleName";
            });

            _unitOfWorkMock.Setup(x => x.LessonRepository).Returns(lessonRepositoryMock.Object);
            _unitOfWorkMock.Setup(x => x.ThemeRepository).Returns(themeRepositoryMock.Object);

            var lessonService = new LessonService(
                _unitOfWorkMock.Object,
                _mapper
                );

            //Act
            var result = await lessonService.CreateLessonAsync(createLessonDto);

            //Assert
            Assert.NotNull(result);

            Assert.Equal(createdLesson.Id, result.Id);
            Assert.Equal(createdLesson.LessonDate, result.LessonDate);
            Assert.Equal(createdLesson.LessonVisits.Count, result.LessonVisits.Count);

            for (int i = 0; i < result.LessonVisits?.Count; i++)
            {
                Assert.Equal(createdLesson.LessonVisits[i]?.Comment, result.LessonVisits[i]?.Comment);
                Assert.Equal(createdLesson.LessonVisits[i]?.Presence, result.LessonVisits[i]?.Presence);
                Assert.Equal(createdLesson.LessonVisits[i]?.StudentId, result.LessonVisits[i]?.StudentId);
                Assert.Equal(createdLesson.LessonVisits[i]?.StudentMark, result.LessonVisits[i]?.StudentMark);
            }

            Assert.Equal(createdLesson.MentorId, result.MentorId);
            Assert.Equal(createdLesson.StudentGroupId, result.StudentGroupId);
            Assert.Equal(createdLesson.ThemeName, result.ThemeName);
        }
        public async Task UpdateLessonAsync()
        {
            //Arrange
            Theme theme = new Theme
            {
                Name = "ExampleName",
                Id   = 5
            };

            Mentor mentor = new Mentor
            {
                Id = 2
            };

            StudentGroup studentGroup = new StudentGroup
            {
                Id = 3
            };

            List <VisitDto> visitsDto = new List <VisitDto>()
            {
            };

            var foundLesson = new Lesson()
            {
                Id             = 7,
                MentorId       = 2,
                StudentGroupId = 3,
                ThemeId        = 5,
                Mentor         = mentor,
                StudentGroup   = studentGroup,
                Theme          = theme,
                Visits         = { }
            };

            var updateLessonDto = new UpdateLessonDto
            {
                ThemeName    = null,
                LessonDate   = DateTime.Parse("2020-11-18T15:30:00.384Z"),
                LessonVisits = null
            };

            var foundLessonDto = new LessonDto()
            {
                Id             = 7,
                ThemeName      = "ExampleName",
                MentorId       = 2,
                StudentGroupId = 3,
                LessonDate     = DateTime.Parse("2020-11-18T15:00:00.384Z"),
                LessonVisits   = null
            };

            var updatedLesson = new LessonDto()
            {
                Id             = 7,
                ThemeName      = "ExampleName",
                MentorId       = 2,
                StudentGroupId = 3,
                LessonDate     = DateTime.Parse("2020-11-18T15:30:00.384Z"),
                LessonVisits   = visitsDto
            };

            _unitOfWorkMock.Setup(x => x.LessonRepository.GetByIdAsync(7))
            .ReturnsAsync(foundLesson);

            var lessonService = new LessonService(
                _unitOfWorkMock.Object,
                _mapper
                );

            //Act
            var result = await lessonService.UpdateLessonAsync(7, updateLessonDto);

            //Assert
            Assert.NotNull(result);

            Assert.Equal(updatedLesson.Id, result.Id);
            Assert.Equal(updatedLesson.LessonDate, result.LessonDate);
            Assert.Equal(updatedLesson.LessonVisits, result.LessonVisits);
            Assert.Equal(updatedLesson.MentorId, result.MentorId);
            Assert.Equal(updatedLesson.StudentGroupId, result.StudentGroupId);
            Assert.Equal(updatedLesson.ThemeName, result.ThemeName);
        }
Beispiel #20
0
 public void Update(LessonDto lesson)
 {
     lessonServiceClient.Update(lesson);
 }
        public async Task <ActionResult <LessonDto> > UpdateLesson([FromRoute] Guid lessonId, [FromBody] LessonDto lessonDto)
        {
            var result = await _timetableService.UpdateLesson(lessonId, lessonDto);

            return(Ok(result));
        }
Beispiel #22
0
        public async Task <IActionResult> Get(int courseId, int moduleId, int id)
        {
            LessonDto lessonDto = _lessonLogic.Get(courseId, moduleId, id);

            return(Ok(lessonDto));
        }
        public async Task <IActionResult> AddEditLesson(LessonDto model)
        {
            using (var txscope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (!ModelState.IsValid)
                    {
                        txscope.Dispose();
                        return(RedirectToAction("AddEditLesson", model.Id));
                    }
                    #region LessonFile
                    string newLessonFile = string.Empty, newLicenseFile = string.Empty;
                    if (model.LessonFile != null)
                    {
                        newLessonFile = $@"lesson-{CommonMethod.GetFileName(model.LessonFile.FileName)}";
                        await CommonMethod.UploadFileAsync(HostingEnvironment.WebRootPath, FilePathListConstant.LessonFile, newLessonFile, model.LessonFile);
                    }
                    #endregion
                    if (model.Id == 0)
                    {
                        model.CreatedDate = DateTime.UtcNow;
                        model.FileName    = newLessonFile;
                        var gradeObj = Mapper.Map <Lessons>(model);
                        gradeObj.IsActive = true;
                        var result = await _lessonService.InsertAsync(gradeObj, Accessor, User.GetUserId());

                        if (result != null)
                        {
                            //StaffLog
                            if (User.IsInRole(UserRoles.Staff))
                            {
                                await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.CreateNewLesson }, Accessor, User.GetUserId());
                            }
                            txscope.Complete();
                            return(JsonResponse.GenerateJsonResult(1, ResponseConstants.CreateNewLesson));
                        }
                    }
                    else if (model != null)
                    {
                        var result = await _lessonService.GetSingleAsync(x => x.Id == model.Id);

                        result.Name     = model.Name;
                        result.FileName = newLessonFile;
                        await _lessonService.UpdateAsync(result, Accessor, User.GetUserId());

                        //StaffLog
                        if (User.IsInRole(UserRoles.Staff))
                        {
                            await _staffLog.InsertAsync(new Log { CreatedDate = DateTime.UtcNow, StaffId = User.GetUserId(), Description = ResponseConstants.UpdateLesson }, Accessor, User.GetUserId());
                        }
                        txscope.Complete();
                        return(JsonResponse.GenerateJsonResult(1, ResponseConstants.UpdateLesson));
                    }
                    else
                    {
                        txscope.Dispose();
                        return(JsonResponse.GenerateJsonResult(0, ResponseConstants.SomethingWrong));
                    }

                    txscope.Dispose();
                    return(JsonResponse.GenerateJsonResult(0, ResponseConstants.SomethingWrong));
                }
                catch (Exception ex)
                {
                    txscope.Dispose();
                    ErrorLog.AddErrorLog(ex, "CreateGrade");
                    return(JsonResponse.GenerateJsonResult(0, ResponseConstants.SomethingWrong));
                }
            }
        }
Beispiel #24
0
        public async Task <string> AddLesson(LessonDto data)
        {
            await lessonService.AddLesson(data);

            return("Done!");
        }
 public async Task Add(LessonDto lessonDto)
 {
     Lesson lesson = _mapper.Map <Lesson>(lessonDto);
     await _lessonRepository.Add(lesson);
 }
Beispiel #26
0
        public async Task <string> UpdateLesson(int lessonId, LessonDto data)
        {
            await lessonService.UpdateLesson(lessonId, data);

            return("Done!");
        }