public StudentDTO Get(StudentDTO student) { _cmd = DataProvider.Conn.CreateCommand(); _cmd.CommandText = "SELECT * FROM Student where id = @id"; _cmd.Parameters.Add(new SQLiteParameter("@id", student.Id)); DataProvider.Conn.Open(); try { var reader = _cmd.ExecuteReader(); while (reader.Read()) { student.Id = reader.GetInt32(0); student.Name = reader.GetString(1); student.Avg = reader.GetFloat(2); student.Status = reader.GetBoolean(3); student.Code = reader.GetString(4); student.Birthday = reader.GetDateTime(5); student.Image = reader.GetString(5); } } catch { return null; } finally { DataProvider.Conn.Close(); } return student; }
public StudentViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher, StudentDTO student) : base(userInterop, controllerInterop, dispatcher) { groups = new List<GroupDTO>(); originalEntity = student; }
public void DeleteTest() { var target = new StudentDAO(); // TODO: Initialize to an appropriate value var student = new StudentDTO { Id = 1 }; // TODO: Initialize to an appropriate value var actual = target.Delete(student); Assert.AreEqual(false, actual.Status); }
public bool isAuthencation(StudentDTO user) { StudentDAO ud = new StudentDAO(); if (ud.CheckPassword(user) == true) return true; else return false; }
public StudentViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher) : base(userInterop, controllerInterop, dispatcher) { groups = new List<GroupDTO>(); originalEntity = new StudentDTO(); Model = new StudentModel(originalEntity as StudentDTO) { Role = UserRoles.Student }; this.Model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ModelPropertyChanged); }
public StudentDTO Delete(StudentDTO student) { _cmd = DataProvider.Conn.CreateCommand(); _cmd.CommandText = "UPDATE Student SET status = 0 WHERE id = @id"; _cmd.Parameters.Add(new SQLiteParameter("@id", student.Id)); DataProvider.Conn.Open(); try { _cmd.ExecuteNonQuery(); } catch { return null; } finally { DataProvider.Conn.Close(); } return student; }
// Update private void Button2Click(object sender, RoutedEventArgs e) { var selectedStudent = (StudentDTO) studentGrid.SelectedItems[0]; var student = new StudentDTO { Avg = float.Parse(tbAvg.Text), Birthday = DateTime.Parse(dpBirthday.Text), Code = tbCode.Text, Fullname = tbFullname.Text, Status = true, Id = selectedStudent.Id }; Proxy.UpdateStudent(student); }
private void btnDoneofAddUser_click(object sender, RoutedEventArgs e) { StudentDTO temp = new StudentDTO(); temp.Id = id_addstudent.Text; temp.Email = email_addstudent.Text; temp.DateofBith = birthofday_addstudent.Text; temp.Phone = phone_addstudent.Text; temp.Gender = gender_addstudent.Text; temp.Password = password_addstudent.Password.ToString(); temp.Name = fname_addstudent.Text; if (id_addstudent.Text == "" || email_addstudent.Text == "" || birthofday_addstudent.Text == "" || phone_addstudent.Text == "" || gender_addstudent.Text == "" || password_addstudent.Password.ToString() == "" || passwordconfirm_addstudent.Password.ToString() == "") { MessageBox.Show("You must fill out the infomation"); return; } if (password_addstudent.Password.ToString() != passwordconfirm_addstudent.Password.ToString()) { MessageBox.Show("Password and Confirm Password does not match"); return; } if (AcademicAffairsOfficeBUS.addNewStudent(temp) == false) { MessageBox.Show("Add student failed"); return; } else { MessageBox.Show("Add successfully"); } id_addstudent.Text = ""; email_addstudent.Text = ""; birthofday_addstudent.Text = ""; phone_addstudent.Text = ""; fname_addstudent.Text = ""; chooseYear.SelectedIndex = 0; gender_addstudent.Text = ""; password_addstudent.Clear(); passwordconfirm_addstudent.Clear(); }
public async Task AddStudent() { //Arrenge StudentDTO studentDTO = new StudentDTO() { Id = studentDTOs.Count() + 1, Name = "Leonid", Surname = "Rybitsky", Age = 12 }; studentDTOs.Add(studentDTO); //Act await studentService.Create(studentDTO); StudentDTO studentFound = await studentService.Get(studentDTO.Id); //Assert studentDTO.Should().BeEquivalentTo(studentFound); }
public StudentDTO GetStudentById(string id) { // Student student = db.StudentRepository.GetByID(id); // GenericRepository (GetByID(id)) pronalazi i Teacher-e (i sve User-e) ako unesemo njihov ID (zbog nasledjivanja) i onda zapucava, moramo nekako proveravati tip!! Student student = db.StudentRepository.Get(x => x.Id == id).FirstOrDefault(); if (student == null) { return(null); } StudentDTO studentDto = new StudentDTO(); studentDto = Utils.ConvertStudentToDto(student); return(studentDto); }
public Student CreateStudent(StudentDTO studenDTO) { try { var student = Mapper.Map <Student>(studenDTO); student.Id = Guid.NewGuid(); _context.Add(student); _context.SaveChanges(); return(student); } catch (Exception) { throw; } }
public async Task <IHttpActionResult> UpdateStudent([FromBody] StudentDTO StudentModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var updatedStudent = await StudentService.UpdateStudentAsync(StudentModel); if (updatedStudent != null) { return(Ok(updatedStudent)); } else { return(NotFound()); } }
public List <StudentDTO> getStudentBySchoolId(long schoolId) { using (MyDbContext ctx = new MyDbContext()) { BaseDAL <Student> bs = new BaseDAL <Student>(ctx); var persons = bs.getAll().Include(s => s.Teachers).Where(s => s.schoolId == schoolId); List <StudentDTO> students = new List <StudentDTO>(); foreach (var person in persons) { StudentDTO studentdto = getDTO(person); students.Add(studentdto); //studentdto.teacherId = person.Teachers.; //studentdto.schoolId = person.schoolId; } return(students); } }
public static bool updateInfoStudent(StudentDTO student) { string sCommand = string.Format(@"Update student set Name = N'{0}', BirthDay = '{1}', Email = '{2}', Gender = '{3}', Phone = '{4}' where IDStudent = '{5}'", student.Name, student.DateofBith, student.Email, student.Gender, student.Phone, student.Id); con = DataProvider.OpenConnection(); try { bool result = DataProvider.ExecuteQuery(sCommand, con); DataProvider.CloseConnection(con); return(result); } catch (Exception ex) { DataProvider.CloseConnection(con); return(false); } }
public IActionResult UpdateStudent(int sid, [FromBody] StudentDTO studentDTO) { if (studentDTO == null || sid != studentDTO.SID) { return(BadRequest(ModelState)); } var studentObj = _mapper.Map <Student>(studentDTO); if (!_student.UpdateStudent(studentObj)) { ModelState.AddModelError("", $"Something went wrong when saving the record{studentObj.Name}"); return(StatusCode(500, ModelState)); } return(NoContent()); }
public ActionResult Edit(StudentDTO studentRecord) { if (studentRecord == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(View(studentRecord)); //using (var db = new TutuorDbEntities()) //{ // Student_2 stud = db.Student_2.SingleOrDefault(s => s.Id == _id); // TableMapper<Student_2, StudentDTO> mapObject = new TableMapper<Student_2, StudentDTO>(); // StudentDTO student = mapObject.Translate(stud); // Console.WriteLine(student); // return View(student); //} }
// Listar DB public List <StudentDTO> ReadStudentsDB(int?id = null) { var studentsList = new List <StudentDTO>(); try { // Cria o comando IDbCommand selectCmd = connection.CreateCommand(); if (id == null) { selectCmd.CommandText = "SELECT * FROM Students"; } else { selectCmd.CommandText = $"SELECT * FROM Students WHERE Id = {id}"; } // Executa o comando IDataReader result = selectCmd.ExecuteReader(); while (result.Read()) { var std = new StudentDTO { Id = Convert.ToInt32(result["Id"]), Name = Convert.ToString(result["Name"]), LastName = Convert.ToString(result["LastName"]), Phone = Convert.ToString(result["Phone"]), Registry = Convert.ToInt32(result["Registry"]), }; studentsList.Add(std); } return(studentsList); } catch (Exception ex) { throw new Exception(ex.Message); } finally { // Fecha a conexao connection.Close(); } }
public async Task CreateStudent_ReturnsSuccessNewStudentAndLocationHeader() { // Arrange var client = _factory.CreateClient(); var studentDto = new StudentDTO { Id = 3, Name = "John Doe", ClassId = 1 }; var content = new StringContent(JsonSerializer.Serialize(studentDto, new JsonSerializerOptions { IgnoreNullValues = true }), Encoding.UTF8, "application/json"); try { // Act var response = await client.PostAsync("/students", content); // Assert response.EnsureSuccessStatusCode(); Assert.NotNull(response.Content); var responseStudent = JsonSerializer.Deserialize <StudentDTO>( await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); Assert.NotNull(responseStudent); Assert.Equal(studentDto.Id, responseStudent.Id); Assert.Equal(studentDto.Name, responseStudent.Name); Assert.Equal(studentDto.ClassId, responseStudent.ClassId); Assert.Equal(1, responseStudent.TeacherId); Assert.Equal(1, responseStudent.SchoolId); Assert.Equal(new Uri(client.BaseAddress, "/students/3"), response.Headers.Location); } finally { // Clean-up (so it doesn't mess up other tests) var dbContext = _factory.Services.GetRequiredService <RosterDbContext>(); var student = await dbContext.Student.FindAsync(studentDto.Id); dbContext.Student.Remove(student); await dbContext.SaveChangesAsync(); } }
public static StudentDTO GetStudentByStuAndCouId(int Id, int CouId) { String sqlQuery = String.Format("Select * from Student where StuId={0}", Id); using (DBHelper helper = new DBHelper()) { var reader = helper.ExecuteReader(sqlQuery); StudentDTO dto = null; if (reader.Read()) { dto = FillStudentDTO(reader); AttendanceDTO attendance = AttendanceDAO.GetAttendanceByStuIdAndCouId(Id, CouId); dto.StuAttendance = attendance; } return(dto); } }
public IHttpActionResult Edit([FromBody] StudentDTO student) { try { var s = DB.Students.Where(r => r.Id == student.Id).FirstOrDefault(); s.Fname = student.Fname; s.Lname = student.Lname; s.Email = student.Email; s.Age = student.Age; DB.SaveChanges(); return(Ok(true)); } catch (Exception e) { return(Ok(new { StatusCode = 200, e })); } }
// PUT: api/Students/5 //[ResponseType(typeof(void))] public IHttpActionResult PutStudent(int id, StudentDTO student) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != student.Id) { return(BadRequest()); } _service.Update(student); return(StatusCode(HttpStatusCode.OK)); }
public override void Remove(object obj) { StudentDTO student = (StudentDTO)obj; try { using (var db = new stageobxdatabaseEntities()) { db.Students.Remove(db.Students.First(stud => stud.StudentId == student.Id)); db.SaveChanges(); } } catch (Exception e) { throw new Exception(e.Message); } }
public IActionResult GetStudentDetail(int id) { try { StudentDTO student = _studentService.GetStudentDetail(id); if (student == null) { return(NotFound("The Student record couldn't be found.")); } return(Ok(student)); } catch (Exception ex) { _exceptionLogger.LogError(ex.Message); return(StatusCode(500, "Intrenal Server Error.")); } }
private async Task <ScoringAssessmentDTO> GetAssessmentScoringsByStudent(StudentDTO student, string assessmentCategoryDescriptor = null) { var ods = await _odsApiClientProvider.NewResourcesClient(); var studentAssessments = await ods.Get <IList <StudentAssessment> >("studentAssessments", new Dictionary <string, string> { { "studentUniqueId", student.StudentUniqueId }, }); var associationDTO = new ScoringAssessmentDTO() { Student = student, Associations = new List <StudentAssessmentAssociationDTO>(), }; foreach (var studentAssessment in studentAssessments) { Assessment assessment; try { assessment = await _assessments.GetByIdentifier(studentAssessment.AssessmentReference.Identifier); } catch (Exception ex) { // Prevent loop from ending continue; } if (!string.IsNullOrWhiteSpace(assessmentCategoryDescriptor)) { if (assessment.CategoryDescriptor != assessmentCategoryDescriptor) { continue; } } associationDTO.Associations = associationDTO.Associations.Append(new StudentAssessmentAssociationDTO { Assessment = assessment, AssociationModel = studentAssessment, }); } return(associationDTO); }
public int SaveStudentToDB() { var newStudent = new StudentDTO { StudentID = Guid.NewGuid(), FirstName = firstNameTxt.Text.Trim(), LastName = lastNameTxt.Text.Trim(), Email = emailTxt.Text.Trim(), Nic = nicTxt.Text.Trim(), UserName = userNameTxt.Text.Trim(), Password = passwordTxt.Text }; var studentEntity = AutoMapper.Mapper.Map <Student>(newStudent); return(studentService.SaveStudent(studentEntity)); }
// Thêm học sinh mới public static bool AddNewStudent(StudentDTO student) { string sCommand = string.Format(@"Insert into Student(IDStudent,Name,Gender,Email,Phone,BirthDay,PassWord, isActive) values ('{0}',N'{1}','{2}','{3}','{4}','{5}','{6}','{7}')", student.Id, student.Name, student.Gender, student.Email, student.Phone, student.DateofBith, student.Password, student.IsActive); con = DataProvider.OpenConnection(); try { bool result = DataProvider.ExecuteQuery(sCommand, con); DataProvider.CloseConnection(con); return(result); } catch (Exception ex) { DataProvider.CloseConnection(con); return(false); } }
/// <summary> /// Creates a new student /// </summary> public void CreateStudent(StudentDTO newstudentDTO) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["UWHousing"].ConnectionString)) //placeholder { connection.Open(); string sql = @"Insert INTO Student (StudentID, Firstname, Lastname, Buildingname, Roomnumber) Values (@StudentID, @Firstname, @Lastname, @Buildingname, @Roomnumber)"; connection.Execute(sql, newstudentDTO); } }
public async Task <StudentDTO> CreateEntity(StudentDTO data) { var entities = await _baseRepository.QueryAsync <Student>(); foreach (var element in entities) { if (element.Username == data.Username) { throw new Exception("Student with username: "******" exists."); } } var entity = _mapper.Map <Student>(data); var created = await _baseRepository.CreateAsync(entity); data = _mapper.Map <StudentDTO>(created); return(data); }
public async Task <ResultMessage <bool> > FinishRegistrationProcess(RegisterUserDTO registerData) { try { using (IDbContextTransaction transaction = await _context.Database.BeginTransactionAsync()) { StudentDTO student = Mapping.Mapper.Map <StudentDTO>(registerData); ResultMessage <RegistrationDTO> res = await _registrationService.GetSingleOrDefault( reg => reg.RegistrationCode == registerData.RegistrationCode); RegistrationDTO registration = res.Result; Mapping.Mapper.Map(registration, student); byte[] salt = Security.GenerateRandomBytes(Constants.SALT_SIZE); string saltBase64 = Convert.ToBase64String(salt); string hash = Security.CreateHash(registerData.Password, salt, Constants.PASSWORD_HASH_SIZE); student.PasswordHash = hash; student.Salt = saltBase64; student.Rating = 0; registration.Used = true; ResultMessage <RegistrationDTO> registrationProcessResult = await _registrationService.Update(registration); if (!registrationProcessResult.IsSuccess) { return(new ResultMessage <bool>(registrationProcessResult.Status, "Registration couldn't been updated." + registrationProcessResult.Message)); } ResultMessage <StudentDTO> dtoStudent = await _studentService.Add(student); if (!dtoStudent.IsSuccess) { return(new ResultMessage <bool>(dtoStudent.Status, "Registration couldn't been updated." + dtoStudent.Message)); } transaction.Commit(); return(new ResultMessage <bool>(true, OperationStatus.Success)); } } catch (DbUpdateException ex) { return(new ResultMessage <bool>(false, _errorHandler.Handle(ex))); } }
public async Task <IHttpActionResult> RegisterStudent(StudentRegisterBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); var newUser = UserManager.FindByEmail(model.Email); UserManager.AddToRoles(newUser.Id, new string[] { "Student" }); int StdId = 0; if (result.Succeeded) { StudentDTO std = new StudentDTO() { St_Name = model.FirstName + " " + model.LastName, EnrolmentDate = DateTime.Now, St_Address1 = model.St_Address1, St_Address2 = model.St_Address2, St_PostCode = model.St_PostCode, St_Email = model.Email, St_Telephone = model.St_Telephone, UserId = user.Id, _ImageFileUrl = model._ImageFileUrl, StandardId = model.StandardId }; IStudentService stService = new StudentService(); StdId = await stService.AddStudentAsync(std); } else { return(GetErrorResult(result)); } return(Ok(StdId)); }
public async Task <IEnumerable <StudentDTO> > GetAllAsync() { using (MyDbContent cxt = new MyDbContent()) { List <StudentDTO> students = new List <StudentDTO>(); //foreach (var student in cxt.Students) //{ // StudentDTO dto = new StudentDTO() { Id = student.Id, Name = student.Name, Age = student.Age }; // students.Add(dto); //} await cxt.Students.ForEachAsync <Student>(student => { StudentDTO dto = new StudentDTO() { Id = student.Id, Name = student.Name, Age = student.Age }; students.Add(dto); }); return(students); } }
public void Update() { StudentDTO student = new StudentDTO { StudentId = 2, FirstName = "Medeni", LastName = "Baykal", StudentNumber = "15314287", MobilePhone = "05526229767", EmailAdress = "*****@*****.**", CreatedDate = DateTime.Now, RecordStatusId = 1 }; var result = service.Update(student); Assert.IsTrue(result); }
public StudentDTO Create(StudentDTO student) { _cmd = DataProvider.Conn.CreateCommand(); _cmd.CommandText = "INSERT INTO Student(name,avg,status,code,birthday,image) VALUES(@name,@avg,@status,@code,@birthday,@image)"; _cmd.Parameters.Add(new SQLiteParameter("@name", student.Name)); _cmd.Parameters.Add(new SQLiteParameter("@avg", student.Avg)); _cmd.Parameters.Add(new SQLiteParameter("@status", student.Status)); _cmd.Parameters.Add(new SQLiteParameter("@code", student.Code)); _cmd.Parameters.Add(new SQLiteParameter("@birthday", student.Birthday)); _cmd.Parameters.Add(new SQLiteParameter("@image", student.Image)); DataProvider.Conn.Open(); try { _cmd.ExecuteNonQuery(); } catch { return null; } finally { DataProvider.Conn.Close(); } return student; }
public IActionResult SendRequest([FromBody] RequestViewModel request) { var student = request.Student; var studentDto = new StudentDTO( student.FirstName, student.LastName, student.Patronymic, 193, student.Email, DateTime.Now); try { RequestService.CreateDiplomaRequest(studentDto, request.DaId, request.TeacherId, 193, request.Title); return(Json(new { Message = "Заявка отравлена" })); } catch (Exception ex) { return(Json(ex.InnerException == null ? new { Error = ex.ToString(), ErrorMessage = ex.Message } : new { Error = ex.InnerException.ToString(), ErrorMessage = ex.InnerException.Message })); } }
// // GET: /ViewBag/ public ActionResult Index() { StudentDTO student = new StudentDTO() { City = "Pune", Class = "MVC", Country = "India", Email = "*****@*****.**", EnrollYear = "2016", Name = "Niraj", StudentID = 1, }; ViewData["StudentDetails"] = student; var schoolName = TempData.Peek("SchoolName").ToString(); return(View()); }
public async Task <IActionResult> Create(StudentDTO studentDTO) { //var student = new Student { // LastName=studentDTO.LastName, // FirstMidName=studentDTO.FirstMidName, // EnrollmentDate =studentDTO.EnrollmentDate //}; if (ModelState.IsValid) { var student = _mapper.Map <Student>(studentDTO); student = await _studentService.Insert(student); var id = student.ID; return(RedirectToAction("Index")); } return(View(studentDTO)); }
public ActionResult Create(StudentViewModel studentViewModel) { if (ModelState.IsValid) { var student = new StudentDTO { FirstName = studentViewModel.FirstName, LastName = studentViewModel.LastName, Address = studentViewModel.Address, Phone = studentViewModel.Phone, DateOfBirth = studentViewModel.DateOfBirth, GroupId = _groupManager.GetAll().Where(t => t.NameOfGroup.Equals(studentViewModel.Group)).ToList().First().Id }; _studentManager.Create(student); return(RedirectToAction(nameof(Index))); } return(View()); }
public static bool updateInfoStudent(StudentDTO student) { string birthDay = student.DateofBith; if (!TeacherBUS.marchBirthDay(student.DateofBith)) { return(false); } if (!TeacherBUS.marchEmail(student.Email)) { return(false); } TeacherBUS.StandalizedBirthDayToDatabase(ref birthDay); student.DateofBith = birthDay; return(AcademicAffairsOfficeDAO.updateInfoStudent(student)); }
public void CreateTest() { Service1 target = new Service1(); // TODO: Initialize to an appropriate value // Create the web request var request = WebRequest.Create("http://localhost:3978/Service1/" + "students/create") as HttpWebRequest; var dto = new StudentDTO {Name = "nXqd", Avg = (float) 10.1, Code = "0812090"}; // Set type to POST if (request != null) { request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentType = "application/json"; } // Create a byte array of the data we want to send var byteData = Encoding.UTF8.GetBytes( "{\"Name\":\"" + dto.Name + "\"," + "\"Code\":\"" + dto.Code + "\"," + "\"Status\":\"" + dto.Status + "\"," + "\"Avg\":\"" + dto.Avg + "\"," + "\"Birthday\":\"" + dto.Birthday + "\",}" ); // Set the content length in the request headers request.ContentLength = byteData.Length; // Write data using (var postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } // Get response using (var response = request.GetResponse() as HttpWebResponse) { // Get the response stream var reader = new StreamReader(response.GetResponseStream()); } // Assert.AreEqual(expected, actual); }
private void Button1Click(object sender, RoutedEventArgs e) { // Ready to add new row if (_readyToAdd) { _readyToAdd = false; var student = new StudentDTO { Avg = float.Parse(tbAvg.Text), Birthday = DateTime.Parse(dpBirthday.Text), Code = tbCode.Text, Fullname = tbFullname.Text, Status = true, Id = Proxy.GetId() }; Proxy.CreateStudent(student); _dataSource.Add(student); } else { _readyToAdd = true; tbFullname.Text = "Your full name!"; tbCode.Text = "Your student code!"; tbAvg.Text = "Your avg mark !"; dpBirthday.Text = "Pick your birthday !"; } }
/// <summary> /// Adds a student to waiting list of specific course given by ID /// </summary> /// <param name="id">ID of the course</param> /// <param name="model">A model containing the SSN of the student</param> /// <returns>A personDTO of the student</returns> public StudentDTO AddStudentToWaitingList(int id, AddStudentViewModel model) { // Validate var courseEntity = _db.Courses.SingleOrDefault(x => x.ID == id); if (courseEntity == null) { throw new AppObjectNotFoundException(); } //verify that the person exists! var person = _db.Persons.SingleOrDefault(x => x.SSN == model.SSN); if (person == null) { throw new AppObjectNotFoundException(); } //check if student already in course var studentAlreadyInCourse = (from cs in _db.CourseStudents where cs.CourseID == id && person.ID == cs.PersonID select cs).SingleOrDefault(); if (studentAlreadyInCourse != null) { throw new DuplicateEntryException(); } //make sure person is not currently on the waiting list var onWaitingList = (from cwl in _db.CourseWaitingList where cwl.CourseID == id && person.ID == cwl.PersonID select cwl).SingleOrDefault(); if(onWaitingList != null) { throw new DuplicateEntryException(); } var waitingEntity = new CourseWaitingList { CourseID = id, PersonID = person.ID }; _db.CourseWaitingList.Add(waitingEntity); _db.SaveChanges(); var result = new StudentDTO { SSN = model.SSN, Name = person.Name }; return result; }
/// <summary> /// Adds a student to a given course /// </summary> /// <param name="id"></param> /// <param name="model"></param> /// <returns></returns> public StudentDTO AddStudentToCourse(int id, AddStudentViewModel model) { var course = _db.Courses.SingleOrDefault(x => x.ID == id); //if course doesn't exist an error will be thrown. Not possible to add student to non existing courses if (course == null) { throw new AppObjectNotFoundException(); } //verify that the person exists! var person = _db.Persons.SingleOrDefault(x => x.SSN == model.SSN); if(person == null) { throw new AppObjectNotFoundException(); } //count students in the course var countStudents = _db.CourseStudents.Count(x => x.CourseID == course.ID); //stop adding new students if course is full if(countStudents >= course.MaxStudents) { throw new MaxStudentException(); } //check if student already in course var studentAlreadyInCourse = (from cs in _db.CourseStudents where cs.CourseID == id && person.ID == cs.PersonID select cs).SingleOrDefault(); if (studentAlreadyInCourse != null) { throw new DuplicateEntryException(); } //check if person is on the waitinglist var isOnWaitList = (from cwl in _db.CourseWaitingList //join p in _db.Persons on cwl.PersonID equals p.ID where cwl.CourseID == id && person.ID == cwl.PersonID select cwl).SingleOrDefault(); //person is on the waitinglist if(isOnWaitList != null) { _db.CourseWaitingList.Remove(isOnWaitList); _db.SaveChanges(); } //Actually add the record var courseStudent = new CourseStudent { PersonID = person.ID, CourseID = course.ID }; _db.CourseStudents.Add(courseStudent); _db.SaveChanges(); //3.Figure out what to return. var returnValue = new StudentDTO { Name = person.Name, SSN = person.SSN }; return returnValue; }
public List<StudentDTO> GetAll() { var dtos = new List<StudentDTO>(); _cmd = DataProvider.Conn.CreateCommand(); _cmd.CommandText = "SELECT * FROM Student WHERE status = 1"; DataProvider.Conn.Open(); SQLiteDataReader reader = null; try { reader = _cmd.ExecuteReader(); while (reader.Read()) { var dto = new StudentDTO { Id = reader.GetInt32(0), Name = reader.GetString(1), Avg = reader.GetFloat(2), Status = reader.GetBoolean(3), Code = reader.GetString(4), Birthday = reader.GetDateTime(5), Image = reader.GetString(5), }; dtos.Add(dto); } } catch { return null; } finally { if (reader != null) reader.Close(); } DataProvider.Conn.Close(); return dtos; }
public StudentDTO Update(StudentDTO student) { _cmd = DataProvider.Conn.CreateCommand(); _cmd.CommandText = "UPDATE Student SET name=@name, [avg]=@avg,status=@status,code=@code,birthday=@birthday,image=@image WHERE id=@id"; _cmd.Parameters.Add(new SQLiteParameter("@id", student.Id)); _cmd.Parameters.Add(new SQLiteParameter("@name", student.Name)); _cmd.Parameters.Add(new SQLiteParameter("@avg", student.Avg)); _cmd.Parameters.Add(new SQLiteParameter("@status", student.Status)); _cmd.Parameters.Add(new SQLiteParameter("@code", student.Code)); _cmd.Parameters.Add(new SQLiteParameter("@birthday", student.Birthday)); _cmd.Parameters.Add(new SQLiteParameter("@image", student.Image)); DataProvider.Conn.Open(); try { _cmd.ExecuteNonQuery(); } catch { return null; } finally { DataProvider.Conn.Close(); } return student; }