示例#1
0
        // Private method to perform MCQ marks calculation
        private void calculateMCQMarks(Assessment assessment, List <Question> questions)
        {
            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                List <Student_Answer> studentAnswerList = db.Student_Answer.Where(sa => sa.Question.assessmentId == assessment.Id).ToList();
                int    correctCounter = 0;
                double score          = 0.0;

                for (int i = 0; i < studentAnswerList.Count; i++)
                {
                    if (db.Answer.Find(Guid.Parse(studentAnswerList[i].studentAnswer)).isCorrectAnswer)
                    {
                        correctCounter++;
                    }
                }

                score = Math.Round((Convert.ToDouble(correctCounter) / assessment.Question.Count) * 100.00);

                Student_Assessment studentAssessment = new Student_Assessment();
                studentAssessment.Id           = Guid.NewGuid();
                studentAssessment.assessmentId = assessment.Id;
                studentAssessment.studentId    = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
                studentAssessment.score        = Convert.ToInt32(score);
                studentAssessment.dateFinished = DateTime.Now;
                db.Student_Assessment.Add(studentAssessment);
                db.SaveChanges();
            }
        }
        /**
         * Private method for initializing
         * Subject table in database
         */
        private void initSubjectDatabase()
        {
            // Declare subjects for the application
            string[] subjects =
            {
                "BACS2053 Object-Oriented Analysis and Design",
                "BACS2063 Data Structures & Algorithms",
                "BAIT2164 Computer Networks",
                "BAIT2113 Web Application Development",
                "AACA2132 Financial Accounting",
                "AACA3232 Principles of Finance",
                "AACA3431 Fundamentals of Auditing",
                "AACA2322 Pricing Strategy",
                "ADMK2563 Digital Marketing",
                "ADMK3262 Principles of Marketing",
                "ACHC2362 Production and Multimedia",
                "ACHC2342 Television Production",
                "ABCI2423 Advanced Photography",
                "ABCC2212 Consumer Behaviour and Culture",
            };

            /**
             * Temporarily use db connection to insert the subjects
             */
            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                // Loop through each subject and create them
                foreach (string subject in subjects)
                {
                    // Check if the subject already exist in database
                    if (db.Subject.Where(s => s.subjectName == subject).FirstOrDefault() is null)
                    {
                        try
                        {
                            // Create new Subject object
                            Subject sub = new Subject();
                            sub.Id          = Guid.NewGuid();
                            sub.subjectName = subject;
                            sub.creditHours = Convert.ToInt32(subject.Substring(7, 1));

                            // Save the new subject into database
                            db.Subject.Add(sub);
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception($"An exception occured when inserting subjects: {ex.Message}");
                        }
                    }
                }
            }
        }
        protected void submitBtn_Click(object sender, EventArgs e)
        {
            // Variables declaration
            double totalMark = 0.0;
            Guid   assessID  = Guid.Empty;
            string studID    = "";


            try
            {
                assessID = Guid.Parse(Page.RouteData.Values["id"].ToString());
                studID   = Page.RouteData.Values["studId"].ToString();
            }
            catch (Exception)
            {
                Response.Redirect("/lecturer/list");
            }

            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                Student_Assessment studAssess = db.Student_Assessment.Where(sa => sa.aspnet_Users.LoweredUserName.Equals(studID.ToLower()) && sa.assessmentId == assessID).FirstOrDefault();

                if (studAssess is null)
                {
                    Response.Redirect("/lecturer/list");
                }

                List <Question> questions = studAssess.Assessment.Question.ToList();

                // Iterate and display questions
                for (int i = 0; i < questions.Count; i++)
                {
                    TextBox markTxtBox = questionPlaceHolder.FindControl($"writtenAns_qm{i + 1}") as TextBox;
                    totalMark += Convert.ToDouble(markTxtBox.Text);
                }

                // Calculate final mark
                totalMark /= Convert.ToDouble(questions.Count);

                studAssess.score = Convert.ToInt16(totalMark);
                db.SaveChanges();

                // Display label
                totalMarkLbl.Text        = $"{Convert.ToInt16(totalMark).ToString()} ({studAssess.getGrade()})";
                alertPlaceholder.Visible = true;

                // Send an email of the score to student
                sendEmailToStudent(studAssess);
            }
        }
        /**
         * Private method for initializing
         * aspnet_Roles table in database
         */
        private void initProgrammeDatabase()
        {
            // Declare programmes for this application
            string[] programmes =
            {
                "[FOCS] Bachelor of Information Technology - Software Systems Development (RSD)",
                "[FOCS] Bachelor of Information Technology - Internet Technology (RIT)",
                "[FCCI] Bachelor of Communication & Creative Industries - Advertising (RAC)",
                "[FCCI] Bachelor of Communication & Creative Industries - Broadcasting (RBC)",
                "[FAFB] Bachelor of Accountancy, Finance & Business - Marketing (RMA)",
                "[FAFB] Bachelor of Accountancy, Finance & Business - Accounting (RAA)",
            };

            /**
             * Temporarily use db connection to insert the programmes
             */
            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                // Loop through each prog and create them
                foreach (string prog in programmes)
                {
                    // Check if the subject already exist in database
                    if (db.Programme.Where(s => s.progName == prog).FirstOrDefault() is null)
                    {
                        try
                        {
                            // Create new Programme object
                            Programme newProg = new Programme();
                            newProg.progId   = Guid.NewGuid();
                            newProg.progName = prog;
                            newProg.faculty  = prog.Substring(1, 4);

                            // Save the new programme into database
                            db.Programme.Add(newProg);
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception($"An exception occured when inserting programme: {ex.Message}");
                        }
                    }
                }
            }
        }
        public void addNewSubject()
        {
            if (Page.IsValid)
            {
                // Create the Subject
                Subject subject = new Subject();
                subject.Id = Guid.NewGuid();
                TryUpdateModel(subject);

                if (ModelState.IsValid)
                {
                    // Connect to database to add new subject
                    using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
                    {
                        // Add the new subject and save it
                        db.Subject.Add(subject);
                        db.SaveChanges();

                        // Set the text to new subject name
                        newSubjectName.Text = subject.subjectName;

                        // Show success label & hide failure label
                        alertSuccess.Visible = true;
                        alertFailure.Visible = false;
                    }
                }
                else
                {
                    // Set the error text
                    alertFailureMsg.Text = "Oops! Something went wrong when registering the new subject";

                    // Show success label & hide failure label
                    alertSuccess.Visible = false;
                    alertFailure.Visible = true;
                }
            }
        }
