public void Setup()
        {
            mockStudentRepository = new Mock<StudentRepository>();
            mockCourseTakenRepository = new Mock<CourseTakenRepository>();
            service = new DomainStudentService(mockStudentRepository.Object, mockCourseTakenRepository.Object);
            coursesTaken = new List<CourseTakenModel>();
            studentId = Guid.NewGuid();

            mockCourseTakenRepository.Setup(r => r.FindCourses(studentId)).Returns(coursesTaken);
        }
 public ActionResult AddStudent()
 {
     Student s = new Student();
     s.Name = "111";
     s.Age = 12;
     s.Score = 100;
     StudentService ss = new StudentService();
     ss.Add(s);
     var list = ss.GetStudent();
     return Content("");
 }
        public static async Task<StudentDisplayObject> GetStudentDisplayObject(StudentService cs, Student student)
        {
            var sections = GetSectionsByStudentId(cs, student.id);
            var assessments = GetStudentAssessmentsByStudentId(cs, student.id);

            await Task.WhenAll(sections, assessments);

            var result = MapStudentToStudentDisplayObject(student, sections.Result, assessments.Result);

            return result;
        }
        private void LoadData()
        {
            // if the user has logged in
            var user = LoggedInUser;

            StudentService service = new StudentService();
            var studentList = service.GetStudents();

            GridViewStudentList.DataSource = studentList;
            GridViewStudentList.DataBind();
        }
        //
        // GET: /Registration/Details
        public ActionResult Details(string id)
        {
            RegistrationStudent student = new StudentService().GetStudentById(id);

            if (student.name == null)
            {
                return View("NotFound");
            }

            else
            {
                return View(student);
            }
        }
        public static async Task<StudentDisplayObject> GetStudentDisplayObject(StudentService ss, Student student)
        {
            //check to see if the item is already in cache. if so, return the cache item
            var cache = (StudentDisplayObject)HttpContext.Current.Cache[student.id];
            if (cache != null)
                return cache;

            var sections = GetSectionsByStudentId(ss, student.id);
            var assessments = GetStudentAssessmentsByStudentId(ss, student.id);
            var academicRecords = GetAllStudentsAcademicRecords(ss);

            await Task.WhenAll(sections, assessments, academicRecords);           

            var sdo = MapStudentToStudentDisplayObject(student, sections.Result, assessments.Result, academicRecords.Result);
            HttpContext.Current.Cache.Insert(student.id, sdo);
            return sdo;
        }
        public void ShouldGetStudentById()
        {
            //create mock and test data
            //var mock = new Mock<IUnitOfWork>();
            mock.Setup(x => x.StudentRepository.GetByID(1))
            .Returns(new Student {
                LastName     = "King",
                FirstMidName = "John",
            });

            //excute test by mock
            _studentService = new StudentService(mock.Object);
            var stu = _studentService.GetStudentById(1);

            Assert.NotNull(stu);
            Assert.IsType(typeof(StudentDto), stu);
            Assert.Equal("John King", stu.FullName);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string     studentId  = Request.QueryString["StudentId"];
                StudentExt objStudent = new StudentService().GetStudentById(studentId);

                this.ltaStudentId.Text   = objStudent.StudentId.ToString();
                this.ltaStudentName.Text = objStudent.StudentName;
                this.ltaStudentIdNo.Text = objStudent.StudentIdNo;
                this.ltaPhoneNumber.Text = objStudent.PhoneNumber;
                this.ltaAddress.Text     = objStudent.StudentAddress;
                this.ltaClass.Text       = objStudent.ClassName;//Binding class
                this.ltaGender.Text      = objStudent.Gender;
                this.ltaBirthday.Text    = objStudent.Birthday.ToString("yyyy-MM-dd");
                this.stuImg.ImageUrl     = "~/images/Student/" + objStudent.StudentId + ".jpg";
            }
        }
        public void Add_New_Student()
        {
            var options = new DbContextOptionsBuilder <SchoolLibraryContext>()
                          .UseInMemoryDatabase("Add_New_Student")
                          .Options;

            using (var context = new SchoolLibraryContext(options))
            {
                var service = new StudentService(context);

                service.Add(new Student
                {
                    Id = 100
                });

                Assert.Equal(100, context.Students.Single().Id);
            }
        }
        public async Task AddStudentTest(StudentDto studentDto, Student expected)
        {
            // Arrange
            Mock <ICrudRepository <Student> > repositoryMock = new();
            var loggerMock = new Mock <ILogger <StudentService> >();
            var mapperMock = new Mock <IMapper>();

            mapperMock.Setup(mapper => mapper.Map <Student?>(studentDto)).Returns(expected);
            var service = new StudentService(repositoryMock.Object, mapperMock.Object, loggerMock.Object);

            // Act
            int id = await service.AddStudent(studentDto);

            // Assert
            Assert.That(id, Is.EqualTo(expected.Id));
            repositoryMock.Verify(repository => repository.SaveAsync(expected, It.IsAny <CancellationToken>()));
            repositoryMock.VerifyNoOtherCalls();
        }
Beispiel #11
0
        private void IntiStudentList()
        {
            //var student is loaded with the teacher list
            var students = StudentService.Load();

            //For every student object, attributes are binded to the respective form component.
            foreach (var student in students)
            {
                this.txtName.Text      = student.Name;
                this.txtSurname.Text   = student.Surname;
                this.txtSubject.Text   = student.Subject;
                this.txtIDCard.Text    = student.IdCard;
                this.txtClass.Text     = student.ClassStudent;
                this.txtAddress.Text   = student.Address;
                this.txtDOB.Text       = Convert.ToString(student.DateOfBirth);
                this.txtContactNo.Text = Convert.ToString(student.ContactNo);
            }
        }
