//
        //On changing the Format ComboBox: Resets & Disables controls, Loads No Of Question ComboBox, gets and sets the value of No of Questions
        //
        private void formatCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Resets & Disables controls
            noOfQuestionsCombo.Items.Clear();
            noOfQuestionsCombo.ResetText();

            //Loads No Of Question ComboBox
            Questions q = new Questions();
            q.exam_Type = examTypeText.Text;
            q.section = sectionCombo.SelectedItem.ToString();
            q.format = formatCombo.SelectedItem.ToString();
            int i = qb.getQuestionNoCount(q);
            for (int j = 0; j <= i; j++)
            {
                noOfQuestionsCombo.Items.Add(j);
            }
            noOfQuestionsCombo.Enabled = true;
            update.Enabled = true;

            //Gets and sets the value of No of Questions
            Paper s = new Paper();
            s.exam_ID = ed.exam_ID;
            s.section = sectionCombo.SelectedItem.ToString();
            s.format = formatCombo.SelectedItem.ToString();
            int no = p.getNoOfQuestions(s);
            noOfQuestionsCombo.SelectedItem = no;
        }
 public Paper[] getPaperDetails(Paper p)
 {
     PaperDAL pq = new PaperDAL();
     int a = pq.getRowCountForExam(p);
     Paper[] g = new Paper[a];
     g = pq.getPaperDetails(p);
     return g;
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     ed.exam_ID = (String)Session["exam_ID"];
     examIDText.Text = ed.exam_ID;
     int count = p.getRowCountForExam(ed);
     Paper[] arr = new Paper[count];
     arr = p.viewPaperDetails(ed, count);
     paperDataGrid.DataSource = arr;
     paperDataGrid.Enabled = false;
     //paperDataGrid.EnableHeadersVisualStyles = true;
     //paperDataGrid.GridColor = Color.DarkRed;
 }
 //
 //On click on View button: Opens the ViewPaperDetails Form, displaying the Paper
 //
 protected void view_Click(object sender, EventArgs e)
 {
     if (examIDCombo.SelectedIndex != -1)
     {
         Paper p = new Paper();
         p.exam_ID = examIDCombo.SelectedItem.ToString();
         Session["exam_ID"] = p.exam_ID;
         Response.Redirect("");
     }
     else
         System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please select a valid Exam ID.')</SCRIPT>");
         //MessageBox.Show("Please select a valid Exam ID.", "Error");
 }
 //
 //Deletes paper, returns Success or Error Message
 //
 public string deletePaper(Paper b)
 {
     try
     {
         conn.Open();
         cmd = new SqlCommand("Delete From SetPaper where Exam_ID='" + b.exam_ID + "'", conn);
         int i =cmd.ExecuteNonQuery();
         conn.Close();
         if(i>0)
             return "Paper for Exam " + b.exam_ID + " is successfully deleted";
         else
             return "Attempt unsuccessful. Sorry for the inconvenience.";
     }
     catch (Exception ex)
     {
         conn.Close();
         return "Attempt unsuccessful. Sorry for the inconvenience.";
     }
 }
        //
        //Deletes the selected Exam & pops up a Success or Error message
        //
        protected void delete_Click(object sender, EventArgs e)
        {
            if (examIDCombo.SelectedIndex != -1)
            {
                Paper b = new Paper();
                b.exam_ID = examIDCombo.SelectedItem.ToString();
                //DialogResult result = MessageBox.Show("Are you sure you want delete " + examIDCombo.SelectedItem.ToString() + "?", "Delete Exam Type", MessageBoxButtons.YesNo);
                //if (result == DialogResult.Yes)

                    string abc = ed.deletePaper(b);
                    System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert(abc)</SCRIPT>");
                    //MessageBox.Show(abc, "Delete Paper");

            }
            else
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please select a valid Exam ID.')</SCRIPT>");
                //MessageBox.Show("Please select a valid Exam ID.", "Error");

            this.Page_Load(sender, e);
        }
        //
        //On click of Add: Validates selection, Adds it, and updates No Of Quesions Added
        //
        private void add_Click(object sender, EventArgs e)
        {
            //Validates selection and adds it
            if ((sectionCombo.SelectedIndex == -1 )|| (formatCombo.SelectedIndex == -1) || (noOfQuestionsCombo.SelectedIndex == -1))
                MessageBox.Show("Please select a valid entry","Error");
            else
            {
                Paper s = new Paper();
                s.exam_ID = ed.exam_ID;
                s.section = sectionCombo.SelectedItem.ToString();
                s.format = formatCombo.SelectedItem.ToString();
                s.no_Of_Questions = Convert.ToInt32(noOfQuestionsCombo.SelectedItem);
                string feed = p.addSectionFormat(s);
                MessageBox.Show(feed, "Set Paper");
            }

            //Updates No Of Quesions Added
            Paper pq = new Paper();
            pq.exam_ID = ed.exam_ID;
            noOfQuestionsText.Text = p.getAddedQuestionCount(pq)+"";
        }
        //
        //On Form Load: Loads Exam ID ComboBox
        //
        private void ViewPaperDetails_Load(object sender, EventArgs e)
        {
            // to allign the Legend(Group Box) to
            // the center of form
            int centerForm;
            int centerGroup;
            int groupStartPosition;

            centerForm = this.Width / 2;
            centerGroup = paperDetailsLegend.Width / 2;
            groupStartPosition = centerForm - centerGroup;
            paperDetailsLegend.Left = groupStartPosition;

            examIDText.Text = ed.exam_ID;
            int count = p.getRowCountForExam(ed);
            Paper[] arr = new Paper[count];
            arr = p.viewPaperDetails(ed, count);
            paperDataGrid.DataSource = arr;
            paperDataGrid.Enabled = false;
            paperDataGrid.EnableHeadersVisualStyles = true;
            paperDataGrid.GridColor = Color.DarkRed;
        }
        //
        //On click of Add: Validates selection, Adds it, and updates No Of Quesions Added
        //
        protected void add_Click(object sender, EventArgs e)
        {
            //Validates selection and adds it
            if ((sectionCombo.SelectedIndex == -1) || (formatCombo.SelectedIndex == -1) || (noOfQuestionsCombo.SelectedIndex == -1))
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please select a valid entry')</SCRIPT>");
                //MessageBox.Show("Please select a valid entry", "Error");
            else
            {
                Paper s = new Paper();
                s.exam_ID = ed.exam_ID;
                s.section = sectionCombo.SelectedItem.ToString();
                s.format = formatCombo.SelectedItem.ToString();
                s.no_Of_Questions = Convert.ToInt32(noOfQuestionsCombo.SelectedItem);
                string feed = p.addSectionFormat(s);
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Successfully')</SCRIPT>");
                //MessageBox.Show(feed, "Set Paper");
            }

            //Updates No Of Quesions Added
            Paper pq = new Paper();
            pq.exam_ID = ed.exam_ID;
            noOfQuestionsText.Text = p.getAddedQuestionCount(pq) + "";
        }
 //
 //Adds the selected Section-Format-No Of Questions, returns Success, Already Added or Error Message
 //
 public string addSectionFormat(Paper s)
 {
     try
     {
         conn.Open();
         cmd = new SqlCommand("Insert into SetPaper(Exam_ID,Section,Format,No_Of_Questions) values('" + s.exam_ID + "','" + s.section + "','" + s.format + "'," + s.no_Of_Questions + ")", conn);
         int i = cmd.ExecuteNonQuery();
         conn.Close();
         if(i==1)
             return "Successfully added";
         else
             return "Some error occured. Sorry for the inconvenience.";
     }
     catch (SqlException ex)
     {
         conn.Close();
         return "You have already added questions for the selected combination of Section-Format.";
     }
     catch (Exception e)
     {
         conn.Close();
         return "Some error occured. Sorry for the inconvenience.";
     }
 }
 //
 //DAL call to delete Paper
 //
 public string deletePaper(Paper b)
 {
     string abc = pq.deletePaper(b);
     return abc;
 }
 //
 //DAL call to add selected Section-Format-No Of Questions
 //
 public string addSectionFormat(Paper s)
 {
     string abc = pq.addSectionFormat(s);
     return abc;
 }
 //
 //DAL call to get an array containing the paper Details for a given Paper
 //
 public Paper[] viewPaperDetails(Paper s, int count)
 {
     Paper[] arr = new Paper[count];
     arr = pq.viewPaperDetails(s, count);
     return arr;
 }
 //
 //DAL call to update selected Section-Format-No Of Questions
 //
 public string updateSectionFormat(Paper s)
 {
     string feed = pq.updateSectionFormat(s);
     return feed;
 }
        //
        //On Form Load: Displays No of Added Question, Disables controls & Loads Section ComboBox
        //
        private void SetPaper_Load(object sender, EventArgs e)
        {
            // to allign the Legend(Group Box) to
            // the center of form
            int centerForm;
            int centerGroup;
            int groupStartPosition;

            centerForm = this.Width / 2;
            centerGroup = setPaperRegion.Width / 2;
            groupStartPosition = centerForm - centerGroup;
            setPaperRegion.Left = groupStartPosition;

            // Displays No of Added Questions
            Paper pq = new Paper();
            pq.exam_ID = ed.exam_ID;
            noOfQuestionsText.Text = p.getAddedQuestionCount(pq) + "";

            //Diables controls
            sectionCombo.Enabled = false;
            formatCombo.Enabled = false;
            noOfQuestionsCombo.Enabled = false;
            add.Enabled = false;

            //Loads Section ComboBox
            Questions q = new Questions();
            q.exam_Type = ed.exam_Type;
            int i = qb.getSectionCount(q);
            if (i > 0)
            {
                string[] abc = new string[i];
                abc = qb.loadSection(q, i);
                for (int j = 0; j < i; j++)
                {
                   sectionCombo.Items.Add(abc[j]);
                }
                sectionCombo.Enabled = true;
            }
            else
                MessageBox.Show("No Questions present in the database for the Exam Type of the selected Exam.", "Error");
        }
        public Paper[] getPaperDetails(Paper p)
        {
            SqlConnection cnNorth;
            SqlCommand cmdOrders;
            SqlDataReader dreadOrders;
            string constr = @"Server=NIKKHIL-HP\sqlexpress;Integrated Security=true; database=OnlineExamination";
            cnNorth = new SqlConnection(constr);
            cnNorth.Open();
            string query = string.Format("select Format from SetPaper where Exam_ID ='{0}'", p.exam_ID);
            cmdOrders = new SqlCommand(query, cnNorth);
            dreadOrders = cmdOrders.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dreadOrders);
            int a = dt.Rows.Count;

            Paper[] pa = new Paper[a];
            return pa;
            DataRow drow = dt.Rows[0];

            pa[0].format = drow[0].ToString();

               /* string[] tab = new string[a];
            DataRow dr;
            Object[] ob = new Object[1];
            for (int i = 0; i < a; i++)
            {
                dr = dt.Rows[i];
                ob= dr.ItemArray;
                tab[i] = Convert.ToString(ob);
               // tab[i] = ob.ToString();
            }*/
            dreadOrders.Close();
            cnNorth.Close();
            return pa;
        }
 public int getTotalQuestions(Paper pq)
 {
     PaperDAL ed = new PaperDAL();
     int count = ed.getTotalQuestions(pq);
     return count;
 }
        //
        //Randomly selects questions for each Format-Section specification of the Paper as per the No Of Questions
        //
        public Questions[] getQuestionPaper(Paper[] arr, Questions[] q, Exam_Details ed)
        {
            int maxcount = 0, mincount = 0;
            DataRow dr;
            int index = 0;
            Object[] abc = new Object[11];
            string temp;
            bool[] rand;
            int no = 0;
            int m;
            int param = arr.Length;
            DataTable dt;
            conn.Open();

            for (int l = 0; l < param; l++)
            {
                //Selects questions for each Format-Section specification of the Paper
                cmd = new SqlCommand("Select * from Questions where Exam_Type ='" + ed.exam_Type + "' and Section ='" + arr[l].section + "' and Format ='" + arr[l].format + "'",conn);
                dread = cmd.ExecuteReader();
                dt = new DataTable();
                dt.Load(dread);

                //Random Selection of questions
                maxcount = dt.Rows.Count;
                mincount = arr[l].no_Of_Questions;
                rand = new bool[maxcount];
                no = 0;
                while (no < mincount)
                {
                    Random r = new Random();
                    m = r.Next(maxcount);

                    if (rand[m] == false)
                    {
                        rand[m] = true;
                        no++;
                    }
                }

                //Loads the randomly selected question into Question Array
                for (int i = 0; i < maxcount; i++)
                {
                    if (rand[i] == true)
                    {
                        q[index] = new Questions();
                        dr = dt.Rows[i];
                        abc = dr.ItemArray;

                        q[index].question_ID = (string)abc.ElementAt(0);
                        q[index].exam_Type = (string)abc.ElementAt(1);
                        q[index].format = (string)abc.ElementAt(2);
                        q[index].question = (string)abc.ElementAt(3);
                        q[index].option1 = (string)abc.ElementAt(4);
                        q[index].option2 = (string)abc.ElementAt(5);
                        q[index].option3 = (string)abc.ElementAt(6);
                        q[index].option4 = (string)abc.ElementAt(7);
                        q[index].solution = (string)abc.ElementAt(8);
                        temp = abc.ElementAt(9).ToString();
                        q[index].marks = Convert.ToInt32(temp);
                        q[index].section = (string)abc.ElementAt(10);
                        if((q[index].format.Equals("Picture Question: Single Answer") )|| (q[index].format.Equals("Picture Question: Multiple Answer")))
                            q[index].picture_ID = (string)abc.ElementAt(11);
                        index++;
                    }
                }

            }
            dread.Close();
            conn.Close();
            return q;
        }
 //
 //DAL call to get the number of added questions for a particular Exam ID
 //
 public int getAddedQuestionCount(Paper p)
 {
     int i = pq.getAddedQuestionCount(p);
     return i;
 }
 //
 //Gets the row count for given Exam in Set Paper table
 //
 public int getRowCountForExam(Paper p)
 {
     conn.Open();
     cmd = new SqlCommand("select Section, Format, No_Of_Questions from SetPaper where Exam_ID ='"+p.exam_ID+"'", conn);
     dread = cmd.ExecuteReader();
     DataTable dt = new DataTable();
     dt.Load(dread);
     int a = dt.Rows.Count;
     dread.Close();
     conn.Close();
     return a;
 }
 //
 //Returns an array containing the paper Details for a given Paper
 //
 public Paper[] viewPaperDetails(Paper s, int count)
 {
     Paper[] arr = new Paper[count];
     conn.Open();
     cmd = new SqlCommand("select Section, Format, No_Of_Questions from SetPaper where Exam_ID ='"+s.exam_ID+"'", conn);
     dread = cmd.ExecuteReader();
     for (int i = 0; i < count; i++)
     {
         dread.Read();
         arr[i] = new Paper();
         arr[i].section = dread[0].ToString();
         arr[i].format = dread[1].ToString();
         arr[i].no_Of_Questions = Convert.ToInt32(dread[2].ToString());
         arr[i].exam_ID = s.exam_ID;
     }
     dread.Close();
     conn.Close();
     return arr;
 }
 //
 //Updates the selected Section-Format-No Of Questions, returns Success, or Error Message
 //
 public string updateSectionFormat(Paper s)
 {
     int count;
     try
     {
         conn.Open();
         cmd = new SqlCommand("Update SetPaper SET No_Of_Questions="+s.no_Of_Questions+" Where Exam_ID='" + s.exam_ID + "' and Section='" + s.section + "' and Format ='" + s.format + "'");
         count = cmd.ExecuteNonQuery();
         if (count == 0)
         {
             cmd = new SqlCommand("Insert into SetPaper(Exam_ID,Section,Format,No_Of_Questions) values('" + s.exam_ID + "','" + s.section + "','" + s.format + "'," + s.no_Of_Questions + ")", conn);
             count = cmd.ExecuteNonQuery();
         }
         conn.Close();
         if (count == 1)
             return "Successfully Updated.";
         else
             return "Some error occured. Sorry for the inconvenience.";
     }
     catch (Exception ex)
     {
         conn.Close();
         return "Some error occured. Sorry for the inconvenience.";
     }
 }
        public int getTotalQuestions(Paper pq)
        {
            SqlConnection cnNorth;
            SqlCommand cmdProducts;
            SqlDataReader dreadProducts;

            string constr = @"Server=NIKKHIL-HP\sqlexpress;Integrated Security=true; database=OnlineExamination";
            cnNorth = new SqlConnection(constr);
            cnNorth = new SqlConnection(constr);
            cmdProducts = new SqlCommand("select * from Paper", cnNorth);
            cnNorth.Open();
            dreadProducts = cmdProducts.ExecuteReader();
            int j = 0;
            while (dreadProducts.Read())
            {
                j++;
            }
            constr = @"Server=NIKKHIL-HP\sqlexpress;Integrated Security=true; database=OnlineExamination";
            cnNorth = new SqlConnection(constr);
            cnNorth = new SqlConnection(constr);
            String query = string.Format("select No_Of_Questions from Paper where Exam_ID = '{0}'", pq.exam_ID);
            cmdProducts = new SqlCommand(query, cnNorth);
            //cmdProducts = new SqlCommand("select No_Of_Questions from Paper", cnNorth);
            cnNorth.Open();
            dreadProducts = cmdProducts.ExecuteReader();
            int[] a = new int[j];
            int count = 0;
            string b;
            while (dreadProducts.Read())
            {
                b = dreadProducts[0].ToString();
                count += Convert.ToInt32(b);
            }
            dreadProducts.Close();
            return count;
        }
        public int getTotalMarks(Paper pq)
        {
            string constr = @"Server=NIKKHIL-HP\sqlexpress;Integrated Security=true; database=OnlineExamination";
            SqlDataAdapter da = new SqlDataAdapter();
            SqlCommandBuilder sb = new SqlCommandBuilder(da);
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlTransaction tran = conn.BeginTransaction();
            String sql = "Select Marks from TempPaper where Exam_ID ='" + pq.exam_ID + "'";
            da.SelectCommand = new SqlCommand(sql, conn, tran);
            DataSet ds = new DataSet();
            da.Fill(ds, "TempPaper");
            DataTable dt = ds.Tables["TempPaper"];
            int sum = 0;
            int a = dt.Rows.Count;
            DataRow dr;
            string m;
            int n;
            for (int i = 0; i < a; i++)
            {
                dr = dt.Rows[i];
                m = dr[0].ToString();
                n = Convert.ToInt32(m);
                sum += n;
            }

            conn.Close();
            return sum ;
        }
 //
 //DAL call to get the No Of Questions for the Section-Format combination for the given Exam
 //
 public int getNoOfQuestions(Paper s)
 {
     int a = pq.getNoOfQuestions(s);
     return a;
 }
 //
 //Accepts the passed Paper from ViewPaper form
 //
 public ViewPaperDetails(Paper e)
 {
     InitializeComponent();
     ed = e;
 }
 //
 //DAL call to get the row count for given Exam in Set Paper table
 //
 public int getRowCountForExam(Paper p)
 {
     int a = pq.getRowCountForExam(p);
     return a;
 }
        //
        //On click Of Start Button
        //
        protected void startTest_Click(object sender, EventArgs e)
        {
            //DialogResult r = MessageBox.Show("Are you sure you want to start the test?", "Start the Test", MessageBoxButtons.OKCancel);
            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue == "Yes")
            {
                //Gets the Set Paper Details for the Exam
                Paper s = new Paper();
                s.exam_ID = ed.exam_ID;
                PaperBS p = new PaperBS();
                int scount = p.getRowCountForExam(s);
                Paper[] arr = new Paper[scount];
                arr = p.viewPaperDetails(s, scount);

                //Timer duration
                int timeLeft = ed.duration * 60;

                //Gets the questions according to the set paper details after random selection and shuffling
                int qcount = p.getAddedQuestionCount(s);
                q = new Questions[qcount];
                QuestionsBS b = new QuestionsBS();
                q = b.getQuestionPaper(arr, q, ed);

                //Initializes the Answers array and Bookmark array
                AnswerBS ab = new AnswerBS();
                a = new Answers[qcount];
                a = ab.initializeAnswersArray(a, q, ed, emp);
                b1 = new Bookmark[qcount];
                b1 = ab.initializeBookmarksArray(b1);

                //Swap Options
                Questions[] qnew = b.swapOptions(q);
                Int32 n = 0;
                Session["noOfQues"] = q.Count();
                Session["questions"] = qnew;
                Session["answers"] = a;
                Session["bookmark"] = b1;
                Session["ind"] = n;
                Session["time"] = timeLeft;
                Session["employee"] = emp;
                Session["exam"] = ed;
                Session["timeout"] = DateTime.Now.AddMinutes(ed.duration).ToString();

                //Chooses the first from according to the format of first question
                string first = qnew[0].format;
                switch (first)
                {
                    case "Match The Column":
                        Response.Redirect("~/MatchTheColumnTest.aspx");
                        break;

                    case "MCQ (Single Answer)":
                        Response.Redirect("~/SingleAnswerTest.aspx");
                        break;

                    case "MCQ (Multiple Answers)":
                        Response.Redirect("~/MultipleAnswerTest.aspx");
                        break;

                    case "Picture Question: Single Answer":
                        Response.Redirect("~/PictureQuestionSingleAns.aspx");
                        break;

                    case "Picture Question: Multiple Answer":
                        Response.Redirect("~/PictureQuestionMultipleAnswer.aspx");
                        break;
                }
            }
        }
 //
 //Returns the number of added Questions for a given Exam ID
 //
 public int getAddedQuestionCount(Paper pq)
 {
     cmd = new SqlCommand("select No_Of_Questions from SetPaper where Exam_ID='" + pq.exam_ID + "'", conn);
     conn.Open();
     dread = cmd.ExecuteReader();
     int count = 0;
     while (dread.Read())
     {
         string n = dread["No_Of_Questions"].ToString();
         int m = Convert.ToInt32(n);
         count += m;
     }
     dread.Close();
     conn.Close();
     return count;
 }
 //
 //Gets the No Of Questions for the Section-Format combination for the given Exam
 //
 public int getNoOfQuestions(Paper pq)
 {
     try
     {
         cmd = new SqlCommand("select No_Of_Questions from SetPaper where Exam_ID='" + pq.exam_ID + "' and Section ='" + pq.section + "' and Format = '" + pq.format + "'", conn);
         conn.Open();
         int i = (int)cmd.ExecuteScalar();
         conn.Close();
         return i;
     }
     catch (SqlException e)
     {
         conn.Close();
         return 0;
     }
     catch(Exception e)
     {
         conn.Close();
         return 0;
     }
 }