示例#6
0
        protected void submitAsmntBtn_Click(object sender, EventArgs e)
        {
            String assessID = "";

            try
            {
                assessID = Page.RouteData.Values["id"].ToString();
            }
            catch (Exception)
            {
                Response.Redirect("/student/list");
            }

            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                Assessment assessment = db.Assessment.Find(Guid.Parse(assessID));

                if (assessment.type == 0)
                {
                    // Get the list of questions
                    List <Question> questions = assessment.Question.ToList();

                    // Loop through the list of questions
                    for (int i = 0; i < questions.Count; i++)
                    {
                        Student_Answer student_Answer = new Student_Answer();

                        // Declare an empty Guid and question ID
                        Guid studMCQAnswerID = Guid.Empty;
                        Guid questionID      = questions[i].Id;

                        // Loop through the 4 MCQ choice to find the answer choice the student has chosen
                        for (int j = 0; j < 4; j++)
                        {
                            CheckBox ansChkBox = questionPlaceHolder.FindControl($"mcqAns_{i + 1}_{j + 1}") as CheckBox;

                            // If student picked this MCQ choice as the answer
                            if (ansChkBox.Checked)
                            {
                                // Get the MCQ answer text
                                String studSelectedAns = (questionPlaceHolder.FindControl($"ans_{i + 1}_{j + 1}") as Label).Text.Substring(3);

                                // Retrieve the answer and get the ID
                                Answer answer = db.Answer.Where(a => a.answer1.Equals(studSelectedAns) && a.questionId == questionID).FirstOrDefault();
                                if (answer != null)
                                {
                                    studMCQAnswerID = answer.Id;
                                }
                                break;
                            }
                        }

                        // Set student answer attributes and save it into database
                        student_Answer.questionId    = questionID;
                        student_Answer.studentId     = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
                        student_Answer.studentAnswer = studMCQAnswerID.ToString();
                        db.Student_Answer.Add(student_Answer);
                        db.SaveChanges();
                    }

                    // Method to perform MCQ marks calculation
                    calculateMCQMarks(assessment, questions);

                    Response.Redirect("/student/list", false);
                }
                else if (assessment.type == 1)
                {
                    // Get the list of questions
                    List <Question> questions = assessment.Question.ToList();

                    // Create new student assessment record
                    Student_Assessment student_Assessment = new Student_Assessment();
                    student_Assessment.Id           = Guid.NewGuid();
                    student_Assessment.studentId    = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
                    student_Assessment.assessmentId = assessment.Id;
                    student_Assessment.dateFinished = DateTime.Now;
                    student_Assessment.score        = -1;

                    // Loop through the list of questions
                    for (int i = 0; i < questions.Count; i++)
                    {
                        // Get the written answer and save into database
                        Student_Answer student_Answer = new Student_Answer();
                        TextBox        writtenAnswer  = questionPlaceHolder.FindControl($"writtenAns_q{i + 1}") as TextBox;
                        student_Answer.questionId    = questions[i].Id;
                        student_Answer.studentId     = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());
                        student_Answer.studentAnswer = writtenAnswer.Text;
                        db.Student_Answer.Add(student_Answer);
                        db.SaveChanges();
                    }

                    db.Student_Assessment.Add(student_Assessment);
                    db.SaveChanges();
                }

                Session["assessCompleted"] = "1";
                Session["assessName"]      = assessment.assessName;
                Response.Redirect("/student/list");
            }
        }
        protected void updateBtn_Click(object sender, EventArgs e)
        {
            Guid assessID = Guid.Empty;

            try
            {
                assessID = Guid.Parse(Page.RouteData.Values["id"].ToString());
            }
            catch (Exception)
            {
                Response.Redirect("/lecturer/list");
            }

            using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
            {
                Assessment assessment = db.Assessment.Find(assessID);

                if (assessment == null)
                {
                    Response.Redirect("/lecturer/list");
                }

                List <Question> questions = assessment.Question.ToList();

                assessment.subject    = Guid.Parse(subject.SelectedItem.Value);
                assessment.assessName = assessName.Text;
                assessment.publicity  = Convert.ToInt16(assessPublicity.SelectedItem.Value);
                db.SaveChanges();
                subjectLbl.Text = assessment.Subject1.subjectName;

                // 0 = MCQ, 1 = Written
                if (assessment.type == 0)
                {
                    for (int i = 0; i < questions.Count; i++)
                    {
                        questions[i].question1 = (questionPlaceHolder.FindControl($"ques_{i + 1}") as TextBox).Text;

                        FileUpload quesImg = questionPlaceHolder.FindControl($"quesImg_{i + 1}") as FileUpload;
                        // If there is an image
                        if (quesImg.HasFile)
                        {
                            Regex  fileExtRegex       = new Regex(@"^\.(jpg|png|jpeg|gif)$", RegexOptions.IgnoreCase);
                            string imageStoragePath   = "~/Image_Storage/",
                                   fileName           = Path.GetFileName(quesImg.PostedFile.FileName),
                                   fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName),
                                   fileExtension      = Path.GetExtension(fileName);
                            if (fileExtRegex.IsMatch(fileExtension))
                            {
                                if (!Directory.Exists(Server.MapPath(imageStoragePath)))
                                {
                                    Directory.CreateDirectory(Server.MapPath(imageStoragePath));
                                }
                                String finalPath = $"{fileNameWithoutExt}_{DateTime.Now.Ticks.ToString()}{fileExtension}";
                                quesImg.PostedFile.SaveAs($"{Server.MapPath(imageStoragePath)}{finalPath}");
                                questions[i].imgPath = finalPath;
                            }
                        }

                        List <Answer> answers = questions[i].Answer.ToList();

                        for (int j = 0; j < answers.Count; j++)
                        {
                            answers[j].answer1 = (questionPlaceHolder.FindControl($"ans_{i + 1}_{j + 1}") as TextBox).Text;

                            CheckBox isAnsChkBox = questionPlaceHolder.FindControl($"isAns_{i + 1}_{j + 1}") as CheckBox;
                            answers[j].isCorrectAnswer = false;
                            if (isAnsChkBox.Checked)
                            {
                                answers[j].isCorrectAnswer = true;
                            }
                        }

                        db.SaveChanges();
                    }
                }
                else if (assessment.type == 1)
                {
                    // Generate nth of questions
                    for (int i = 0; i < questions.Count; i++)
                    {
                        questions[i].question1 = (questionPlaceHolder.FindControl($"ques_{i + 1}") as TextBox).Text;

                        FileUpload quesImg = questionPlaceHolder.FindControl($"quesImg_{i + 1}") as FileUpload;
                        // If there is an image
                        if (quesImg.HasFile)
                        {
                            Regex  fileExtRegex       = new Regex(@"^\.(jpg|png|jpeg|gif)$", RegexOptions.IgnoreCase);
                            string imageStoragePath   = "~/Image_Storage/",
                                   fileName           = Path.GetFileName(quesImg.PostedFile.FileName),
                                   fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName),
                                   fileExtension      = Path.GetExtension(fileName);
                            if (fileExtRegex.IsMatch(fileExtension))
                            {
                                if (!Directory.Exists(Server.MapPath(imageStoragePath)))
                                {
                                    Directory.CreateDirectory(Server.MapPath(imageStoragePath));
                                }
                                String finalPath = $"{fileNameWithoutExt}_{DateTime.Now.Ticks.ToString()}{fileExtension}";
                                quesImg.PostedFile.SaveAs($"{Server.MapPath(imageStoragePath)}{finalPath}");
                                questions[i].imgPath = finalPath;
                            }
                        }
                        // Save the changes
                        db.SaveChanges();
                    }
                }
                updateStatus.Visible = true;
            }
        }
        public void addNewStudent()
        {
            if (Page.IsValid)
            {
                try
                {
                    // Retrieve controls
                    TextBox      studId    = registerStudentForm.FindControl("studId") as TextBox;
                    TextBox      password  = registerStudentForm.FindControl("password_confirmation") as TextBox;
                    TextBox      email     = registerStudentForm.FindControl("email") as TextBox;
                    DropDownList programme = registerStudentForm.FindControl("programme") as DropDownList;

                    // First create the user membership
                    MembershipUser newStudent = Membership.CreateUser(studId.Text, password.Text, email.Text);
                    Roles.AddUserToRole(studId.Text, "Student");

                    // Create the student profile
                    Student_Profile student = new Student_Profile();
                    student.Id = (Guid)newStudent.ProviderUserKey;
                    TryUpdateModel(student);

                    if (ModelState.IsValid)
                    {
                        // Connect to database to add new staff profile
                        using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
                        {
                            // Create the enrollment records for the new student
                            Enrollment newEnrollment = new Enrollment();
                            newEnrollment.Id                 = Guid.NewGuid();
                            newEnrollment.studId             = student.Id;
                            newEnrollment.progId             = Guid.Parse(programme.SelectedItem.Value);
                            newEnrollment.enrollmentDateTime = DateTime.Now;

                            // Add the new staff and save it
                            db.Enrollment.Add(newEnrollment);
                            db.Student_Profile.Add(student);
                            db.SaveChanges();

                            // Set the text to new staff ID
                            newStudID.Text = studId.Text;

                            // Show success label & hide failure label
                            alertSuccess.Visible = true;
                            alertFailure.Visible = false;
                        }
                    }
                }
                catch (MembershipCreateUserException ex)
                {
                    // Match exception code with status code from MembershipCreateStatus class
                    switch (ex.StatusCode)
                    {
                    case MembershipCreateStatus.DuplicateUserName:
                        alertFailureMsg.Text = "There already exists a user with this username.";
                        break;

                    case MembershipCreateStatus.DuplicateEmail:
                        alertFailureMsg.Text = "There already exists a user with this email address.";
                        break;

                    case MembershipCreateStatus.InvalidEmail:
                        alertFailureMsg.Text = "There email address you provided in invalid.";
                        break;

                    case MembershipCreateStatus.InvalidPassword:
                        alertFailureMsg.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                        break;

                    default:
                        alertFailureMsg.Text = "There was an unknown error; the user account was NOT created.";
                        break;
                    }

                    // Show failure message
                    alertSuccess.Visible = false;
                    alertFailure.Visible = true;
                }
                catch (Exception ex)
                {
                    // Show failure message
                    alertFailureMsg.Text = "Oops! There was a problem occurred when registering the new student.";
                    alertSuccess.Visible = false;
                    alertFailure.Visible = true;
                }
            }
        }
        public void addNewLecturer()
        {
            if (Page.IsValid)
            {
                try
                {
                    // Retrieve controls
                    TextBox lectId   = registerLecturerForm.FindControl("lectId") as TextBox;
                    TextBox password = registerLecturerForm.FindControl("password_confirmation") as TextBox;
                    TextBox email    = registerLecturerForm.FindControl("email") as TextBox;

                    // First create the user membership
                    MembershipUser newLecturer = Membership.CreateUser(lectId.Text, password.Text, email.Text);
                    Roles.AddUserToRole(lectId.Text, "Lecturer");

                    // Create the lecturer profile
                    Lecturer_Profile lecturer = new Lecturer_Profile();
                    lecturer.Id = (Guid)newLecturer.ProviderUserKey;
                    TryUpdateModel(lecturer);

                    if (ModelState.IsValid)
                    {
                        // Connect to database to add new staff profile
                        using (OnlineAssessmentDBEntities db = new OnlineAssessmentDBEntities())
                        {
                            // Add the new staff and save it
                            db.Lecturer_Profile.Add(lecturer);
                            db.SaveChanges();

                            // Set the text to new staff ID
                            newLecturerID.Text = lectId.Text;

                            // Show success label & hide failure label
                            alertSuccess.Visible = true;
                            alertFailure.Visible = false;
                        }
                    }
                }
                catch (MembershipCreateUserException ex)
                {
                    // Match exception code with status code from MembershipCreateStatus class
                    switch (ex.StatusCode)
                    {
                    case MembershipCreateStatus.DuplicateUserName:
                        alertFailureMsg.Text = "There already exists a user with this username.";
                        break;

                    case MembershipCreateStatus.DuplicateEmail:
                        alertFailureMsg.Text = "There already exists a user with this email address.";
                        break;

                    case MembershipCreateStatus.InvalidEmail:
                        alertFailureMsg.Text = "There email address you provided in invalid.";
                        break;

                    case MembershipCreateStatus.InvalidPassword:
                        alertFailureMsg.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
                        break;

                    default:
                        alertFailureMsg.Text = "There was an unknown error; the user account was NOT created.";
                        break;
                    }

                    // Show failure message
                    alertSuccess.Visible = false;
                    alertFailure.Visible = true;
                }
                catch (Exception ex)
                {
                    // Show failure message
                    alertFailureMsg.Text = "Oops! There was a problem occurred when registering the new lecturer.";
                    alertSuccess.Visible = false;
                    alertFailure.Visible = true;
                }
            }
        }