Beispiel #12
0
        public void loadData()
        {
            //sinhVien = StudentService.getSinhVienToFile(pathSinhVien, "101");
            sinhVien            = StudentService.GetSinhVienFromDB(idsv);
            txtMa.Text          = sinhVien.ID;
            txtTen.Text         = sinhVien.FullName;
            dtpNgaySinh.Value   = sinhVien.DateOfBirth;
            ckbGioiTinh.Checked = sinhVien.Gender == Models.GENDER.Male;
            txtNoiSinh.Text     = sinhVien.PlaceOfBirth;

            //sinhVien.quaTrinh = QuaTrinhService.getListQuaTrinh("102");
            //sinhVien.quaTrinh = QuaTrinhService.getListQuaTrinh(pathQuaTrinh, sinhVien.ID);
            sinhVien.quaTrinh = QuaTrinhService.getListQuaTrinhFromDB(idsv);
            dgvQuaTrinh.AutoGenerateColumns = false;
            bdsQuaTrinh.DataSource          = sinhVien.quaTrinh;

            dgvQuaTrinh.DataSource = bdsQuaTrinh;
        }
Beispiel #13
0
        private void UpdateStudentForm_Load(object sender, EventArgs e)
        {
            using (StudentService studentService = new StudentService())
            {
                var students = studentService.List();

                lbStudents.DataSource    = students;
                lbStudents.DisplayMember = "FullName";
                lbStudents.ValueMember   = "StudentId";
            }

            using (DefinitionService definitionService = new DefinitionService())
            {
                cbRecordStatus.DataSource    = definitionService.GetRecordStatuses();
                cbRecordStatus.DisplayMember = "RecordStatusName";
                cbRecordStatus.ValueMember   = "RecordStatusId";
            }
        }
Beispiel #14
0
 public void linq_group()
 {
     StudentService studentService = new StudentService(new StudentRepository());
     var            s = studentService.GetAll(1);
     var            r = s.GroupBy(c => c.School).Select(group => new
     {
         group.Key,
         count = group.Count()
     });
     var w = from a in s
             group a by a.School
             into g
             select new
     {
         g.Key,
         count = g.Count()
     };
 }
Beispiel #15
0
        public void CalculateGpaNoEnrollmentTest()
        {
            //// Arrange
            var errors = new List <string>();

            var mockRepository = new Mock <IStudentRepository>();
            var studentService = new StudentService(mockRepository.Object);

            mockRepository.Setup(x => x.GetEnrollments("testId")).Returns(new List <Enrollment>());

            //// Act
            var enrollments = studentService.GetEnrollments("testId", ref errors);
            var gap         = studentService.CalculateGpa("testId", enrollments, ref errors);

            //// Assert
            Assert.AreEqual(0, errors.Count);
            Assert.AreEqual(0.0f, gap);
        }
Beispiel #16
0
        public void UpdateStudent_ReturnEmptyValidationResponse_WhenStudentIsValid()
        {
            //Arrange
            Student student           = GetDefaultStudent();
            var     studentRepository = Substitute.For <IRepository <Student> >();

            studentRepository.GetAll().Returns(new List <Student>());
            StudentService studentService = new StudentService(studentRepository, null);

            //Act
            var result = studentService.UpdateStudent(student);

            //Assert
            ValidationResponse expected = new ValidationResponse();

            expected.Should().BeEquivalentTo(result);
            studentRepository.Received(Quantity.Exactly(1)).Update(student);
        }
Beispiel #17
0
        public void Insert_GetStudentByEmail()
        {
            ServiceTestsHelper helper         = new ServiceTestsHelper();
            StudentService     studentService = helper.studentService;

            var student = new Student()
            {
                Id    = 1,
                Name  = "name",
                Email = "*****@*****.**"
            };

            studentService.Insert(student);
            var tmp = studentService.GetStudentByEmail("*****@*****.**");

            Assert.NotNull(tmp);
            Assert.Equal(tmp.Email, "*****@*****.**");
        }
        public async void OnPrezentSelected()
        {
            if (student == null)
            {
                var response = await StudentService.GetById();

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    student = JsonConvert.DeserializeObject <StudentModel>(content);
                }
            }
            if (student != null && !StudentiPrezenti.Any(a => a.Nume == student.Nume))
            {
                StudentiPrezenti.Add(student);
            }
        }
Beispiel #19
0
        private async void btnSave_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            student.DateOfBirth = dpDateTime.UtcDateTime;

            if (ValidateForm())
            {
                var studentService = new StudentService();
                var response       = (MessageResult)studentService.Save(student);

                var dialog = new MessageDialog(response.IsSuccess ? "Save Successful!" : response.ErrorMessage);
                await dialog.ShowAsync();

                if (response.IsSuccess)
                {
                    this.Frame.Navigate(typeof(StudentsPage));
                }
            }
        }
        public void TestAddStudent()
        {
            //Create mock of DbSet
            var mockSet = GetQueryableMockDbSet(new Student());

            //Create mock for context with mocked dbset
            var mockContext = new Mock <StudentDBEntities>();

            mockContext.Setup(m => m.Students).Returns(mockSet.Object);

            //Create service with mocked context
            var studentService = new StudentService(mockContext.Object);

            studentService.AddStudent(CreateMockStudent());

            //Verify that an insertion has been made
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
Beispiel #21
0
        public void Delete_RedirectsToStudents_WhenStudentExists()
        {
            //Arrange
            Student student = new Student()
            {
                Name = "Test Student"
            };
            StudentService studentService = Substitute.For <StudentService>();

            studentService.GetStudentById(5).Returns(student);
            StudentController controller = new StudentController(studentService);

            //Act
            var actionResult = controller.Delete(student.Id);

            // Assert
            actionResult.Should().BeOfType <RedirectToActionResult>().Which.ActionName.Should().Be("Students");
        }
Beispiel #22
0
        public async void Create()
        {
            var mock  = new ServiceMockFacade <IStudentRepository>();
            var model = new ApiStudentRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Student>())).Returns(Task.FromResult(new Student()));
            var service = new StudentService(mock.LoggerMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.StudentModelValidatorMock.Object,
                                             mock.BOLMapperMockFactory.BOLStudentMapperMock,
                                             mock.DALMapperMockFactory.DALStudentMapperMock);

            CreateResponse <ApiStudentResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            mock.ModelValidatorMockFactory.StudentModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiStudentRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Student>()));
        }
