예제 #1
0
        public Task Handle(RegisterNewStudentCommand message, CancellationToken cancellationToken)
        {
            //check if the command
            if (!message.IsValid())
            {
                //sent notification if the commando is not accepted
                NotifyValidationErrors(message);
                return(Task.CompletedTask);
            }

            //if the course it's full send a notification
            bool isCourseFull = _courseRepository.IsCourseFull(message.CourseId);

            if (isCourseFull)
            {
                Bus.RaiseEvent(new DomainNotification(message.MessageType, "The course has already been full."));
                return(Task.CompletedTask);
            }

            var student = new Student(message.Id, message.Name, message.Age);

            _studentRepository.Add(student);

            //Save Student
            if (Commit())
            {
                Bus.RaiseEvent(new StudentRegisteredEvent(student.Id, student.Name, Convert.ToInt32(student.Age), student.CourseId));
            }

            return(Task.CompletedTask);
        }
예제 #2
0
        public void SqlDaoTest(Student alumno)
        {
            var alumno_devuelto = repositrory.Add(alumno);

            Assert.IsTrue(alumno.Equals(alumno_devuelto));
            Assert.IsTrue(alumno.ID > 0);
        }
예제 #3
0
 public int AddStudent(Person person)
 {
     using (TransactionScope tran = new TransactionScope()) {
         Persons.Add(person);
         Students.Add(new Student()
         {
             Id = person.Id
         });
         // Complete();
         tran.Complete();
         return(person.Id);
     }
 }
예제 #4
0
        public async Task <IActionResult> LikeUser(int id, int recipientId)
        {   // compare userId against the route paramater of userId to see if they match
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());                      // deny access
            }
            var like = await _repo.GetLike(id, recipientId); // get like from repo

            if (like != null)                                // if the like exists - return bad request message
            {
                return(BadRequest("You already like this user"));
            }

            if (await _repo.GetUser(recipientId) == null) //query the repo again to check for recipientId
            {
                return(NotFound());                       // if not found - return notfound
            }
            like = new Like {                             // create new like with the likerid and likeeid
                LikerId = id,
                LikeeId = recipientId
            };

            _repo.Add <Like>(like);    // saves the like into memory

            if (await _repo.SaveAll()) // upon saving the like, if OK, return ok
            {
                return(Ok());
            }

            return(BadRequest("Failed to like user")); // if it fails, return bad message
        }
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photo != null)
                {
                    uniqueFileName = ProcessUpload(model.Photo);
                }

                var student = new Student {
                    Name      = model.Name,
                    Email     = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName,
                };

                // 处理多文件上传
                if (model.Gallery != null && model.Gallery.Count > 0)
                {
                    foreach (var photo in model.Gallery)
                    {
                        ProcessUpload(photo);
                    }
                }

                var newStudent = _studentRepository.Add(student);
                return(RedirectToAction("details", new { id = newStudent.Id }));
            }

            return(View());
        }
예제 #6
0
        public async Task <IActionResult> AddStudent([FromBody] StudentDTO student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input"));
            }

            if (student.age < 1)
            {
                return(BadRequest("Invalid input"));
            }

            Student newStudent = new Student()
            {
                forename = student.forename,
                surname  = student.surname,
                age      = student.age,
                status   = student.status,
                @class   = student.@class
            };

            if (_studentRepository.CheckIfExists(newStudent))
            {
                return(Conflict("Student already exists"));
            }

            bool created = await _studentRepository.Add(newStudent);

            if (created)
            {
                return(Created("", newStudent));
            }

            return(Conflict());
        }
        public IActionResult CreateStudent(Student student)
        {
            // ModelState.IsValid checks the Models validation attributes such as [Required]. In this case the Student Model.
            if (!ModelState.IsValid)
            {
                return(View(nameof(CreateStudentPage)));
            }

            if (student.ImageFile == null)
            {
                student.ImageFileName = "default-image.jpg";
            }
            else
            {
                // Image upload handling
                string uniqueFileName = $"{Guid.NewGuid()}";
                string imageFolder    = Path.Combine(_webHostEnv.WebRootPath, "images");
                string filePath       = Path.Combine(imageFolder, uniqueFileName);
                using FileStream fs = new FileStream(filePath, FileMode.Create);

                student.ImageFile.CopyTo(fs);
                student.ImageFileName = uniqueFileName;
            }
            _studentRepo.Add(student);
            return(RedirectToAction(nameof(ShowStudents)));
        }
