private void odstrániťToolStripMenuItem_Click(object sender, EventArgs e) { try { var result = MessageBox.Show("Naozaj chcete odstrániť aktivitu ?", "Odstrániť aktivitu", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { using (var con = new StudentDBDataContext(conn_str)) { var stud = con.GetTable <Student>().Where(x => x.ID_stud_skupina == studentSkupina.Id && x.Id == (int)Student_Grid.CurrentRow.Cells[0].Value).FirstOrDefault(); var act = con.GetTable <Activity>().Where(x => x.IdStudent == stud.Id && x.Id == (int)Activity_Grid.CurrentRow.Cells[3].Value).FirstOrDefault(); var tasks = con.GetTable <Task>().Where(x => x.IdStudent == (int)Student_Grid.CurrentRow.Cells[0].Value && x.IdActivity == act.Id); con.Tasks.DeleteAllOnSubmit(tasks); con.SubmitChanges(); con.Activities.DeleteOnSubmit(act); con.SubmitChanges(); } } Activity_Grid.DataSource = null; GetActivities(); } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); } }
/// <summary> /// Vytvorenie aktivity, body za aktivitu /// </summary> private void PointsForActivity(int?id) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var actTempl = con.GetTable <ActivityTemplate>().Where(x => x.Id == id).FirstOrDefault(); Activity activity = new Activity() { ActivityName = actTempl.ActivityName, IdFirstRem = null, IdSecRem = null, MaxPoints = actTempl.MaxPoints, Deadline = DateTime.Now, EmailSendingActive = false, IdSkupina = studentSkupina.Id, IdUser = currentUser.Id, Hodnotene = true, SendFirst = false, SendSecond = false, IdStudent = (int)Student_Grid.CurrentRow.Cells[0].Value, Hodnotenie = actTempl.MaxPoints, Comment = string.Empty, SendMe = false, }; con.Activities.InsertOnSubmit(activity); con.SubmitChanges(); var tasks = con.GetTable <TaskTemplate>().Where(x => x.IdActivityTemplate == actTempl.Id); foreach (var tsk in tasks) { Task task = new Task() { IdActivity = activity.Id, TaskName = tsk.TaskName, Points = tsk.MaxPts, IdStudent = activity.IdStudent, Hodnotenie = tsk.MaxPts, Comment = string.Empty, }; con.Tasks.InsertOnSubmit(task); } con.SubmitChanges(); } GetActivities(); } catch (ArgumentNullException ex) { Logger logger = new Logger(); logger.LogError(ex); } }
private void CreateEmailTempBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var exists = con.GetTable <EmailTemplate>().Where(x => x.EmailTemplateName == NameOfTempTextBox.Text && x.IdUser == currentUser.Id); if (exists.Count().Equals(0)) { if (!string.IsNullOrEmpty(SubjectTextbox.Text) && !string.IsNullOrEmpty(ContentTextBox.Text) && !string.IsNullOrEmpty(NameOfTempTextBox.Text)) { var newTemp = new EmailTemplate() { EmailTemplateName = NameOfTempTextBox.Text, EmailSubject = SubjectTextbox.Text, EmailContent = ContentTextBox.Text, IdUser = currentUser.Id }; con.EmailTemplates.InsertOnSubmit(newTemp); con.SubmitChanges(); SaveAttachmentsToDB(newTemp); } else { MessageBox.Show("Subjekt alebo správa nie sú vyplnené, pred uložením je potrebné vyplniť tieto polia", "Prázdne polia"); return; } } else { var exisEmail = con.EmailTemplates.Where(x => x.IdUser == currentUser.Id && x.Id == (int)TempGridView.CurrentRow.Cells[2].Value); exisEmail.FirstOrDefault().EmailSubject = SubjectTextbox.Text; exisEmail.FirstOrDefault().EmailContent = ContentTextBox.Text; SaveAttachmentsToDB(exisEmail.FirstOrDefault()); con.SubmitChanges(); } GetEmailTemps(currentUser); AttachmentsGrid.ClearSelection(); } } catch (Exception ex) { Logger logger = new Logger(); logger.LogError(ex); } }
private bool CreateUser() { try { if (Validation()) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { User user = new User { Meno = NameBox.Text, Email = EmailBox.Text, Heslo = SHA512(FirstPssBox.Text) }; con.Users.InsertOnSubmit(user); con.SubmitChanges(); MessageBox.Show("Registrácia bola úspešná"); return(true); } } else { return(false); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } }
/// <summary> /// Odstranenie vsetkych taskov a nasledne samotnej activity /// </summary> private void RemoveActTempBtn_Click(object sender, EventArgs e) { try { if (AllActTempGrid.Rows.Count > 0 && MessageBox.Show("Naozaj chcete odstrániť šablónu?", "Odstrániť šablónu", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var selectedTaskTemp = con.TaskTemplates.Where(a => a.IdActivityTemplate == (int)AllActTempGrid.CurrentRow.Cells[2].Value); var selectedAct = con.ActivityTemplates.Where(a => a.Id == (int)AllActTempGrid.CurrentRow.Cells[2].Value); foreach (var x in selectedTaskTemp) { con.TaskTemplates.DeleteOnSubmit(x); } con.ActivityTemplates.DeleteOnSubmit(selectedAct.FirstOrDefault()); con.SubmitChanges(); } GetTableTemp(); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
private void CreateBtn_Click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(GroupNameBox.Text) && GroupNameBox.Text.Length > 3) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var existingGroups = con.GetTable <StudentSkupina>().Where(x => x.Nazov == GroupNameBox.Text && x.Id_User == currentUser.Id); if (existingGroups.Count() > 0) { MessageBox.Show("Skupina s týmto názvom už existuje, prosím zvoľte iný názov skupiny", "Upozornenie", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var newGroup = new StudentSkupina() { Id_User = currentUser.Id, Nazov = GroupNameBox.Text, Forma = (string)FormCombo.SelectedItem }; con.StudentSkupinas.InsertOnSubmit(newGroup); con.SubmitChanges(); } } else { MessageBox.Show("Názov skupiny musí obsahovať viac ako 3 znaky"); return; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Delete email template /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void materialFlatButton3_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { DialogResult response = MessageBox.Show("Naozaj chcete odstrániť šablónu ?", "Upozornenie", MessageBoxButtons.YesNo); if (response == DialogResult.Yes) { con.Attachments.DeleteAllOnSubmit(con.GetTable <Attachment>().Where(x => x.IdEmailTemplate == (int)TempGridView.CurrentRow.Cells[2].Value)); con.EmailTemplates.DeleteOnSubmit(con.GetTable <EmailTemplate>(). Where(x => x.IdUser == currentUser.Id && x.Id == (int)TempGridView.CurrentRow.Cells[2].Value).FirstOrDefault()); con.SubmitChanges(); } else { return; } } GetEmailTemps(currentUser); } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); return; } }
// Pri prvom zapnuti okna sa vytvori finalne hodnotenie pre kazdeho studenta // Aby bol mozny export finalneho hodnotenia private void CreateFinalGradeOnStart() { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var allStudents = con.GetTable <Student>().Where(x => x.ID_stud_skupina == group.Id); var allFinalGrades = con.GetTable <FinalGrade>().Where(x => x.IdSkupina == group.Id); bool isAdded = false; if (allStudents.Count() <= 0 || allStudents == null) { return; } foreach (var student in allStudents) { var exists = allFinalGrades.Where(x => x.IdSkupina == group.Id && x.IdStudent == student.Id); if (exists.Count() > 0) { continue; } FinalGrade finalGrade = new FinalGrade() { IdSkupina = group.Id, IdStudent = student.Id, ActivityLectPoints = 0, ActivitySemPoints = 0, GotPoints = 0, Grade = "Fx", MaxPts = 0, MissedLectures = 0, MissedSeminars = 0, }; con.FinalGrades.InsertOnSubmit(finalGrade); isAdded = true; } if (isAdded) { con.SubmitChanges(); } else { return; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); Logger newLog = new Logger(); newLog.LogError(ex); } }
private void GradeTaskBtnClick(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { string taskTab = string.Empty; taskTab = MaterialTabCOntrol.SelectedTab.Name; tasksDictionary.TryGetValue(taskTab, out int Id); Task task1 = con.Tasks.Where(x => x.IdActivity == currActivity.Id && x.Id == Id && x.IdStudent == currStud.Id).FirstOrDefault(); var textBox = MaterialTabCOntrol.SelectedTab.Controls.Find("GradeTextBox", false).FirstOrDefault(); if (textBox != null && !string.IsNullOrEmpty(textBox.Text)) { double.TryParse(textBox.Text, out double grade); if (grade <= task1.Points) { task1.Hodnotenie = grade; } else { MessageBox.Show("Hodnotenie nemôže byť väčšie ako maximum bodov. Pred pridaním hodnotenia opravte hodnotu"); return; } } else { task1.Hodnotenie = 0; return; } var commentBox = (RichTextBox)MaterialTabCOntrol.SelectedTab.Controls.Find("comment", false).FirstOrDefault(); if (!string.IsNullOrEmpty(commentBox.Text)) { task1.Comment = commentBox.Text + "\u00A0"; } else { task1.Comment = "\u00A0"; } con.SubmitChanges(); MaterialTabCOntrol.SelectedTab.Text = task1.TaskName + Graded(task1); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
private void GradeActivityBtnClick(object sender, EventArgs e) { try { if (this.MaterialTabCOntrol.SelectedTab.Name == currActivity.ActivityName) { var labl = (Label)MaterialTabCOntrol.SelectedTab.Controls.Find("StudentPtsLabel", false).FirstOrDefault(); var commentBox = (RichTextBox)MaterialTabCOntrol.SelectedTab.Controls.Find("comment", false).FirstOrDefault(); using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var act = con.GetTable <Task>().Where(x => x.IdActivity == currActivity.Id && x.IdStudent == currStud.Id); double gradeTotal = 0; foreach (var tsk in act) { gradeTotal += tsk.Hodnotenie; } var insert = con.Activities.Where(x => x.IdSkupina == currGroup.Id && x.Id == currActivity.Id && x.IdStudent == currStud.Id).FirstOrDefault(); if (gradeTotal <= insert.MaxPoints) { ///ERROR 280 Line insert.Hodnotene = true; insert.Hodnotenie = gradeTotal; if (!string.IsNullOrEmpty(commentBox.Text)) { insert.Comment = commentBox.Text; } else { insert.Comment = string.Empty; } insert.EmailSendingActive = false; insert.SendFirst = false; insert.SendSecond = false; insert.SendMe = false; } con.SubmitChanges(); MessageBox.Show("Aktivita ohodnotená"); } } else { return; } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
private void odstrániťToolStripMenuItem1_Click(object sender, EventArgs e) { try { var result = MessageBox.Show("Naozaj chcete odstrániť študenta?", "Odstrániť študenta", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { this.UseWaitCursor = true; using (var con = new StudentDBDataContext(conn_str)) { var studentId = (int)Student_Grid.CurrentRow.Cells[0].Value; var stud = con.GetTable <Student>().First(x => x.Id == studentId); var totalAttendance = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == studentId).FirstOrDefault(); con.TotalAttendances.DeleteOnSubmit(totalAttendance); con.SubmitChanges(); var attendance = con.GetTable <AttendanceStud>().Where(x => x.IDStudent == studentId); if (attendance.Count() > 0) { con.AttendanceStuds.DeleteAllOnSubmit(attendance); con.SubmitChanges(); } var tasks = con.GetTable <Task>().Where(x => x.IdStudent == studentId); if (tasks.Count() > 0) { con.Tasks.DeleteAllOnSubmit(tasks); con.SubmitChanges(); var activity = con.GetTable <Activity>().Where(x => x.IdStudent == studentId); con.Activities.DeleteAllOnSubmit(activity); con.SubmitChanges(); } var finalGrade = con.GetTable <FinalGrade>().Where(x => x.IdStudent == studentId); if (finalGrade.Count() > 0) { con.FinalGrades.DeleteAllOnSubmit(finalGrade); con.SubmitChanges(); } con.Students.DeleteOnSubmit(stud); con.SubmitChanges(); } this.UseWaitCursor = false; } GetTable(); } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); } }
private void ChangePassword(User user, string NewPassword) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var ChangePssUser = con.Users.FirstOrDefault(x => x.Id == user.Id); ChangePssUser.Heslo = SHA512(NewPassword); con.SubmitChanges(); FirstPssBox.Text = string.Empty; SecondPssBox.Text = string.Empty; OldPssBox.Text = string.Empty; NameBox.Text = string.Empty; EmailBox.Text = string.Empty; } }
private void AddManualAttendanceBtn_Click(object sender, EventArgs e) { try { if ((string)comboBox3.SelectedValue != string.Empty) { using (var con = new StudentDBDataContext(conn_str)) { var student = studentsManual.TryGetValue(comboBox3.Text, out int value); var std = con.GetTable <Student>().Where(x => x.Id == value).FirstOrDefault(); if (std == null) { MessageBox.Show("Nie je vybraný žiaden študent"); return; } var insert = new AttendanceStud { IDSkupina = this.StudentSkup.Id, Type = CheckType(), Date = GetDate(), IDStudent = value, IdGroup = std.ID_Kruzok, Comment = string.Empty }; var attend = con.GetTable <AttendanceStud>(); var AttList = from AttendanceStud in attend where insert.IDSkupina == AttendanceStud.IDSkupina && AttendanceStud.Date == insert.Date && AttendanceStud.Type == insert.Type && AttendanceStud.IDStudent == insert.IDStudent select new { AttendanceStud.Type, AttendanceStud.Date }; if (AttList.Count() == 0) { con.AttendanceStuds.InsertOnSubmit(insert); con.SubmitChanges(ConflictMode.FailOnFirstConflict); } Filter(); ResetLabels(); } } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show("Nastala chyba, viac informácii nájdete v logoch.", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//Finalne hodnotenie private void GradeBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { // Ak udaje niew su v pozadovanych formatoch tak sa nic nestane if (!Validator()) { return; } FinalGrade grade = con.FinalGrades.Where(x => x.IdSkupina == group.Id && x.IdStudent == (int)StudentGrid.CurrentRow.Cells[0].Value).FirstOrDefault(); float.TryParse(MaxPtsBox.Text, out float maxPoints); float.TryParse(SemPtsBox.Text, out float semPts); float.TryParse(LecPtsBox.Text, out float lecPts); int.TryParse(MissedLecBox.Text, out int missedLec); int.TryParse(MissedSemBox.Text, out int missedSem); float.TryParse(TotalPtsBox.Text, out float totalPts); grade.ActivitySemPoints = semPts; grade.ActivityLectPoints = lecPts; grade.MissedLectures = missedLec; grade.MissedSeminars = missedSem; grade.MaxPts = maxPoints; grade.GotPoints = totalPts; grade.Grade = FinalGradeBox.Text; con.SubmitChanges(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); Logger newLog = new Logger(); newLog.LogError(ex); } }
private void DeleteWholeGroupData(User currentUser, StudentSkupina currentGroup) { try { UseWaitCursor = true; using (var con = new StudentDBDataContext(conn_str)) { var students = con.GetTable <Student>().Where(x => x.ID_stud_skupina == currentGroup.Id); foreach (var student in students) { var totalAttendance = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == student.Id).FirstOrDefault(); con.TotalAttendances.DeleteOnSubmit(totalAttendance); con.SubmitChanges(); var attendance = con.GetTable <AttendanceStud>().Where(x => x.IDSkupina == group.Id); con.AttendanceStuds.DeleteAllOnSubmit(attendance); con.SubmitChanges(); var tasks = con.GetTable <Task>().Where(x => x.IdStudent == student.Id); con.Tasks.DeleteAllOnSubmit(tasks); con.SubmitChanges(); var activity = con.GetTable <Activity>().Where(x => x.IdStudent == student.Id); con.Activities.DeleteAllOnSubmit(activity); con.SubmitChanges(); var studentId = student.Id; var finalGrade = con.GetTable <FinalGrade>().Where(x => x.IdStudent == studentId); con.FinalGrades.DeleteAllOnSubmit(finalGrade); con.SubmitChanges(); con.Students.DeleteOnSubmit(student); con.SubmitChanges(); } } UseWaitCursor = false; } catch (Exception ex) { MessageBox.Show(ex.ToString()); Logger logger = new Logger(); logger.LogError(ex); } }
//private void materialFlatButton1_Click(object sender, EventArgs e) //{ // this.Close(); //} private void AddEmailTemplateAttachmentsBtn_Click(object sender, EventArgs e) { try { EmailAttachments emailAttachments = new EmailAttachments(); var attach = emailAttachments.BrowseForFile(); var notAddedList = new List <string>(); if (attach != (null, null)) { foreach (var files in attach.Item1.Zip(attach.Item2, (paths, names) => (paths, names))) { var type = emailAttachments.GetMIMEType(files.paths); if (type == null) { notAddedList.Add(files.names); continue; } Attachment attachment = new Attachment() { FilePath = files.paths, FileName = files.names, IdUser = currentUser.Id, }; if (editMode) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var att = attachment; att.IdEmailTemplate = (int)TempGridView.CurrentRow.Cells[2].Value; var emailTemp = con.GetTable <EmailTemplate>().First(x => x.Id == (int)TempGridView.CurrentRow.Cells[2].Value); if (!AttachmentExists(att, emailTemp)) { con.Attachments.InsertOnSubmit(att); con.SubmitChanges(); AttachmentsGrid.DataSource = null; AttachmentsGrid.DataSource = con.GetTable <Attachment>().Where(x => x.IdEmailTemplate == (int)TempGridView.CurrentRow.Cells[2].Value); AttachmentsGrid.Columns["FilePath"].Visible = false; AttachmentsGrid.Columns["IdUSer"].Visible = false; AttachmentsGrid.Columns["IdEmailTemplate"].Visible = false; AttachmentsGrid.Columns["Id"].Visible = false; AttachmentsGrid.Columns["EmailTemplate"].Visible = false; AttachmentsGrid.Columns["User"].Visible = false; if (notAddedList.Count >= 1) { string list = null; foreach (var x in notAddedList) { list += x + " "; } var msg = $"Súbor/y {list} nebol pridaný, lebo tento typ súboru nie je možné odoslať emailom. Pre informácie o tom, ktoré " + "súbory nie je možné odoslať otvorte BlockedExtensions.txt"; MessageBox.Show(msg); } } return; } } else if (!attachmentList.Contains(attachment)) { attachmentList.Add(attachment); } } if (attachmentList.Count >= 1) { AttachmentsGrid.DataSource = null; AttachmentsGrid.DataSource = attachmentList; AttachmentsGrid.Columns["FilePath"].Visible = false; AttachmentsGrid.Columns["IdUSer"].Visible = false; AttachmentsGrid.Columns["IdEmailTemplate"].Visible = false; AttachmentsGrid.Columns["Id"].Visible = false; AttachmentsGrid.Columns["EmailTemplate"].Visible = false; AttachmentsGrid.Columns["User"].Visible = false; } if (notAddedList.Count >= 1) { string list = null; foreach (var x in notAddedList) { list += x + " "; } var msg = $"Súbor/y {list} nebol pridaný, lebo tento typ súboru nie je možné odoslať emailom. Pre informácie o tom, ktoré " + "súbory nie je možné odoslať otvorte BlockedExtensions.txt"; MessageBox.Show(msg); } } else { return; } AttachmentsGrid.ClearSelection(); }
public void SaveAttachmentsToDB(EmailTemplate template) { try { if (attachmentList != null) { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { if (editMode) { foreach (DataGridViewRow x in AttachmentsGrid.Rows) { var attachment = con.GetTable <Attachment>().Where(id => id.Id == (int)x.Cells[0].Value).FirstOrDefault(); Attachment atta = new Attachment() { FileName = attachment.FileName, FilePath = attachment.FilePath, IdEmailTemplate = template.Id, IdUser = currentUser.Id }; if (!AttachmentExists(atta, template)) { con.Attachments.InsertOnSubmit(atta); } } } else { foreach (var path in attachmentList) { Attachment attachment = new Attachment() { IdEmailTemplate = template.Id, IdUser = currentUser.Id, FileName = path.FileName, FilePath = path.FilePath, }; if (!AttachmentExists(attachment, template)) { con.Attachments.InsertOnSubmit(attachment); } else { continue; } } } con.SubmitChanges(); AttachmentsGrid.DataSource = con.GetTable <Attachment>().Where(x => x.IdEmailTemplate == template.Id && x.IdUser == currentUser.Id); } } else { return; } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
private void Remove_Button_Click(object sender, EventArgs e) { if (Skupiny_Grid.Rows.Count <= 0) { MessageBox.Show("Nie je vytvorená žiadna skupina"); return; } if (MessageBox.Show("Naozaj chcete odstrániť skupinu, so všetkými údajmi, ktoré obsahuje ?", "Odstrániť skupinu", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { Selected = (StudentSkupina)Skupiny_Grid.CurrentRow.DataBoundItem; StudentDBDataContext con = new StudentDBDataContext(conn_str); var students = con.GetTable <Student>().Where(x => x.ID_stud_skupina == Selected.Id); if (students.Count() > 0) { var totalAttendance = con.GetTable <TotalAttendance>().Where(x => x.Student.ID_stud_skupina == Selected.Id); if (totalAttendance.Count() > 0) { con.TotalAttendances.DeleteAllOnSubmit(totalAttendance); con.SubmitChanges(); } var attendance = con.GetTable <AttendanceStud>().Where(x => x.IDSkupina == Selected.Id); if (attendance.Count() > 0) { con.AttendanceStuds.DeleteAllOnSubmit(attendance); con.SubmitChanges(); } var tasks = con.GetTable <Task>().Where(x => x.Student.ID_stud_skupina == Selected.Id); if (tasks.Count() > 0) { con.Tasks.DeleteAllOnSubmit(tasks); con.SubmitChanges(); } var activity = con.GetTable <Activity>().Where(x => x.IdSkupina == Selected.Id); if (activity.Count() > 0) { con.Activities.DeleteAllOnSubmit(activity); con.SubmitChanges(); } var finalGrade = con.GetTable <FinalGrade>().Where(x => x.IdSkupina == Selected.Id); if (finalGrade.Count() > 0) { con.FinalGrades.DeleteAllOnSubmit(finalGrade); con.SubmitChanges(); } con.Students.DeleteAllOnSubmit(students); con.SubmitChanges(); } var group = con.GetTable <StudentSkupina>().First(x => x.Id == Selected.Id); con.StudentSkupinas.DeleteOnSubmit(group); con.SubmitChanges(); UserGroups(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
//Ulozenie alebo vytvorenie studenta private void SaveBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { if (AddStudRadio.Checked) { int.TryParse(GradeBox.Text, out int rocnik); Student newStudent = new Student() { Meno = NameBox.Text, Priezvisko = SurnameBox.Text, Email = EmailBox.Text, Email_UCM = EmailUcmBox.Text, ISIC = IsicBox.Text, ID_stud_skupina = skup.Id, Stud_program = skup.Nazov, Forma = skup.Forma, Rocnik = rocnik }; if (GroupCombo.SelectedItem != null && GroupAttCombo.SelectedItem != null) { newStudent.IdGroupForAttendance = (string)GroupAttCombo.SelectedItem; newStudent.ID_Kruzok = (string)GroupCombo.SelectedItem; } else if (!string.IsNullOrEmpty(GroupCombo.Text)) { newStudent.IdGroupForAttendance = GroupCombo.Text; newStudent.ID_Kruzok = GroupCombo.Text; } else { MessageBox.Show("Krúžok musí byť vyplnený, ak nemáte žiadne možnosti, tak napíšte manuálne"); return; } if (StudentBoxesValidator() && IsicValidator()) { con.Students.InsertOnSubmit(newStudent); con.SubmitChanges(); MessageBox.Show("Študent bol úspešne pridaný/upravený"); this.Close(); } else { return; } } else { if ((string)StudentsCombo.SelectedValue != string.Empty && StudentBoxesValidator()) { var student = students.TryGetValue(StudentsCombo.Text, out int value); Student editStudent = con.GetTable <Student>().Where(x => x.Id == value && x.ID_stud_skupina == skup.Id).FirstOrDefault(); int.TryParse(GradeBox.Text, out int rocnik); editStudent.Meno = NameBox.Text; editStudent.Priezvisko = SurnameBox.Text; editStudent.Email = EmailBox.Text; editStudent.Email_UCM = EmailUcmBox.Text; editStudent.ISIC = IsicBox.Text; editStudent.ID_stud_skupina = skup.Id;/// change studprogram editStudent.Stud_program = editStudent.Stud_program; editStudent.IdGroupForAttendance = (string)GroupAttCombo.SelectedItem; editStudent.ID_Kruzok = (string)GroupCombo.SelectedItem; editStudent.Forma = skup.Forma; editStudent.Rocnik = rocnik; con.SubmitChanges(); MessageBox.Show("Študent bol úspešne pridaný/upravený"); } else { return; } } } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
private void CreateActBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var selectedActivity = (int)ActivityGridView.CurrentRow.Cells["Id"].Value; var actTempl = con.GetTable <ActivityTemplate>().Where(x => x.Id == selectedActivity && x.IdUser == currUser.Id).FirstOrDefault(); ///Whether, and what reminders should be send var first = false; var second = false; if (actTempl.FirstRem.HasValue) { first = true; } if (actTempl.SecondRem.HasValue) { second = true; } if (studentCombo.SelectedItem == null) { MessageBox.Show("Najprv musíte vybrať študenta", "Upozornenie", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } studentsId.TryGetValue((string)studentCombo.SelectedItem, out int id); Student student = con.GetTable <Student>().Where(x => x.ID_stud_skupina == skupina.Id && x.Id == id).FirstOrDefault(); List <EmailAddress> studentAddress = new List <EmailAddress>(); Activity activityForEmailSending = null; Activity activity = new Activity() { ActivityName = actTempl.ActivityName, IdFirstRem = actTempl.FirstRem, IdSecRem = actTempl.SecondRem, MaxPoints = actTempl.MaxPoints, Deadline = GetDate(), EmailSendingActive = IsSendingChecked(), IdSkupina = skupina.Id, IdUser = this.currUser.Id, Hodnotenie = 0, Hodnotene = false, SendFirst = first, SendSecond = second, IdStudent = student.Id, Comment = string.Empty, SendMe = SendMe(), }; studentAddress.Add(MailHelper.StringToEmailAddress(student.Email)); con.Activities.InsertOnSubmit(activity); con.SubmitChanges(); activityForEmailSending = activity; //GetTasks var tasks = con.GetTable <TaskTemplate>().Where(x => x.IdActivityTemplate == actTempl.Id); foreach (var tsk in tasks) { Task task = new Task() { IdActivity = activity.Id, TaskName = tsk.TaskName, Points = tsk.MaxPts, Hodnotenie = 0, IdStudent = student.Id, Comment = string.Empty }; con.Tasks.InsertOnSubmit(task); } con.SubmitChanges(); if (ActCreatedCheckBox.Checked == true && currUser.ApiKey != string.Empty) { var link = Interaction.InputBox("Ak si neželáte zaslať dodatočné informácie o úlohe, nechajte prázdne", "Dodatočná správa", "Viac informácií nájdete na: ", -1, -1); SendActivityCreated(studentAddress, activityForEmailSending, link); } else if (currUser.ApiKey == string.Empty && SendMeBox.Checked == true || SendingEmailCheck.Checked == true || ActCreatedCheckBox.Checked == true) { MessageBox.Show("ApiKey je prázdny, aktivita bude vytvorená ale žiaden email nebude odoslaný pokým nebude pridaný ApiKey"); } MessageBox.Show($"Aktivita {actTempl.ActivityName} bola úspešne vytvorená"); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); return; } }
private void save_email_Click(object sender, EventArgs e) { try { EmailSettings emailSettings = new EmailSettings() { ApiKey = textBox1.Text, EmailAddress = textBox2.Text }; StudentDBDataContext con = new StudentDBDataContext(conn_str); User user = con.Users.FirstOrDefault(x => x.Id == currentUser.Id); if (user.ApiKey != textBox1.Text) { user.ApiKey = textBox1.Text; } if (user.Email != textBox2.Text) { user.Email = textBox2.Text; } if (comboBox1.SelectedItem != null) { activityId.TryGetValue((string)comboBox1.SelectedItem, out int id); user.PointsForActSem = id; } if (comboBox2.SelectedItem != null) { activityId.TryGetValue((string)comboBox2.SelectedItem, out int id); user.PointsForActLec = id; } float.TryParse(ABox.Text, out float aGrade); float.TryParse(BBox.Text, out float bGrade); float.TryParse(CBox.Text, out float cGrade); float.TryParse(DBox.Text, out float dGrade); float.TryParse(EBox.Text, out float eGrade); bool isProblem = false; if (aGrade < bGrade || aGrade < cGrade || aGrade < dGrade || aGrade < eGrade) { isProblem = true; } else if (bGrade > aGrade || bGrade < cGrade || bGrade < dGrade || bGrade < eGrade) { isProblem = true; } else if (cGrade > aGrade || cGrade > bGrade || cGrade < dGrade || cGrade < eGrade) { isProblem = true; } else if (dGrade > aGrade || dGrade > bGrade || dGrade > cGrade || dGrade < eGrade) { isProblem = true; } else if (eGrade > aGrade || eGrade > bGrade || eGrade > cGrade || eGrade > dGrade) { isProblem = true; } if (isProblem) { MessageBox.Show("Opravte chybu v stupnici", "Chyba v stupnici", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } user.AGrade = aGrade; user.BGrade = bGrade; user.CGrade = cGrade; user.DGrade = dGrade; user.EGrade = eGrade; user.Signature = materialMultiLineTextBox1.Text; con.SubmitChanges(); ABox.Text = user.AGrade.ToString(); BBox.Text = user.BGrade.ToString(); CBox.Text = user.CGrade.ToString(); DBox.Text = user.DGrade.ToString(); EBox.Text = user.EGrade.ToString(); materialMultiLineTextBox1.Text = user.Signature; textBox1.Text = ""; this.Close(); } catch (Exception ex) { Logger logger = new Logger(); logger.LogError(ex); } }
private void CreateActBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { if (ActivityGridView.Rows.Count <= 0) { MessageBox.Show("Nie je vytvorená žiadna šablóna aktivity", "Upozornenie", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //Ziskanie sablony aktivity var selectedActivity = (int)ActivityGridView.CurrentRow.Cells["Id"].Value; var actTempl = con.GetTable <ActivityTemplate>().Where(x => x.Id == selectedActivity && x.IdUser == currUser.Id).FirstOrDefault(); //Ziskavanie udajov o tom, ci, a ktore upozornenia maju byt odosielane var first = false; var second = false; if (actTempl.FirstRem.HasValue) { first = true; } if (actTempl.SecondRem.HasValue) { second = true; } IQueryable <Student> studs; if (groupCmbo.Text == "Všetky") { studs = con.GetTable <Student>().Where(x => x.ID_stud_skupina == studentSkup.Id); } else { studs = con.GetTable <Student>().Where(x => x.ID_stud_skupina == studentSkup.Id && x.ID_Kruzok == groupCmbo.Text); } if (studs.Count() <= 0) { MessageBox.Show("Skupina neobsahuje žiadnych študentov. Nie je možné vytvoriť aktivitu."); return; } List <EmailAddress> studentsAddresses = new List <EmailAddress>(); Activity activityForEmailSending = null; if (SendMe()) { if (apiKeyEmpty) { MessageBox.Show("ApiKey nemôže byť prázdny, aktivita bude vytvorená ale nebudú odoslané emaily", "ApiKey prázdny", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// Vytvorenie novej aktivity na zaklade sablony aktivity pre kazdeho studenta z studs foreach (var student in studs) { Activity activity = new Activity() { ActivityName = actTempl.ActivityName, IdFirstRem = actTempl.FirstRem, IdSecRem = actTempl.SecondRem, MaxPoints = actTempl.MaxPoints, Deadline = GetDate(), EmailSendingActive = IsSendingChecked(), IdSkupina = studentSkup.Id, IdUser = this.currUser.Id, Hodnotene = false, SendFirst = first, SendSecond = second, IdStudent = student.Id, Comment = string.Empty, SendMe = SendMe(), }; studentsAddresses.Add(MailHelper.StringToEmailAddress(student.Email)); con.Activities.InsertOnSubmit(activity); con.SubmitChanges(); activityForEmailSending = activity; //Vyrvorenie novych uloh ku kazdej aktivite z vybranej sablony var tasks = con.GetTable <TaskTemplate>().Where(x => x.IdActivityTemplate == actTempl.Id); foreach (var tsk in tasks) { Task task = new Task() { IdActivity = activity.Id, TaskName = tsk.TaskName, Points = tsk.MaxPts, IdStudent = student.Id, Comment = string.Empty }; con.Tasks.InsertOnSubmit(task); } con.SubmitChanges(); } MessageBox.Show($"Aktivita {actTempl.ActivityName} bola úspešne vytvorená"); if (ActCreatedCheckBox.Checked == true && !string.IsNullOrEmpty(currUser.ApiKey)) { var link = Interaction.InputBox("Ak si neželáte zaslať dodatočné informácie o úlohe, nechajte prázdne", "Dodatočná správa", "Viac informácií nájdete na: ", -1, -1); SendActivityCreated(studentsAddresses, activityForEmailSending, link); } } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); return; } }
private void CreateTemplateBtn_Click(object sender, EventArgs e) { try { using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var checkExisting = con.ActivityTemplates.Where(x => x.ActivityName == ActNameTxtBox.Text && x.IdUser == currUser.Id).Count(); ActivityTemplate ActTemp; bool editMode = false; if (checkExisting != 0) { // MessageBox.Show("Aktivita s týmto menom už existuje", "Chyba"); if (MessageBox.Show("Aktivita s týmto menom už existuje, chcete ju prepísať?", "Upozornenie", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { editMode = true; ActTemp = con.GetTable <ActivityTemplate>().Where(x => x.ActivityName == ActNameTxtBox.Text && x.IdUser == currUser.Id).FirstOrDefault(); var taskTemps = con.GetTable <TaskTemplate>().Where(x => x.IdActivityTemplate == ActTemp.Id); con.TaskTemplates.DeleteAllOnSubmit(taskTemps); con.SubmitChanges(); ActTemp.MaxPoints = Math.Round(float.Parse(MaxPtsLabel.Text), 2); ActTemp.ActivityName = ActNameTxtBox.Text; ActTemp.FirstRem = GetEmailTemps(comboBox1); ActTemp.SecondRem = GetEmailTemps(comboBox2); } else { return; } } else { ActTemp = new ActivityTemplate() { IdUser = currUser.Id, MaxPoints = Math.Round(float.Parse(MaxPtsLabel.Text), 2), ActivityName = ActNameTxtBox.Text, FirstRem = GetEmailTemps(comboBox1), SecondRem = GetEmailTemps(comboBox2), }; } if (ActTemp.MaxPoints != 0 && !string.IsNullOrWhiteSpace(ActTemp.MaxPoints.ToString()) && ActTemp.ActivityName != string.Empty) { if (editMode == false) { con.ActivityTemplates.InsertOnSubmit(ActTemp); } con.SubmitChanges(); } else { MessageBox.Show("Názov aktivity ani maximálny počet bodov nemôžu byť prázdne", "Chyba", MessageBoxButtons.OK); return; } /// Wrong numbers // Change ctrlpoints to ctrlptsfedit and anmes too foreach (var x in controlNamesForEdit.Zip(controlPointsForEdit, (names, points) => new { controlNamesForEdit = names, controlPointsForEdit = points })) { var toParse = x.controlPointsForEdit.Text; bool success = Single.TryParse(toParse, out float isParsable); if (!success) { MessageBox.Show("Niektoré pole nie je vyplnené", "Chyba", MessageBoxButtons.OK); var getAct = con.ActivityTemplates.Where(p => p.ActivityName == ActTemp.ActivityName); var deleteTask = con.TaskTemplates.Where(p => p.IdActivityTemplate == getAct.FirstOrDefault().Id); con.SubmitChanges(); if (deleteTask.Count() > 0) { foreach (var task in deleteTask) { con.TaskTemplates.DeleteOnSubmit(task); } } con.ActivityTemplates.DeleteOnSubmit(getAct.FirstOrDefault()); con.SubmitChanges(); return; } var TaskTemp = new TaskTemplate() { IdActivityTemplate = ActTemp.Id, MaxPts = Math.Round(isParsable, 2), TaskName = x.controlNamesForEdit.Text }; if (!string.IsNullOrWhiteSpace(TaskTemp.TaskName) && TaskTemp.MaxPts != 0 && TaskTemp?.MaxPts != null) { con.TaskTemplates.InsertOnSubmit(TaskTemp); } else { MessageBox.Show("Niektoré pole nie je vyplnené, alebo je zle vyplnené", "Chyba", MessageBoxButtons.OK); con.ActivityTemplates.DeleteOnSubmit(ActTemp); con.SubmitChanges(); return; } } con.SubmitChanges(); try { GetTableTemp(); ClearTasks(); } catch (Exception ex) { Logger logger = new Logger(); logger.LogError(ex); MessageBox.Show("Niekde nastala chyba.\n Skúste vytvoriť šablónu odznova"); } } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.ToString()); } }
public void Querys(StudentSkupina skupina) { try { group = skupina; var path = SelectPath(); if (path != "Cancel") { if ((File.GetAttributes(path) & FileAttributes.ReadOnly) > 0) { MessageBox.Show("Excel súbor je iba na čítanie"); return; } string constr = ExcelConnection(path); var excelCon = new OleDbConnection(constr); OleDbCommand Ecom = new OleDbCommand(query, excelCon); excelCon.Open(); DataSet excelDataSet = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter(query, excelCon); adapter.Fill(excelDataSet); excelCon.Close(); DataTable excelDataTable = excelDataSet.Tables[0]; for (int i = excelDataTable.Rows.Count - 1; i >= 0; i--) { if ((string)excelDataTable.Rows[i].ItemArray[5] == "A") { didntHappened = true; notAddedStuds.Add(i + 7); excelDataTable.Rows[i].Delete(); } } excelDataTable.AcceptChanges(); using (var con = new StudentDBDataContext(conn)) { for (int i = 0; i <= excelDataTable.Rows.Count - 1; i++) { var form = (string)excelDataTable.Rows[i].ItemArray[2]; if (form.ElementAt(form.Length - 3) == 'D' && !skupina.Forma.Contains("Denná") || form.ElementAt(form.Length - 3) == 'E' && !skupina.Forma.Contains("Externá")) { didntHappened = false; warnUser = true; continue; } string isic = null; if (!string.IsNullOrEmpty((string)excelDataTable.Rows[i].ItemArray[5])) { isic = excelDataTable.Rows[i].ItemArray[5].ToString().Remove(0, 5); } Student students = new Student { Meno = excelDataTable.Rows[i].ItemArray[0].ToString(), Priezvisko = excelDataTable.Rows[i].ItemArray[1].ToString(), Stud_program = excelDataTable.Rows[i].ItemArray[2].ToString(), ID_stud_skupina = skupina.Id, ID_Kruzok = excelDataTable.Rows[i].ItemArray[3].ToString(), IdGroupForAttendance = excelDataTable.Rows[i].ItemArray[3].ToString(), Email = excelDataTable.Rows[i].ItemArray[8].ToString(), Email_UCM = excelDataTable.Rows[i].ItemArray[7].ToString(), Rocnik = Convert.ToInt32(excelDataTable.Rows[i].ItemArray[6]), ISIC = isic, Forma = skupina.Forma }; if (!Exists(students)) { con.Students.InsertOnSubmit(students); con.SubmitChanges(); } else { continue; } } ; if (warnUser == true) { MessageBox.Show("Nie je možné pridávať študentov externej formy do skupiny určenej pre denných študentov.", "Upozornenie"); } if (notAddedStuds.Count >= 1 && didntHappened == true) { string warning = $"Študenti z tabuľky na pozíciach" + " " + string.Join(string.Empty, notAddedStuds.ToArray()) + " " + "neboli pridaný"; MessageBox.Show(warning); } } } else { return; } } catch (Exception ex) { if (ex.Message == "External table is not in the expected format.") { MessageBox.Show("Otvorte súbor manuálne a skúste znovu importovať. Ak sa chyba opakuje, je nutné súbor znovu uložiť ako .xlsx", "Chyba pri načítaní súboru", MessageBoxButtons.OK); return; } else { Logger logger = new Logger(); logger.LogError(ex); MessageBox.Show("Vybrali ste nesprávny súbor alebo štruktúra súboru je chybná", "Chyba pri načítaní súboru", MessageBoxButtons.OK); } } }
public async void AutomatedEmailSending(User user) { try { EmailClient eClient = new EmailClient(); if (string.IsNullOrEmpty(user.ApiKey)) { return; } SendGridClient client = new SendGridClient(eClient.SetEnvironmentVar(user)); using (StudentDBDataContext con = new StudentDBDataContext(conn_str)) { var activity = con.GetTable <Activity>().Where(chck => chck.IdUser == user.Id); /// Zoskupenie aktivit na zaklade mena aktivity a datumu odovzdania. aby sa mohli odosielat presne emaily, a iba tam, kde, /// bolo oznacene odosielanie emailovych upozorneni. var selectActivity = from act in activity where act.IdUser == user.Id && act.EmailSendingActive == true || act.SendMe == true group act by new { act.Deadline, act.ActivityName }; if (selectActivity == null || selectActivity.Count() <= 0) { return; } ///Prehladavanie kazdej skupiny foreach (var group in selectActivity) { // Prehladavanie jednotlivych aktivit v skupine, aby sme zistili ci ma student dostat upozornenie foreach (var act in group) { var days = ((act.Deadline.Subtract(DateTime.Now).TotalDays)); switch (act.EmailSendingActive) { /// Odosielanie prvych upozorneni ak do odovzdania zostavaju 3 alebo 2 dni case true when days <= 3 && days > 1 && act.SendFirst == true && act.Hodnotene == false: { firstReminderAddresses.Add(MailHelper.StringToEmailAddress(act.Student.Email)); Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault(); currAct.SendFirst = false; con.SubmitChanges(ConflictMode.ContinueOnConflict); break; } /// Zbieranie emailovych adries na odoslanie druhych upozorneni ak do odovzdania zostavaju 1 alebo 0 dni case true when days >= 0 && days < 1 && act.SendSecond == true && act.Hodnotene == false: { secondReminderAddresses.Add(MailHelper.StringToEmailAddress(act.Student.Email)); Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault(); currAct.SendSecond = false; currAct.EmailSendingActive = false; con.SubmitChanges(ConflictMode.ContinueOnConflict); break; } default: break; } if (act.SendMe == true && act.Hodnotene == false && days <= 0) { Activity currAct = con.GetTable <Activity>().Where(x => x.Id == act.Id).FirstOrDefault(); currAct.SendMe = false; con.SubmitChanges(); SendToMe = true; activitiesToGrade.Add(act.ActivityName); groupsToSend.Add(act.StudentSkupina.Nazov); } } /// Ziskanie emailu, ktory ma byt odoslany pre konkretnu aktivitu if (firstReminderAddresses.Count >= 1) { var emailToSend = group.Select(x => x.IdFirstRem); var template = con.GetTable <EmailTemplate>().Where(x => x.IdUser == user.Id && x.Id == emailToSend.FirstOrDefault()).FirstOrDefault(); await SendEmails(template, 3, firstReminderAddresses, user, group.Key.Deadline); } if (secondReminderAddresses.Count >= 1) { var emailToSend = group.Select(x => x.IdSecRem); var template = con.GetTable <EmailTemplate>().Where(x => x.IdUser == user.Id && x.Id == emailToSend.FirstOrDefault()).FirstOrDefault(); await SendEmails(template, 1, secondReminderAddresses, user, group.Key.Deadline); } } if (SendToMe == true) { string activities = string.Empty; string groups = string.Empty; foreach (var group in groupsToSend.Distinct()) { groups = groups + group + ", "; } foreach (var activ in activitiesToGrade.Distinct()) { activities += (activ + ", <br/>"); } string finalMsg = $"Uplynul dátum odovzdania pre následujúce aktivity: {activities}<br/>"; string subject = $"Aktivita pripravená na hodnotenie pre skupiny: {groups}"; var msg = MailHelper.CreateSingleEmail(MailHelper.StringToEmailAddress(user.Email), MailHelper.StringToEmailAddress(user.Email) , subject, finalMsg, finalMsg); var result = await client.SendEmailAsync(msg); SendToMe = false; } } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); return; } }
private void CreateButton_Click(object sender, EventArgs e) { try { using (var con = new StudentDBDataContext(conn_str)) { IQueryable <Student> student; Nullable <int> idStud; if (comboBox1.SelectedIndex == 0) { var studentId = con.GetTable <Student>().Where(x => x.Forma == StudentSkup.Forma && x.ID_stud_skupina == StudentSkup.Id); student = studentId; if (student.Count() <= 0) { MessageBox.Show("Nenašiel sa žiaden študent"); return; } } else { var studentId = con.GetTable <Student>().Where(x => x.Forma == StudentSkup.Forma && x.ID_stud_skupina == StudentSkup.Id && x.ID_Kruzok == (string)comboBox1.SelectedItem); student = studentId; if (student.Count() <= 0) { MessageBox.Show("Nenašiel sa žiaden študent"); return; } } foreach (var x in student) { var insert = new AttendanceStud { IDSkupina = this.StudentSkup.Id, Type = CheckType(), Date = GetDate(), IDStudent = x.Id, IdGroup = x.ID_Kruzok, Comment = string.Empty }; var attend = con.GetTable <AttendanceStud>(); var AttList = from AttendanceStud in attend where insert.IDSkupina == AttendanceStud.IDSkupina && AttendanceStud.Date == insert.Date && AttendanceStud.Type == insert.Type && AttendanceStud.IDStudent == insert.IDStudent select new { AttendanceStud.Type, AttendanceStud.Date }; if (AttList.Count() == 0) { con.AttendanceStuds.InsertOnSubmit(insert); con.SubmitChanges(ConflictMode.FailOnFirstConflict); } //GetAttendance(); Filter(); if (attGrid.Rows.Count > 0 && (int?)attGrid.CurrentRow.Cells[7].Value != null) { idStud = (int?)attGrid.CurrentRow.Cells[7].Value; if (idStud != null) { PresenceCounter(idStud.GetValueOrDefault()); } } } ResetLabels(); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show("Nastala chyba, viac informácii nájdete v logoch.", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Remove selected student's attendance /// </summary> private void RemoveBtn_Click(object sender, EventArgs e) { try { using (var con = new StudentDBDataContext(conn_str)) { var attend = con.GetTable <AttendanceStud>(); var stud = con.GetTable <Student>(); var selected = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IdAttendance == (int)attGrid.CurrentRow.Cells[5].Value && a.Type == CheckType()); var totalAttendance = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == (int)attGrid.CurrentRow.Cells[7].Value).FirstOrDefault(); Nullable <int> idStud = selected.FirstOrDefault().IDStudent; foreach (var x in selected) { var date = GetLatestDate((int)attGrid.CurrentRow.Cells[7].Value); switch (x.Status) { case "Neprítomný": if (x.Type == "Cvičenie" && !x.IsReplacable) { if (date != null) { var attDate = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IDStudent == (int)attGrid.CurrentRow.Cells[7].Value && a.Date == date && a.Type == "Cvičenie" && a.Status == "Nahradené").FirstOrDefault(); if (attDate != null) { attDate.IsReplacable = true; } } } break; case "Nahradené": date = GetClosestAbsentDate((int)attGrid.CurrentRow.Cells[7].Value, x); if (!x.IsReplacable) { var id = (int)attGrid.CurrentRow.Cells[7].Value; var attDate = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IDStudent == id && a.Date == date && a.Type == "Cvičenie" && a.Status == "Neprítomný").FirstOrDefault(); if (attDate != null) { attDate.IsReplacable = true; } } break; default: break; } if ((int?)attGrid.CurrentRow.Cells[7].Value != null) { idStud = (int?)attGrid.CurrentRow.Cells[7].Value; } con.AttendanceStuds.DeleteOnSubmit(x); } ; con.SubmitChanges(); Filter(); if (idStud != null) { PresenceCounter(idStud.GetValueOrDefault()); } ResetLabels(); } } catch (Exception ex) { ex.ToString(); MessageBox.Show("Nenašiel sa žiaden záznam.", "Prázdna tabuľka"); } }
private void button1_Click(object sender, EventArgs e) { try { using (var con = new StudentDBDataContext(conn_str)) { var type = CheckType(); if (attGrid.Rows.Count <= 0) { MessageBox.Show("Nie je vytvorený žiaden záznam"); return; } if (attGrid.SelectedRows.Count <= 0) { MessageBox.Show("Nie je vybraný žiaden záznam."); return; } foreach (DataGridViewRow selected in attGrid.SelectedRows) { AttendanceStud attendance = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IdAttendance == (int)selected.Cells[5].Value).FirstOrDefault(); var totalAttendance = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == (int)selected.Cells[7].Value).FirstOrDefault(); if (attendance == null) { MessageBox.Show("Nie je vybraný žiaden záznam."); return; } if (totalAttendance == null) { MessageBox.Show("Nenašiel sa záznam o celkovej dochádzke, ak máte pridaných študentov, skúste reštartovať aplikáciu", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } attendance.Status = comboBox2.SelectedItem.ToString(); AttendanceStud attDate; var date = GetLatestDate((int)selected.Cells[7].Value); switch (comboBox2.SelectedItem.ToString()) { case "Neprítomný": if (attendance.Type == "Cvičenie" && date == null) { attendance.IsReplacable = true; } else if (attendance.Type == "Cvičenie" && date != null) { attDate = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IDStudent == (int)selected.Cells[7].Value && a.Date == date && a.Type == "Cvičenie").FirstOrDefault(); if (attDate.Status == "Nahradené" && attDate.IsReplacable) { attDate.IsReplacable = false; attendance.IsReplacable = false; } else { attendance.IsReplacable = true; } } attendance.Comment = string.Empty; break; case "Nahradené": //date = GetLatestDate((int)selected.Cells[7].Value); date = GetClosestAbsentDate((int)selected.Cells[7].Value, attendance); attDate = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IDStudent == (int)selected.Cells[7].Value && a.Date == date && a.Type == "Cvičenie").FirstOrDefault(); if (attDate != null) { if (CheckType() == "Cvičenie" && attDate.IsReplacable == true && RWS(attDate.Status) == "Neprítomný" || attDate.Status == "Ospravedlnené") { attDate.IsReplacable = false; attendance.IsReplacable = false; } else { attendance.IsReplacable = true; } } else if (attendance.Type == "Cvičenie") { attendance.IsReplacable = false; } attendance.Comment = string.Empty; con.SubmitChanges(); break; case "Zrušené": attendance.IsReplacable = false; break; case "Ospravedlnené": if (attendance.Type == "Cvičenie" && date == null) { attendance.IsReplacable = true; } else if (attendance.Type == "Cvičenie" && date != null) { attDate = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.IDStudent == (int)selected.Cells[7].Value && a.Date == date && a.Type == "Cvičenie").FirstOrDefault(); if (attDate.Status == "Nahradené" && attDate.IsReplacable) { attDate.IsReplacable = false; attendance.IsReplacable = false; } else { attendance.IsReplacable = true; } } attendance.Comment = string.Empty; break; default: break; } globalRowIndex = selected.Index; con.SubmitChanges(); PresenceCounter((int)selected.Cells[7].Value); ResetLabels(); } if (comboBox5.Text != string.Empty) { var value = comboBox5.SelectedItem; FilterBy(); comboBox5.SelectedItem = value; } else { Filter(); } this.attGrid.ClearSelection(); this.attGrid.CurrentCell.Selected = false; try { this.attGrid.Rows[globalRowIndex + 1].Selected = true; this.attGrid.Focus(); } catch (Exception) { } if (comboBox2.Text == "Zrušené") { IQueryable <AttendanceStud> attCancelled; var cancelledComment = Interaction.InputBox("Uveďte dôvod zrušenia výučby", "Dôvod zrušenia", "Zrušená hodina", -1, -1); switch (comboBox1.SelectedIndex) { case 0: attCancelled = con.AttendanceStuds.Where(a => a.IDSkupina == StudentSkup.Id && a.Type == CheckType() && a.Date == (DateTime)attGrid.CurrentRow.Cells[2].Value); break; default: attCancelled = con.AttendanceStuds .Where(a => a.IDSkupina == StudentSkup.Id && a.Type == CheckType() && a.Date == (DateTime)attGrid.CurrentRow.Cells[2].Value && a.Student.ID_Kruzok == comboBox1.Text); break; } foreach (var x in attCancelled) { x.Status = comboBox2.Text; x.Comment = cancelledComment; con.SubmitChanges(); } Filter(); } ResetLabels(); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show("Nastala chyba, viac informácii nájdete v logoch.", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void PresenceCounter(int studentId) { try { using (var con = new StudentDBDataContext(conn_str)) { var getAttendance = con.GetTable <AttendanceStud>().Where(x => x.IDSkupina == StudentSkup.Id && x.IDStudent == studentId); var stud = con.GetTable <Student>().Where(f => f.Id == studentId).FirstOrDefault(); var z = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == studentId).FirstOrDefault(); List <DateTime> dateList = new List <DateTime>(); z.TotalAbsentLecture = 0; z.TotalPresentLecture = 0; z.TotalExcusedLecture = 0; z.TotalPresentSeminar = 0; z.TotalExcusedSeminar = 0; z.TotalAbsentSeminar = 0; con.SubmitChanges(); z.TotalLecture = con.GetTable <AttendanceStud>().Where(x => x.IDSkupina == StudentSkup.Id && x.IdGroup == stud.ID_Kruzok && x.Type == "Prednáška").Select(x => x.Date).Distinct().Count(); var xxx = con.GetTable <AttendanceStud>().Where(x => x.IDSkupina == StudentSkup.Id && x.IdGroup == stud.ID_Kruzok && x.Type == "Cvičenie"); foreach (var o in xxx) { if (o.Status != "Nahradené") { dateList.Add(o.Date); } } if (dateList.Count > 0) { z.TotalSeminar = dateList.Distinct().Count(); } // z.TotalSeminar// = con.GetTable<AttendanceStud>().Where(x => x.IDSkupina == StudentSkup.Id && x.IdGroup == stud.ID_Kruzok && x.Type == "Cvičenie").Select(x => x.Date).Distinct().Count(); foreach (var att in getAttendance) { if (att.Status == "Prítomný" && att.Type == "Prednáška") { z.TotalPresentLecture += 1; } else if (att.Status == "Prítomný" && att.Type == "Cvičenie") { z.TotalPresentSeminar += 1; } else if (att.Status == "Neprítomný" && att.Type == "Prednáška") { z.TotalAbsentLecture += 1; } else if (att.Status == "Neprítomný" && att.Type == "Cvičenie" && att.IsReplacable) { z.TotalAbsentSeminar += 1; } else if (att.Status == "Neprítomný" && att.Type == "Cvičenie" && !att.IsReplacable) { continue; } else if (att.Status == "Nahradené" && att.Type == "Cvičenie" && att.IsReplacable) { z.TotalPresentSeminar += 1; } else if (att.Status == "Nahradené" && att.Type == "Cvičenie" && !att.IsReplacable) { if (z.TotalAbsentSeminar > 0) { z.TotalAbsentSeminar -= 1; } z.TotalPresentSeminar += 1; } else if (att.Status == "Ospravedlnené" && att.Type == "Cvičenie")// && !att.IsReplacable) { z.TotalExcusedSeminar += 1; z.TotalAbsentSeminar += 1; } else if (att.Status == "Ospravedlnené" && att.Type == "Prednáška") { z.TotalExcusedLecture += 1; z.TotalAbsentLecture += 1; } else if (att.Status == "Zrušené" && att.Type == "Prednáška") { if (z.TotalLecture > 0) { z.TotalLecture -= 1; } } else if (att.Status == "Zrušené" && att.Type == "Cvičenie") { if (z.TotalSeminar > 0) { z.TotalSeminar -= 1; } } con.SubmitChanges(); ResetLabels(); } con.SubmitChanges(); ResetLabels(); } } catch (Exception ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show("Nastala chyba, viac informácii nájdete v logoch.", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// Získanie študentov používateľa pre vybranú skupinu private void GetTable() { try { using (var con = new StudentDBDataContext(conn_str)) { var students = con.GetTable <Student>()?.Where(studs => studs.ID_stud_skupina == studentSkupina.Id && studs.Forma == studentSkupina.Forma). Select(x => new { x.Id, x.Meno, x.Priezvisko, x.Email, Email2 = x.Email_UCM, x.ISIC, Ročník = x.Rocnik, x.Forma, Krúžok = x.IdGroupForAttendance, x.ID_Kruzok, Body = x.FinalGrades.Where(y => y.IdStudent == x.Id).Select(z => z.GotPoints).FirstOrDefault(), Známka = x.FinalGrades.Where(y => y.IdStudent == x.Id).Select(z => z.Grade).FirstOrDefault() }); if (Student_Grid.SelectedRows.Count > 0) { if (Student_Grid.CurrentRow != null) { currentRow = Student_Grid.CurrentRow.Index; } } Student_Grid.RowHeadersVisible = false; Student_Grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; Student_Grid.MultiSelect = false; Student_Grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect; Student_Grid.DataSource = students.OrderBy(x => x.Priezvisko); Student_Grid.Columns["Id"].Visible = false; Student_Grid.Columns["ID_Kruzok"].Visible = false; Student_Grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; // Vytvorenie celkovej dochádzky pre študentov, v prípade ak ešte nebola vytvorená foreach (var stud in students) { var exists = con.GetTable <TotalAttendance>().Where(x => x.IdStudent == stud.Id).FirstOrDefault(); if (exists == null) { TotalAttendance totalAttendance = new TotalAttendance() { IdStudent = stud.Id }; con.TotalAttendances.InsertOnSubmit(totalAttendance); } else { continue; } } con.SubmitChanges(); OnLoadStudent(); } } catch (DataException ex) { Logger newLog = new Logger(); newLog.LogError(ex); MessageBox.Show(ex.Message); } }