Beispiel #23
0
        public ActionResult Plan()
        {
            var user    = GetCurrentUser();
            var student = StudentService.GetCurrentStudent(user);
            var thesis  = Db.Theses.FirstOrDefault(x => x.Student.Id == student.Id);

            var model = new ThesisStateModel
            {
                User      = user,
                Student   = student,
                Thesis    = thesis,
                IssueDate = DateTime.Today.ToShortDateString()
            };



            return(View(model));
        }
Beispiel #24
0
        public async void All()
        {
            var mock    = new ServiceMockFacade <IStudentRepository>();
            var records = new List <Student>();

            records.Add(new Student());
            mock.RepositoryMock.Setup(x => x.All(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(records));
            var service = new StudentService(mock.LoggerMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.StudentModelValidatorMock.Object,
                                             mock.BOLMapperMockFactory.BOLStudentMapperMock,
                                             mock.DALMapperMockFactory.DALStudentMapperMock);

            List <ApiStudentResponseModel> response = await service.All();

            response.Should().HaveCount(1);
            mock.RepositoryMock.Verify(x => x.All(It.IsAny <int>(), It.IsAny <int>()));
        }
Beispiel #25
0
        public async void Delete()
        {
            var mock  = new ServiceMockFacade <IStudentRepository>();
            var model = new ApiStudentRequestModel();

            mock.RepositoryMock.Setup(x => x.Delete(It.IsAny <int>())).Returns(Task.CompletedTask);
            var service = new StudentService(mock.LoggerMock.Object,
                                             mock.RepositoryMock.Object,
                                             mock.ModelValidatorMockFactory.StudentModelValidatorMock.Object,
                                             mock.BOLMapperMockFactory.BOLStudentMapperMock,
                                             mock.DALMapperMockFactory.DALStudentMapperMock);

            ActionResponse response = await service.Delete(default(int));

            response.Should().NotBeNull();
            mock.RepositoryMock.Verify(x => x.Delete(It.IsAny <int>()));
            mock.ModelValidatorMockFactory.StudentModelValidatorMock.Verify(x => x.ValidateDeleteAsync(It.IsAny <int>()));
        }
        private void updateTableHistoryLearning()
        {
            var histories = StudentService.GetHistoryLearningsToDB(idStudent);

            if (histories != null)
            {
                bdsQuaTrinhHocTap.DataSource = histories;
            }
            dtgQuaTrinhHocTap.DataSource = bdsQuaTrinhHocTap;
            if (histories == null)
            {
                toolStripStatusTotalHistoryLearning.Text = "Tổng số mục: 0";
            }
            else
            {
                toolStripStatusTotalHistoryLearning.Text = "Tổng số mục: " + histories.Count.ToString();
            }
        }
        public async Task OneToManyStudentGroupTestAsync()
        {
            var options = new DbContextOptionsBuilder <OlpContext>()
                          .UseInMemoryDatabase(databaseName: "UserGroupTest")
                          .Options;

            // Run the test against one instance of the context
            using (var context = new OlpContext(options))
            {
                Domain.Group group = new Domain.Group()
                {
                    GroupId     = 1,
                    Name        = "PI15B",
                    Description = "make viko great again"
                };

                var groupService = new GroupService(context);
                await groupService.Create(group);

                Domain.Group fecthedGroup = await groupService.FindBy(x => x.Name == group.Name);

                Assert.AreEqual(fecthedGroup.Name, group.Name);
                Console.Write("Group  : " + group.Name + " successfully added");

                //user insert
                Domain.Student student = new Domain.Student()
                {
                    GroupId   = 1,
                    FirstName = "Daniel",
                    LastName  = "Zeimo",
                    Email     = "*****@*****.**"
                };

                var studentService = new StudentService(context);
                await studentService.Create(student);

                Domain.Student fetchedUser = await studentService.FindBy(x => x.FirstName == student.FirstName);

                Assert.AreEqual(fetchedUser.FirstName, student.FirstName);
                Assert.AreEqual(group.Name, fetchedUser.Group.Name);
                Console.Write("|User  : "******" successfully added");
                Console.Write("|User group : " + fetchedUser.Group.Name + " Description" + fetchedUser.Group.Description);
            }
        }
        public frmThongTinSinhVien(string maSinhVien)
        {
            InitializeComponent();

            pathDirectoryImg        = Application.StartupPath + "\\Img";
            pathAvatarImg           = pathDirectoryImg + "\\avatar.png";
            picAnhDaiDien.AllowDrop = true;

            pathStudentDataFile         = Application.StartupPath + @"\Data\student.txt";
            pathLearningHistoryDataFile = Application.StartupPath + @"\Data\learninghistory.txt";
            if (File.Exists(pathAvatarImg))
            {
                FileStream fileStream = new FileStream(pathAvatarImg, FileMode.Open, FileAccess.Read);
                picAnhDaiDien.Image = Image.FromStream(fileStream);
                fileStream.Close();
            }

            bdsQuaTrinhHocTap.DataSource          = null;
            dtgQuaTrinhHocTap.AutoGenerateColumns = false;

            //var student = StudentService.GetStudent(maSinhVien);
            var student = StudentService.GetStudent(pathStudentDataFile, maSinhVien);

            if (student == null)
            {
                throw new Exception("Không tồn tại sinh viên này");
            }
            else
            {
                student.ListHistoryLearning = StudentService.GetHistoryLearning(
                    pathLearningHistoryDataFile, maSinhVien);
                txtMaSinhVien.Text  = student.IDStudent;
                txtHo.Text          = student.LastName;
                txtTen.Text         = student.FirstName;
                txtQueQuan.Text     = student.POB;
                dtpNgaySinh.Value   = student.DOB;
                chkGioiTinh.Checked = student.Gender == GENDER.Male;
                if (student.ListHistoryLearning != null)
                {
                    bdsQuaTrinhHocTap.DataSource = student.ListHistoryLearning;
                }
            }
            dtgQuaTrinhHocTap.DataSource = bdsQuaTrinhHocTap;
        }
Beispiel #29
0
        private async Task <bool> AuthoriseCreate(Guid personId, Guid userId)
        {
            var taskPersonTypes = await _personService.GetPersonTypes(personId);

            if (taskPersonTypes.Student)
            {
                if (User.IsType(UserTypes.Student))
                {
                    var student = await StudentService.GetByPersonId(personId);

                    return(await AuthoriseStudent(student.Id));
                }

                if (User.IsType(UserTypes.Staff))
                {
                    return(true);
                }
            }

            else if (taskPersonTypes.Employee)
            {
                if (await UserHasPermission(Permissions.People.StaffTasks.EditAllStaffTasks))
                {
                    return(true);
                }

                var taskStaffMember = await _staffMemberService.GetByPersonId(personId, false);

                var userStaffMember = await _staffMemberService.GetByUserId(userId, false);

                if (userStaffMember != null && taskStaffMember != null)
                {
                    if (taskStaffMember.Id == userStaffMember.Id)
                    {
                        return(true);
                    }

                    return(await UserHasPermission(Permissions.People.StaffTasks.EditManagedStaffTasks) &&
                           await _staffMemberService.IsLineManager(taskStaffMember.Id, userStaffMember.Id));
                }
            }

            return(false);
        }
Beispiel #30
0
        public ActionResult Create([Bind(Include = "StudentId,StudentSchoolYearId,SchoolYearId,DistrictId,FirstName,MiddleName,LastName,BirthDate,Hispanic,StateId,LocalId,EnrollmentDate,IepIndicator,LepIndicator,FrlIndicator,")] StudentExt studentExt, int hdSchoolId, int?hdLineageId, int hdGradeId, int hdGenderId, int?hdRaceId, int?hdHomeLanguageId, int?hdNativeLanguageId, int schoolYear)
        {
            try
            {
                dbTIREntities  db             = new dbTIREntities();
                SiteUser       siteUser       = ((SiteUser)Session["SiteUser"]);
                StudentService studentService = new StudentService(siteUser, db);

                if (ModelState.IsValid)
                {
                    studentExt.ServingSchoolId  = hdSchoolId;
                    studentExt.LineageId        = hdLineageId;
                    studentExt.NativeLanguageId = hdNativeLanguageId;
                    studentExt.HomeLanguageId   = hdHomeLanguageId;
                    studentExt.RaceId           = hdRaceId;
                    studentExt.GradeLevel       = (short)hdGradeId;
                    studentExt.GenderId         = hdGenderId;
                    studentExt.SchoolYear       = schoolYear;
                    if (studentService.IsStudentExist(studentExt.StateId, null))
                    {
                        PopulateViewData(studentExt);
                        ModelState.AddModelError("StateId", "State Id already exists");
                        return(View(studentExt));
                    }
                    else if (studentService.IsStudentExist(null, studentExt.LocalId))
                    {
                        PopulateViewData(studentExt);
                        ModelState.AddModelError("LocalId", "Local Id already exists");
                        return(View(studentExt));
                    }
                    else
                    {
                        studentService.SaveStudents(studentExt);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging log = new Logging();
                log.LogException(ex);
                return(View("GeneralError"));
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult LoginByCredential(LoginModel model)
        {
            StudentService sinhVienService  = new StudentService();
            TeacherService giangVienService = new TeacherService();

            if (ModelState.IsValid)
            {
                var login = sinhVienService.LoginByCredential(model.Username, model.Password);
                if (login == null)
                {
                    var lg = giangVienService.LoginByCredential(model.Username, model.Password);
                    if (lg == null)
                    {
                        ModelState.AddModelError("LoginError", "Đăng nhập không thành công");
                    }
                    else
                    {
                        //List<String> list = giangVienService.XetQuyen(lg.ID);
                        IQueryable list = giangVienService.XetQuyen(lg.ID);
                        Session["Quyen"] = "";
                        foreach (string item in list)
                        {
                            Session["Quyen"] += " " + item;
                        }
                        Session["UserId"]   = lg.ID;
                        Session["Username"] = lg.MaGV;
                        Session["Fullname"] = lg.FirstName + " " + lg.LastName;
                        return(Redirect("/Home/Index"));
                    }
                }
                else
                {
                    Session["UserId"]   = login.ID;
                    Session["Username"] = login.MaSV;
                    Session["Fullname"] = login.FirstName + " " + login.LastName;
                    return(Redirect("/Home/Student"));
                }
            }
            else
            {
                ModelState.AddModelError("LoginError", "Đăng nhập không thành công");
            }
            return(View("Index"));
        }
Beispiel #32
0
        public async Task ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            Mock <IEmailSenderService>  mockEmail   = new Mock <IEmailSenderService>();
            Mock <IRegistrationService> mockReg     = new Mock <IRegistrationService>();
            Mock <IErrorHandler>        handlerMock = new Mock <IErrorHandler>();

            IServicesExecutor <StudentDTO, Student> executor
                = new ServiceExecutor <StudentDTO, Student>(_context, handlerMock.Object);
            IStudentService          studentService = new StudentService(executor);
            IStudentManagmentService studMngService
                = new StudentManagmentService(
                      mockEmail.Object,
                      studentService,
                      mockReg.Object,
                      _sharedConfigMock.Object,
                      _imgMock.Object,
                      handlerMock.Object,
                      _context);

            Student stud = await _context.Students.FirstOrDefaultAsync(s => s.Username == "light");

            const string studOldPassword = "******";

            PassChangeStatus status = await studMngService.UpdateStudentPassword(
                stud.StudentId, new UpdatePasswordDTO
            {
                OldPassword     = oldPassword,
                NewPassword     = newPassword,
                ConfirmPassword = confirmPassword
            });

            if (studOldPassword != oldPassword)
            {
                Assert.AreEqual(PassChangeStatus.InvalidOldPass, status);
            }
            else if (newPassword != confirmPassword)
            {
                Assert.AreEqual(PassChangeStatus.PassNoMatch, status);
            }
            else
            {
                Assert.AreEqual(PassChangeStatus.Success, status);
            }
        }
        public ActionResult Create(HomeworkViewModel homework)
        {
            if (homework.endDate <= DateTime.Now)
            {
                ModelState.AddModelError("", "Please choose another end date!");
                return(View());
            }
            if (ModelState.IsValid)
            {
                try
                {
                    HomeworkService service = new HomeworkService();
                    int             id      = Int32.Parse(Request.Cookies["UserSettings"].Values["UserID"]);
                    homework.TeacherID = id;
                    service.AddHomework(homework);
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                    return(View());
                }
                try
                {
                    StudentService           studentService = new StudentService();
                    int                      id             = Int32.Parse(Request.Cookies["UserSettings"].Values["UserID"]);
                    List <StudInfoViewModel> studentsList   = studentService.GetStudentsByTeacherID(id);//all students

                    EmailNotification notification = new EmailNotification(new EmailSender());

                    foreach (var student in studentsList)
                    {
                        notification.NotifystudentWhenHomeworkIsCreated(student.Email, student.FirstName, homework.endDate);
                    }
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Unable to send email to all students. Try again, and if the problem persists, see your system administrator.");
                    return(RedirectToAction("MyHomeworks", "Teacher"));
                }
            }


            return(RedirectToAction("MyHomeworks", "Teacher"));
        }
Beispiel #34
0
        static void Main(string[] args)
        {
            StudentService studentService = new StudentService();
            var            students       = studentService.GetStudentList();

            Console.WriteLine("İsim giriniz:");
            string name = Console.ReadLine();

            Console.WriteLine("Soyisim giriniz:");
            string surname = Console.ReadLine();

            Console.WriteLine("Okul no giriniz:");
            string schoolIdStr = Console.ReadLine();

            int schoolId;

            try
            {
                schoolId = int.Parse(schoolIdStr);
            }
            catch
            {
                schoolId = -1;
                Console.WriteLine("Girilen değer geçersiz!");
            }

            var student = new Student()
            {
                Name     = name,
                Surname  = surname,
                SchoolId = schoolId
            };

            ResponseResult studentAddingResult = studentService.AddStudent(student);

            if (studentAddingResult.IsSuccessful)
            {
                Console.WriteLine("Öğrenci eklendi.");
            }
            else
            {
                Console.WriteLine("İşlem başarısız. : " + studentAddingResult.Message);
            }
        }
Beispiel #35
0
        private void LoadStudent(string studID)
        {
            Student st = new StudentService().GetStudent(studID, new SessionManager().GetUserId(this.Session));

            txtFName.Text         = st.FNames;
            txtIndexNo.Text       = st.IndexNo;
            txtMobile.Text        = st.Mobile;
            txtONames.Text        = st.ONames;
            txtPostalAddress.Text = st.PostAdd;
            txtResAddress.Text    = st.ResAdd;
            txtSName.Text         = st.SName;
            txtStudUserID.Text    = st.UserId;
            txtTel.Text           = st.Tel;
            txtEmail.Text         = st.Email;
            dtDOB.Date            = st.Dob.Date;
            cmbGender.Value       = st.Gender.ToString();
            cmbGender.Text        = st.Gender.ToString();
            cmbMarital.Value      = st.Marital.ToString();
            cmbMarital.Text       = st.Marital.ToString();
            cmbNationality.Value  = st.Nationality.ToString();
            cmbNationality.Text   = st.Nationality.ToString();
            cmbReligion.Value     = st.Religion.ToString();
            cmbReligion.Text      = st.Religion.ToString();
            cmbTitle.Value        = st.Title.ToString();
            cmbTitle.Text         = st.Title.ToString();
            dtAdmission.Date      = st.Admissiondate.Date;
            Session["studUserID"] = st.UserId;
            lblFirstname.Text     = st.FNames;
            lblLastname.Text      = st.SName;

            if (File.Exists(Server.MapPath(UPLOAD_DIR + "img_" + Session["studUserID"].ToString() + ".jpg")))
            {
                imgMember.ImageUrl = UPLOAD_DIR + "img_" + Session["studUserID"].ToString() + ".jpg";
            }
            else
            {
                imgMember.ImageUrl = "~/images/default-person.jpg";
            }

            divMemberPic.Visible   = true;
            spbtnChangePic.Visible = true;
            UpdatePanelProfile.Update();
            upStudent.Update();
        }
        public MainWindow()
        {
            InitializeComponent();

            Student student = new Student();
            student.FirstName = "Arpad";
            student.LastName = "Ketestely";
            student.Address = "Aurel Vlaicu 45";
            student.CNP = "1930702080011";

            IStudentService service = new StudentService();
            //service.AddStudent(student);

            Console.WriteLine(service.GetStudentById(1).FirstName);

            IList<Student> students = service.GetListOfStudents();
            foreach(var s in students)
                Console.WriteLine(s.FirstName + " " + s.LastName);
        }
        public void addStudent()
        {
            try
            {
                Student student = new Student();
                setValue(student, context);

                HttpPostedFile hpf = context.Request.Files["headImgFile"];
                if (hpf != null)
                {
                    string serverPath = "/uploadFile/headImg/" + System.DateTime.Now.Ticks + "." + hpf.FileName.Split('.')[1];
                    string savePath = context.Server.MapPath(serverPath);//路径,相对于服务器当前的路径
                    hpf.SaveAs(savePath);//保存
                    student.HeadImage = serverPath;
                }
                string FacultyID = context.Request.Form.Get("Faculty");
                DepartmentService ds = new DepartmentService();
                string professionID = context.Request.Form.Get("Profession");
                if (!string.IsNullOrEmpty(professionID))
                {
                    Profession profession = ds.getProfessionByID(professionID);
                    if (profession != null)
                        student.Profession = profession;
                }

                string ClassGradeID = context.Request.Form.Get("ClassGrade");
                if (!string.IsNullOrEmpty(ClassGradeID))
                {
                    ClassGrade classGrade = ds.getClassGradeByID(ClassGradeID);
                    if (classGrade != null)
                        student.ClassGrade = classGrade;
                }
                StudentService s = new StudentService();
                student.Password = student.Sn;
                s.save(student);

                context.Response.Write("1");
            }
            catch (Exception e)
            {
                context.Response.Write("0");
            }
        }
        public void ThrowArgumentException_WhenInvokedWithInvalidEmptyStudentIdParameter()
        {
            //Arrange
            var studentMock        = new Mock <IRepository <Student> >();
            var coursesMock        = new Mock <IRepository <Course> >();
            var studentCoursesMock = new Mock <IRepository <StudentCourse> >();
            var mapperMock         = new Mock <IMappingProvider>();
            var saverMock          = new Mock <ISaver>();

            var studentService = new StudentService(
                studentMock.Object,
                coursesMock.Object,
                studentCoursesMock.Object,
                mapperMock.Object,
                saverMock.Object);

            //Act && Assert
            Assert.ThrowsExceptionAsync <ArgumentException>(() => studentService.GetAllRegisteredCourses(string.Empty));
        }
 protected void LoginBtn_Click(object sender, EventArgs e)
 {
     if (Sn.Value == "") {
         ErrorInfos.InnerHtml = "用户名不能为空";
         return;
     }
     else if (Password.Value == "") {
         ErrorInfos.InnerHtml = "密码不能为空";
         return;
     }
     StudentService ss = new StudentService();
     Student s = ss.login(Sn.Value, Password.Value);
     if (s == null)
     {
        ErrorInfos.InnerHtml = "用户名或密码错误";
     }
     else {
         Session["user"] = s;
         Response.Redirect("index.aspx");
     }
 }
 public StudentsController(StudentRepository studentRepository, StudentService studentService)
 {
     this.studentRepository = studentRepository;
     this.studentService = studentService;
 }
 //
 // GET: /Registration/
 public ActionResult Index()
 {
     IEnumerable<RegistrationStudent> students = new StudentService().GetAll();
     return View(students);
 }
 public void delStudent()
 {
     try
     {
         string Id = context.Request.QueryString["Id"];
         StudentService service = new StudentService();
         service.del(service.get(typeof(Student), Id));
         context.Response.Write("1");
     }
     catch (Exception e)
     {
         context.Response.Write("0");
     }
 }
 public void updatePassword()
 {
     try {
         string Sn = context.Request.Form.Get("Sn");
         string Password = context.Request.Form.Get("Password");
         StudentService ss = new StudentService();
         ss.updatePassword(Sn, Password);
         context.Response.Write("1");
     }
     catch (Exception e) {
         context.Response.Write("0");
     }
 }
        public void updateStudent()
        {
            try
            {
                Student student = new Student();
                setValue(student, context);

                HttpPostedFile hpf = context.Request.Files["headImgFile"];
                if (hpf != null) {
                    string savepath = context.Server.MapPath("/uploadFile/headImg/" + student.Id + "." + hpf.GetType());//路径,相对于服务器当前的路径
                    hpf.SaveAs(savepath);//保存
                    student.HeadImage = savepath;
                }

                DepartmentService ds = new DepartmentService();
                string professionID = context.Request.Form.Get("Profession");
                if (!string.IsNullOrEmpty(professionID)) {
                    Profession profession = ds.getProfessionByID(professionID);
                    if (profession != null)
                        student.Profession = profession;
                }

                string ClassGradeID = context.Request.Form.Get("ClassGrade");
                if (!string.IsNullOrEmpty(ClassGradeID)) {
                    ClassGrade classGrade = ds.getClassGradeByID(ClassGradeID);
                    if (classGrade != null)
                        student.ClassGrade = classGrade;
                }

                StudentService s = new StudentService();
                s.save(student);
                context.Response.Write("1");
            }
            catch (Exception e)
            {
                context.Response.Write("0");
            }
        }
 public static async Task<IEnumerable<StudentAcademicRecord>> GetAllStudentsAcademicRecords(StudentService ss)
 {
     var records = await ss.GetAllStudentsAcademicRecords();
     return records;
 }
        public void getStudents()
        {
            try
            {
                StudentService service = new StudentService();
                Student student = new Student();
                setValue(student, context);

                string ProfessionID = context.Request.Form.Get("FacultyID");
                string FacultyID = context.Request.Form.Get("ProfessionID");

                IList<Profession> professionList = new List<Profession>();
                DepartmentService ds = new DepartmentService();
                if (!string.IsNullOrEmpty(ProfessionID)) {
                   Profession profession = ds.getProfessionByID(ProfessionID);
                   if (profession != null) professionList.Add(profession);
                }
                else if (!string.IsNullOrEmpty(FacultyID)) {
                    Faculty faculty = ds.getFacultyByID(FacultyID);
                    if (faculty != null && faculty.professionList != null)
                        foreach (Profession p in faculty.professionList)
                            professionList.Add(p);
                }

                student.ProfessionList = professionList;
                int rows = Convert.ToInt32(context.Request.Form["rows"]);
                int page = Convert.ToInt32(context.Request.Form["page"]);
                object[] data = service.getStudentList(student, rows, page);
                Hashtable ht = new Hashtable();
                ht.Add("total", data[0]);
                ht.Add("rows", data[1]);
                String json = JsonConvert.SerializeObject(ht);
                context.Response.Write(json);
            }
            catch (Exception e)
            {

            }
        }
        public async Task<ActionResult> Group()
        {
            var cs = new CohortService(Session["access_token"].ToString());
            var ss = new StudentService(Session["access_token"].ToString());

            var co = GetCohorts();
            var st = GetStudents();

            await Task.WhenAll(co, st);

            var cohorts = Task.WhenAll(from c in co.Result select CohortHelper.GetCohortDisplayObject(cs, c));
            var students = Task.WhenAll(from s in st.Result select StudentHelper.GetStudentDisplayObject(ss, s));

            await Task.WhenAll(cohorts, students);

            var data = new GroupingDisplayObject();
            data.cohorts = cohorts.Result;
            data.students = students.Result;
            data.filters = FilterHelper.InitializeFilters();

            return View(data);
        }
        public async Task<IEnumerable<Student>> GetStudents()
        {
            var s = new StudentService(Session["access_token"].ToString());
            var students = await s.GetAll();

            return students;
        }
Beispiel #49
0
        private void ShowStudentDataFromWebService(string studentId)
        {
            // start web service
            StudentService service = new StudentService();
            Student student = service.GetStudent(studentId);

            GridViewStudentRecord.DataSource = student.Subjects;
            GridViewStudentRecord.DataBind();
        }
        /// <summary>
        /// This button handler generates a new instance of REGISTRATION_STUDENT and initializes
        /// the attributes with data from the "PRIJAVA_ZA_KONKURS.ASPX" page. If the files were choosen,
        /// they would be saved on the server as normal documents and been later in STUDENT_SERVICE
        /// stored to the database. At the end the user would be redirected to see details about
        /// the information which he saved to the database
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void _btnWriteNewStudent_Click(object sender, EventArgs e)
        {
            RegistrationStudent student = new RegistrationStudent();

            student.personalNumber = Int32.Parse(this._txtPersonalNumber.Text);

            var studentCheck = new StudentService().GetStudentByPersonalNo(student.personalNumber);

            if (studentCheck.name != null)
            {
                Response.Write("Vec postoji student sa istim JMBG");
            }
            else
            {
                student.name = this._txtName.Text;
                student.surname = this._txtSurname.Text;
                if (this._rBtnMale.Checked)
                    student.gender = EGender.male;

                else
                    student.gender = EGender.female;

                student.email = this._txtEMail.Text;
                student.phoneNumber = Int32.Parse(this._txtPhoneNumber.Text);

                student.faculty = this._txtFacultyName.Text;
                student.enrollYear = Int32.Parse(this._txtEnrollYear.Text);
                student.studyYear = Int32.Parse(this._txtStudyYear.Text);
                student.indexNumber = Int32.Parse(this._txtIndexNumber.Text);

                switch (this._dropDownDormName.SelectedIndex)
                {
                    case 0:
                        student.dorm = EDorm.pavilion1;
                        break;

                    case 1:
                        student.dorm = EDorm.pavilion2;
                        break;

                    case 2:
                        student.dorm = EDorm.pavilion3;
                        break;

                    default:
                        student.dorm = EDorm.pavilion4;
                        break;
                }

                if (this._fileUploadIncomingDoc.HasFile)
                {
                    student.incomingDocumentName = Server.MapPath("") + "\\TemporaryData";
                    student.incomingDocumentName += "\\";
                    student.incomingDocumentName += this._fileUploadIncomingDoc.PostedFile.FileName;
                    this._fileUploadIncomingDoc.PostedFile.SaveAs(student.incomingDocumentName);
                }

                if (this._fileUploadFacultyDoc.HasFile)
                {
                    student.facultyDocumentName = Server.MapPath("") + "\\TemporaryData";
                    student.facultyDocumentName += "\\";
                    student.facultyDocumentName += this._fileUploadFacultyDoc.PostedFile.FileName;
                    this._fileUploadFacultyDoc.PostedFile.SaveAs(student.facultyDocumentName);
                }

                new StudentService().AddNewStudent(student);

                File.Delete(student.incomingDocumentName);
                File.Delete(student.facultyDocumentName);

                student.incomingDocumentName = null;
                student.facultyDocumentName = null;

                Response.Redirect("Registration/Details/" + student.id.ToString());
            }
        }
 public BaseController()
 {
     _unitOfWork = new UnitOfWork(new SchoolContext());
     StudentService = new StudentService(_unitOfWork);
     LINQExamplesService = new LINQExamplesService(_unitOfWork);
 }
 public StudentsController()
 {
     Service = new StudentService();
 }
        public async Task<ActionResult> Group()
        {
            var accessToken = Session["access_token"];
            if (accessToken != null)
            {
                var cs = new CohortService(accessToken.ToString());
                var ss = new StudentService(accessToken.ToString());
                var ses = new SectionService(accessToken.ToString());

                var co = GetCohorts();
                var st = GetStudents();
                var se = GetSections();

                //Get the available data elements and colors
                var dataElements = GlobalHelper.InitializeDataElements();
                var colors = GlobalHelper.InitializeColors();

                await Task.WhenAll(co, st, se);

                var cohorts = Task.WhenAll(from c in co.Result select CohortHelper.GetCohortDisplayObject(cs, c));
                var students = Task.WhenAll(from s in st.Result select StudentHelper.GetStudentDisplayObject(ss, s));
                var sections = Task.WhenAll(from s in se.Result select SectionHelper.GetSectionDisplayObject(ses, s));

                await Task.WhenAll(cohorts, students, se);

                var filters = FilterHelper.InitializeFilters(sections.Result); //contruct filter values to filter students in the app
                await Task.WhenAll(dataElements, colors);

                var data = GetGroupingDisplayObject(dataElements, colors, filters, cohorts, students, sections);

                return Json(data, JsonRequestBehavior.AllowGet);
            }

            //session has expired, refresh page
            return View("Index");
        }
        public async Task<ActionResult> Student()
        {

            //var displayObj = new List<CohortDisplayObject>();
            var cs = new StudentService(Session["access_token"].ToString());
            //var c = new StudentsController();
            //var students = await c.Get(Session["access_token"].ToString());
            var st = await GetStudents();
            //var st = GetStudents();

            var displayObj = await Task.WhenAll(from s in st select StudentHelper.GetStudentDisplayObject(cs, s));
            //await Task.WhenAll(co, st);
            //var data = new Data { students = st, cohorts = co };
            //var cs = new CohortService(Session["access_token"].ToString());

            //var result = await Task.WhenAll(from c in co.Result select createMultipleAssociation(cs, c, st.Result));

            return View(displayObj);
        }
 public void getStudent()
 {
     string Id = context.Request.QueryString["Id"];
     StudentService service = new StudentService();
     Student student = (Student)service.get(typeof(Student), Id);
     String json = JsonConvert.SerializeObject(student);
     context.Response.Write(json);
 }
Beispiel #56
0
        private void SaveStudentDataToWebService()
        {
            // start web service
            StudentService service = new StudentService();
            Student newStudent = new Student { Id = TextBox_StudentId.Text, Email = TextBox_Email.Text, Name= TextBox_StudentName.Text };
            Student student = service.AddStudent(newStudent);

            if (student != null) Response.Write("Success");
            else Response.Write("fail");
        }
 private static async Task<IEnumerable<Assessment>> GetStudentAssessmentsByStudentId(StudentService cs, string studentId)
 {
     var result = await cs.GetStudentAssessmentsByStudentId(studentId);
     return result;            
 }
 public static void InitTestClass(TestContext context)
 {
     dataContext = TestDatabaseCreator.Create<UserDataInitializer>(ConnectionStringName);
     _service = new StudentService(dataContext);
 }
        private void initStudentResult()
        {
            try
            {
                string ExamPlanID = context.Request.Form.Get("ExamPlanID");
                PlanService planService = new PlanService();
                ExamPlan examPlan = planService.getExamPlanByID(ExamPlanID);

                IList<ExamPlan> examPlanList = new List<ExamPlan>();
                examPlanList.Add(examPlan);
                ExamResultService ers = new ExamResultService();
                object[] obj = ers.searchExamResult(examPlanList, int.MaxValue, 1);
                if (obj[1] != null) {
                    IList<ExamResult> examResultList = (IList<ExamResult>)obj[1];
                    foreach (ExamResult er in examResultList)
                    {
                      ers.del(er);
                    }
                }

                Student student = new Student();
                IList<Profession> professionList = new List<Profession>();
                professionList.Add(examPlan.Profession);
                student.ProfessionList = professionList;
                StudentService ss = new StudentService();
                object[] studentObjArr = ss.getStudentList(student, int.MaxValue, 1);

                if (studentObjArr[1] != null)
                {
                    IList<Student> studentList = (IList<Student>)studentObjArr[1];
                    foreach (Student s in studentList)
                    {
                        ExamResult examResult = new ExamResult();
                        examResult.ExamPlan = examPlan;
                        examResult.Student = s;
                        ers.save(examPlan);
                        IDictionary<string,string> map = new Dictionary<string,string>();
                        foreach (Coures c in examPlan.CouresSet)
                        {
                            map.Add(c.Name, "0");
                        }
                        examResult.CouresScoreMap = map;
                        ers.save(examResult);
                    }
                }
                context.Response.Write("1");
            }
            catch (Exception e)
            {
                context.Response.Write("0");
            }
        }