예제 #8
0
        public Student CreateStudent(Student student1)
        {
            var student = new Student()
            {
                FirstName   = student1.FirstName,
                LastName    = student1.LastName,
                Gender      = student1.Gender,
                DateOfBirth = student1.DateOfBirth,
                Email       = student1.Email,
                Credit      = student1.Credit
            };

            //if (!_studentRepository.Records.Any(x => x.Email == "*****@*****.**"))

            if (!_studentRepository.Records.Any(x => x.Email == student.Email))
            {
                //student.Id = _studentRepository.Records.Count() + 1;
                _studentRepository.Add(student);
            }
            else
            {
                return(_studentRepository.Records.Where(x => x.Email == student.Email).FirstOrDefault());
            }

            return(student);
        }
        public async Task <IActionResult> RegisterCourses(int id, CourseForRegistrationDto courseForRegistrationDto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var studentFromRepo = await _repo.GetStudent(id);

            var courseName = courseForRegistrationDto.Name.ToLower();
            var getCourse  = await _context.Courses.FirstOrDefaultAsync(x => x.Name == courseName);

            courseForRegistrationDto.creditUnit = getCourse.creditUnit;
            courseForRegistrationDto.faculty    = getCourse.faculty;
            courseForRegistrationDto.Id         = getCourse.Id;
            var studentToSave = _mapper.Map <CourseForRegistrationDto>(getCourse);

            _repo.Add(studentToSave);


            //_mapper.Map(courseForRegistrationDto, studentFromRepo);


            if (await _repo.SaveAll())
            {
                return(NoContent());
            }
            throw new Exception($"Updating user {id} failed on save");
        }
        public void Import(IObjectDataSource <Student> dataSource)
        {
            int count            = 0;
            var studentsToImport = dataSource.GetObjects();

            _log.Information("Importing {countTotal} students", studentsToImport.Count);

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            foreach (var s in studentsToImport)
            {
                _studentRepository.Add(s);
                count++;

                if (count % 50 == 0)
                {
                    _unitOfWork.SaveChanges();
                    _unitOfWork.Dispose();
                    _log.Information("Processed {countProcessed} of {countTotal}", count, studentsToImport.Count);
                }
            }
            _unitOfWork.SaveChanges();

            stopwatch.Stop();
            _log.Information("Import Complete after {timeTaken} seconds", stopwatch.Elapsed.TotalSeconds);
        }
        public Task <bool> Handle(CreateStudentCommand request, CancellationToken cancellationToken)
        {
            var addNew = Student.CreateNew(request.LastName, request.FirstName, request.EnrollmentDate);

            _repo.Add(addNew);
            return(_repo.UnitOfWork.SaveEntitiesAsync());
        }
        public async Task <StudentNotification> Handle(StudentCreateCommand request, CancellationToken cancellationToken)
        {
            string fullName = request.student.FirstName + " " + request.student.LastName;

            try
            {
                await _repository.Add(request.student);

                var result = new StudentNotification()
                {
                    student = request.student, message = $"Student {fullName} was created successful."
                };

                await _mediator.Publish(result);

                return(await Task.FromResult(result));
            }
            catch
            {
                var result = new StudentNotification()
                {
                    student = request.student, message = $"Some thing is wrong cannot create the student {fullName}."
                };

                return(await Task.FromResult(result));
            }
        }
        public IActionResult Index(StudentViewModel student)
        {
            bool   Status  = false;
            string message = "";

            if (ModelState.IsValid)
            {
                var entity = new Student
                {
                    DepartmentId = student.DepartmentId,
                    FirstName    = student.FirstName,
                    LastName     = student.LastName,
                    MatricNumber = student.MatricNumber,
                };
                _studentRepo.Add(entity);
                Status = true;
                //return RedirectToAction(nameof(Login));
            }
            else
            {
                message = "Invalid request";
            }
            ViewBag.Message = message;
            ViewBag.Status  = Status;
            return(View(student));
        }
예제 #14
0
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photo != null)
                {
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                }

                Student newStudent = new Student
                {
                    Name      = model.Name,
                    Email     = model.Email,
                    Course    = model.Course,
                    PhotoPath = uniqueFileName
                };

                _studentRepository.Add(newStudent);
                return(RedirectToAction("details", new { id = newStudent.Id }));
            }
            return(View());
        }
 // Handle Student  || Task ||
 public async Task<int> Handle(CreateStudentCommand command, CancellationToken cancellationToken)
 {
     var student = new Student();
     student.FirstName = command.FirstName;
      await _studentRepository.Add(student);
     return student.Id;  
 }
예제 #16
0
 public IActionResult Creat(StudentCreatViewModel model)
 {
     if (ModelState.IsValid)
     {
         string uniqueFileName = null;
         //if (model.Photos != null || model.Photos.Count > 0)
         //{
         //    //string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");//wwwroot下的images
         //    //uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;//特殊唯一文件名
         //    //string filePath = Path.Combine(uploadsFolder, uniqueFileName);//拼接出文件目录文件名
         //    //model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));//复制图片到指定目录
         //    foreach (var Photo in model.Photos)
         //    {
         //        string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");//wwwroot下的images
         //        uniqueFileName = Guid.NewGuid().ToString() + "_" + Photo.FileName;//特殊唯一文件名
         //        string filePath = Path.Combine(uploadsFolder, uniqueFileName);//拼接出文件目录文件名
         //        Photo.CopyTo(new FileStream(filePath, FileMode.Create));//复制图片到指定目录
         //    }
         //}
         uniqueFileName = ProcessUploadedFile(model);
         Student newstudent = new Student {
             Id = model.Id, Name = model.Name, Number = model.Number, PhotoPath = uniqueFileName
         };
         _studentRepository.Add(newstudent);
         return(RedirectToAction("Details", new { id = newstudent.Id }));
         //Student newstudent = _studentRepository.Add(student);
         //return RedirectToAction("Details", new { id = newstudent.Id });
     }
     return(View());
 }
예제 #17
0
        public void AddStudent(StudentRequest studentRequest)
        {
            var student = Mapper.Map <StudentRequest, Student>(studentRequest);

            student.Id = 0;
            _studentRepository.Add(student);
        }
예제 #18
0
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;

                if (model.Photo != null)
                {
                    //必须将图像上传到wwwroot中的images文件夹
                    //而要获取wwwroot文件夹的路径,我们需要注入 ASP.NET Core提供的HostingEnvironment服务
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
                    //为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                Student newStudent = new Student
                {
                    Name      = model.Name,
                    Email     = model.Email,
                    ClassName = model.ClassName,
                    //   将文件名保存在student对象的PhotoPath属性中 它将保存到数据库 Students的 表中
                    PhotoPath = uniqueFileName
                };

                _studentRepository.Add(newStudent);
                return(RedirectToAction("details", new { id = newStudent.Id }));
            }

            return(View());
        }
예제 #19
0
        public ActionResult Create(StudentViewModel model)
        {
            if (ModelState.IsValid)
            {
                // TODO: Add insert logic here
                var student = new Student
                {
                    Age       = model.Age,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Address   = new Address
                    {
                        Cuntry     = model.Cuntry,
                        City       = model.City,
                        Street     = model.Street,
                        PostalCode = model.PostalCode
                    }
                };

                studentRepository.Add(student);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View(model));
            }
        }
예제 #20
0
        public async Task <dynamic> Add(StudentRequest studentRequest)
        {
            if (studentRequest == null)
            {
                AddError("20000");
                return(null);
            }

            var student = Student.Create(studentRequest.Name);

            if (!student.IsValid)
            {
                AddErrors(student.Error);
                return(null);
            }

            //var course = await _courseRepository.FindById(Guid.Parse("B0DDB957-E4D4-482D-88AC-686ECE51CB52"));
            //var studentCourse = StudentCourse.Create(student, course);
            //student.RegistreStudent(studentCourse);
            _studentRepository.Add(student);

            var studentResponse = _mapper.Map <Student, StudentResponse>(student);

            return(await Task.FromResult(studentResponse));
        }
예제 #21
0
        public Task <Unit> Handle(RegisterStudentCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidattionErrors(message);
                return(Task.FromResult(new Unit()));
            }

            var address  = new Address(message.Province, message.City, message.County, message.Street);
            var customer = new Student(Guid.NewGuid(), message.Name, message.Email, message.Phone, message.BirthDate, address);

            if (_studentRepository.GetByEmail(customer.Email) != null)
            {
                //List<string> errorInfo = new List<string>() { "此邮箱已存在!!" };
                //_cache.Set("ErrorData", errorInfo);

                _bus.RaiseEvent(new DomainNotification("", "此邮箱已存在"));
                return(Task.FromResult(new Unit()));
            }

            _studentRepository.Add(customer);

            if (Commit())
            {
                // 提交成功后,这里需要发布领域事件
                // 比如欢迎用户注册邮件呀,短信呀等
                // waiting....
            }
            return(Task.FromResult(new Unit()));
        }
예제 #22
0
        public async Task <IActionResult> Add(StudentViewModel model)
        {
            if (ModelState.IsValid)
            {
                var uniqueFileName = string.Empty;
                if (model.PhotoPath != null)
                {
                    var uploadsFoloder = Path.Combine(webHostEnvironment.WebRootPath, "Images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.PhotoPath.FileName;

                    string filepath = Path.Combine(uploadsFoloder, uniqueFileName);

                    model.PhotoPath.CopyTo(new FileStream(filepath, FileMode.Create));

                    Student student = new Student()
                    {
                        Grade   = model.Grade,
                        Mailbox = model.Mailbox,
                        Name    = model.Name,
                        Photo   = uniqueFileName
                    };
                    var stu = await _studentRepository.Add(student);

                    if (stu > 0)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }
            return(View());
        }
        public Domain.Entities.Student Add(Domain.Entities.Student entity)
        {
            if (!_person.CheckIfExists(entity.Person))
            {
                try
                {
                    _person.Add(entity.Person);
                }
                catch (Exception ex)
                {
                    entity.AddError(ex.Message);
                    return(entity);
                }
            }

            if (VerifyStudentAlreadyEnrolled(entity))
            {
                entity.AddError("Estudante já matriculado");
                return(entity);
            }

            //TODO INCLUIR VERIFICAÇÃO SE ESTUDANTE TENTANDO SE MATRICULAR É PROFESSOR NO CURSO
            entity.EnrollmentID = GenerateEnrollmentID(entity);

            entity.Status = EEnrollmentStatus.WAITING_APROVEMENT;

            _studentRepository.Add(entity);

            //check if the person is a professor
            return(entity);
        }
예제 #24
0
        public IActionResult AddS(StudentsAddSViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;

                if (model.Photos != null && model.Photos.Count > 0)
                {
                    uniqueFileName = ProcessUploadedFile(model);
                }

                Student newStudent = new Student
                {
                    Name      = model.Name,
                    Email     = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName,
                };

                _studentRepository.Add(newStudent);

                //Student newStudent = _studentRepository.Add(student);

                return(RedirectToAction("Data", new { id = newStudent.Id }));
            }

            return(View());
        }
예제 #25
0
        public StudentCreatedDto CreateStudent(Student student)
        {
            student = _studentRepository.Add(student);
            var createdStudent = Mapper.Map <Student, StudentCreatedDto>(student);

            return(createdStudent);
        }
예제 #26
0
 public void CreateStudent(Student student)
 {
     if (student.IsValid)
     {
         _studentRepository.Add(student);
     }
 }
예제 #27
0
        /// <summary>
        ///  不仅包括命令验证的收集,持久化,还有领域事件和通知的添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task <Unit> Handle(RegisterStudentCommand message, CancellationToken cancellationToken)
        {
            // 命令验证
            if (!message.IsValid())
            {
                // 错误信息收集
                NotifyValidationErrors(message);
                return(Task.FromResult(new Unit()));
            }

            // 实例化领域模型,这里才真正的用到了领域模型
            // 注意这里是通过构造函数方法实现
            var customer = new Student(1, message.Name, message.Email);

            // 持久化
            _studentRepository.Add(customer);

            // 统一提交
            if (Commit())
            {
                // 提交成功后,这里需要发布领域事件
                // 比如欢迎用户注册邮件呀,短信呀等

                // waiting....
            }

            return(Task.FromResult(new Unit()));
        }
예제 #28
0
        public async Task Create(CreateStudentDto student)
        {
            var careers = _careerRepository.Filter(career => student.Careers.Contains(career.Id));
            var campus  = await _campusRepository.FindById(student.Campus);

            var studentInfo = new Student
            {
                Account       = student.Account,
                FirstName     = student.FirstName,
                SecondName    = student.SecondName,
                FirstSurname  = student.FirstSurname,
                SecondSurname = student.SecondSurname,
                Campus        = campus,
                Settlement    = student.Settlement,
                Email         = student.Email
            };

            foreach (var career in careers)
            {
                studentInfo.StudentCareers.Add(new StudentCareer {
                    Career = career
                });
            }
            var stud = _studentRepository
                       .All()
                       .Include(x => x.StudentCareers)
                       .FirstOrDefault(x => x.Account == studentInfo.Account);

            await _studentRepository.Add(studentInfo);
        }
        public IHttpActionResult PostStudent(StudentDTO studentDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //if(studentID == null || firstName == null || lastName == null)
            //{
            //    return BadRequest("One or more parameters are missing values");
            //}

            if (studentDTO == null)
            {
                return(BadRequest("Missing values"));
            }
            Student student = Mapper.Map <Student>(studentDTO);


            studentRepo.Add(student);


            try
            {
                studentRepo.Save();
                return(Ok(student));
            }
            catch
            {
                return(BadRequest("Failed to add student"));
            }

            //return CreatedAtRoute("DefaultApi", new { id = Student.ID }, Student);
        }
예제 #30
0
        public async Task <string> Handle(StudentCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                string fullName = request.student.FirstName + "" + request.student.LastName;

                await _repository.Add(request.student);

                await _mediator.Publish(new StudentCreateNotification()
                {
                    student = request.student
                });

                return(await Task.FromResult($"Student {fullName} was created successfull."));
            }
            catch (Exception ex)
            {
                await _mediator.Publish(new StudentCreateNotification()
                {
                    student = request.student
                });

                await _mediator.Publish(new ErrorNotification { Error = ex.Message, SourceError = ex.StackTrace });

                return(await Task.FromResult("Some wrong happened to create the student."));
            };
        }