protected void ListBox_Rooms_SelectedIndexChanged(object sender, EventArgs e)
        {
            int     n    = 0;
            ListBox lb   = (ListBox)sender;
            int     nmax = (int)ViewState["MaxDesksRequired"];

            foreach (ListItem l in lb.Items)
            {
                if (l.Selected)
                {
                    ExamRoom er = new ExamRoom(); er.Load(new Guid(l.Value));
                    n += er.m_capacity;
                }
            }
            Label_RoomsAllcation.Text = "Allocated : " + n.ToString() + "  Needed: " + nmax.ToString();
            SetupRulesBoxesRooms();
        }
        protected bool AllocateDesksRoom(Guid roomid, DateTime t1, DateTime t2, ref string ErrorS)
        {
            ScheduledComponentList scl2 = new ScheduledComponentList();

            scl2.LoadList_Room(t1, t2, roomid, " ORDER BY DateTime ASC, TimeAllowed DESC, ComponentId DESC, StudentExamNumber ASC");
            if (scl2.m_List.Count == 0)
            {
                return(true);
            }
            ExamRoom               exr1 = new ExamRoom(); exr1.Load(roomid);
            SimpleRoom             room1 = new SimpleRoom(); room1.Load(roomid.ToString());
            ScheduledComponentList scl3 = new ScheduledComponentList();//used to check room empty below
            string             s = ""; bool found = false;
            int                column = 1; int desk = 1; int desk_inc = 1;
            DateTime           time_last     = new DateTime(2000, 1, 1);
            DateTime           time_first    = new DateTime(2000, 1, 1);
            bool               room_full     = false;
            int                no_components = 1;
            ScheduledComponent scX           = new ScheduledComponent();

            scX = (ScheduledComponent)scl2.m_List[0];
            foreach (ScheduledComponent sc in scl2.m_List)
            {
                if (scX.m_ComponentId != sc.m_ComponentId)
                {
                    scX = sc; no_components++;
                }
            }

            int Free_space_min = (exr1.m_capacity - scl2.m_List.Count) / no_components;

            //when we enter no deska allocated to this room so exr1.m_capacity is capacity
            //if we have n students and m components and (capacity -n)> m then we can try to insert gaps...
            // n< scl2.count ( might have later components...


            scX = (ScheduledComponent)scl2.m_List[0];
            foreach (ScheduledComponent sc in scl2.m_List)
            {
                if (scX.m_ComponentId != sc.m_ComponentId)
                {
                    //new component...
                    scX = sc;
                    //if space insert blamk row
                    if ((exr1.columns[column].count < Free_space_min) && (CheckBox1.Checked))
                    {
                        desk = 1; column++; column++;
                    }
                }
                if ((sc.m_Date > time_last) && ((column != 1) || (desk != 1)))
                {
                    scl3.LoadList_Room(sc.m_Date.AddMinutes(-10), sc.m_Date, roomid, "");
                    if (scl3.m_List.Count == 0)
                    {
                        //DialogResult d = MessageBox.Show("It looks as if we can reset the desk alocations at " + sc.m_Date.ToShortTimeString() + ". Are you sure you wna to do this... ie do we have two separate internal exmas in the same session?", "Warning while rooming " + room1.m_roomcode, MessageBoxButtons.YesNo);
                        //if (d == DialogResult.Yes)
                        {
                            column     = 1; desk = 1; desk_inc = 1;
                            time_last  = sc.m_Date.AddMinutes(sc.m_TimeAllowed);
                            time_first = sc.m_Date.AddMinutes(-1);
                        }
                    }
                }

                if (sc.m_Date.AddMinutes(sc.m_TimeAllowed) > time_last)
                {
                    time_last = sc.m_Date.AddMinutes(sc.m_TimeAllowed);
                }

                //assign the lad a desk.....
                //unless he already has one!!!!

                found = false;
                s     = exr1.columns[column].name + desk.ToString();
                foreach (ScheduledComponent sc1 in scl2.m_List)
                {
                    if ((sc1.m_StudentId == sc.m_StudentId) && (sc1.m_Date > time_first))
                    {
                        if (sc1.m_Desk != "")
                        {
                            s = sc1.m_Desk; found = true; break;//he already had  one
                        }
                    }
                }

                sc.m_Desk = s;
                if (!found)
                {//we have added one....
                    if (room_full)
                    {
                        ErrorS = "Room capacity exceeded....." + sc.m_ExamNumber.ToString() + ":" + sc.m_Surname + " " + sc.m_Givenname + "..." + sc.m_ComponentTitle;
                        return(false);
                    }
                    desk = desk + desk_inc;
                    if (desk > exr1.columns[column].count)
                    {
                        column++;
                        desk     = exr1.columns[column].count;
                        desk_inc = desk_inc * (-1);
                    }
                    if (desk < 1)
                    {
                        desk_inc = desk_inc * (-1);
                        desk     = 1;
                        column++;
                    }
                }
                sc.Save();
                //check if we have exceeded capacity!
                if (column > exr1.no_columns + 1)
                {
                    room_full = true;
                }
            }
            return(true);
        }
        private void UpdateDeskGrid()
        {
            DateTime t1 = System.Convert.ToDateTime(DropDownListDeskTimes.SelectedValue);
            string   s1 = "";

            string   dateS = Request.QueryString["Date"];
            DateTime t0    = new DateTime();
            string   sess  = Request.QueryString["Session"];
            bool     Is_AM = true;

            try
            {
                t0 = Convert.ToDateTime(Request.QueryString["Date"]);
                if (sess.Contains("PM"))
                {
                    Is_AM = false;
                }
                ViewState["Session_is_AM"] = Is_AM;
                ViewState["EditDate"]      = t0;
            }
            catch
            {
                //try to get from session state?
                Is_AM = (bool)ViewState["Session_is_AM"];
                t0    = (DateTime)ViewState["EditDate"];
            }
            DateTime t2 = new DateTime();

            t2 = (Is_AM) ? t0.AddHours(13) : t0.AddHours(18);

            System.Drawing.Color[] cell_colours = GetColors();

            Guid[] papers = new Guid[10]; string[] paper_title = new string[10];
            string s         = "";
            int    no_papers = 0;
            bool   found     = false;

            Label_DeskDate.Text = t1.ToLongDateString();



            ScheduledComponentList scl2 = new ScheduledComponentList(); scl2.LoadList(t0, t2);

            scl2.LoadList_orderbyComponent(t0, t2);
            //need to restrict to those current
            ScheduledComponentList scl1 = new ScheduledComponentList();

            foreach (ScheduledComponent sc in scl2.m_List)
            {
                if (sc.m_Date.AddMinutes(sc.m_TimeAllowed) > t1)
                {
                    scl1.m_List.Add(sc);
                }
            }


            t0 = System.Convert.ToDateTime(DropDownListDeskTimes.SelectedValue);

            TableDeskView.Rows.Clear();

            Guid Current_Room = new Guid();

            Current_Room = new Guid(DropDownListDeskRooms.SelectedValue);
            if (Current_Room == Guid.Empty)
            {
                return;
            }
            ExamRoom exr1 = new ExamRoom(); exr1.Load(Current_Room);
            int      nrows = 0; int ncols = 0;

            foreach (ExamColumn ec in exr1.columns)
            {
                if (ec.count > nrows)
                {
                    nrows = ec.count;
                }
            }
            TableDeskView.CssClass = "EventsTable";
            TableRow r0 = new TableRow();

            TableDeskView.Rows.Add(r0);
            TableCell c3 = new TableCell(); r0.Cells.Add(c3); ncols++;

            foreach (ExamColumn ec in exr1.columns)
            {
                if (ec.count > 0)
                {
                    TableCell c = new TableCell();
                    c.Width = 40; c.Text = ec.name;//header row
                    r0.Cells.Add(c); ncols++;
                }
            }
            TableCell c4 = new TableCell(); r0.Cells.Add(c4);
            TableCell c2 = new TableCell();

            r0.Cells.Add(c2);
            c2.Text  = "Colour Code for Papers";
            c2.Width = 200;

            //for (int i = 0; i < nrows; i++)
            for (int i = nrows - 1; i > -1; i--)
            {
                TableRow r = new TableRow();
                TableDeskView.Rows.Add(r);

                TableCell c1 = new TableCell(); c1.Text = (i + 1).ToString(); r.Cells.Add(c1);
                c1.Width = 40; c1.BackColor = System.Drawing.Color.LightGray;
                foreach (ExamColumn ec in exr1.columns)
                {
                    if (ec.count > 0)
                    {
                        TableCell c = new TableCell();
                        c.Width = 40; c.Text = "";
                        r.Cells.Add(c);
                    }
                }
                TableCell c5 = new TableCell(); r.Cells.Add(c5); c5.Width = 40;
                TableCell c6 = new TableCell(); r.Cells.Add(c6); c6.Width = 40;
            }
            t0 = t0.AddMinutes(2);

            try
            {
                s1 = TableDeskView.Rows[1].Cells[1].Text;
            }
            catch { }

            foreach (ScheduledComponent sc in scl1.m_List)
            {
                if ((Current_Room == sc.m_RoomId))
                {
                    if ((sc.m_Date < t0) && (sc.m_Date.AddMinutes(sc.m_TimeAllowed) > t0))
                    {
                        s = sc.m_Desk;

                        if ((s != "") && (s != null))
                        {
                            int col = 0;
                            foreach (TableCell tc in TableDeskView.Rows[0].Cells)
                            {
                                if (tc.Text == s.Substring(0, 1))
                                {
                                    col = TableDeskView.Rows[0].Cells.GetCellIndex(tc);
                                    break;
                                }
                            }
                            int row = System.Convert.ToInt32(s.Substring(1));
                            row = nrows + 1 - row;

                            TableDeskView.Rows[row].Cells[col].Text = sc.m_ExamNumber.ToString();


                            found = false;
                            for (int i = 0; i < no_papers; i++)
                            {
                                if (papers[i] == sc.m_ComponentId)
                                {
                                    found = true;
                                    TableDeskView.Rows[row].Cells[col].BackColor = cell_colours[i];
                                }
                            }
                            if (!found)
                            {
                                no_papers++;
                                papers[no_papers - 1] = sc.m_ComponentId;
                                TableDeskView.Rows[row].Cells[col].BackColor = cell_colours[no_papers - 1];
                                paper_title[no_papers - 1] = sc.m_ComponentCode + ":" + sc.m_ComponentTitle;
                            }
                        }
                    }
                }
            }



            for (int i = 0; i < no_papers; i++)
            {
                TableDeskView.Rows[i + 1].Cells[ncols + 1].Text      = paper_title[i];
                TableDeskView.Rows[i + 1].Cells[ncols + 1].BackColor = cell_colours[i];
            }
        }
        protected bool Apply_Rule(string rule, Guid rule_roomId, ScheduledComponentList scl1, ref string ErrorS, List <Guid> Components, List <int> number, ref int RoomCapacity)
        {
            int      n  = 0;
            ExamRoom er = new ExamRoom();

            switch (rule)
            {
            case "None": break;

            case "ExtraTime":
                n = 0;
                ExamComponent ec1 = new ExamComponent(); int time1 = 0;
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    ec1.Load(c.m_ComponentId); time1 = Convert.ToInt32(ec1.m_Time);
                    if ((c.m_TimeAllowed > time1) && (c.m_RoomId == Guid.Empty))
                    {
                        n++;
                    }
                }
                er.Load(rule_roomId);
                if (n > er.m_capacity)
                {
                    ErrorS = "Rule" + rule + " Exceeds capacity in" + DropDownList_Rule1Room.Text; return(false);
                }
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    ec1.Load(c.m_ComponentId); time1 = Convert.ToInt32(ec1.m_Time);
                    if ((c.m_TimeAllowed > time1) && (c.m_RoomId == Guid.Empty))
                    {
                        c.m_RoomId  = rule_roomId;
                        c.Save(); n = 0; RoomCapacity--;
                        foreach (Guid d in Components)
                        {
                            if (d == c.m_ComponentId)
                            {
                                number[n]--;
                            }
                            n++;
                        }
                    }
                }
                break;

            case "Typists":
                n = 0;
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    if ((c.m_Will_Type) && (c.m_RoomId == Guid.Empty))
                    {
                        n++;
                    }
                }
                er.Load(rule_roomId);
                if (n > er.m_capacity)
                {
                    ErrorS = "Rule" + rule + " Exceeds capacity in" + DropDownList_Rule1Room.Text; return(false);
                }
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    if ((c.m_Will_Type) && (c.m_RoomId == Guid.Empty))
                    {
                        c.m_RoomId  = rule_roomId;
                        c.Save(); n = 0; RoomCapacity--;
                        foreach (Guid d in Components)
                        {
                            if (d == c.m_ComponentId)
                            {
                                number[n]--;
                            }
                            n++;
                        }
                    }
                }
                break;

            default:
                //it is a rule based on a component
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    if ((c.m_ComponentCode == rule) && (c.m_RoomId == Guid.Empty))
                    {
                        n++;
                    }
                }
                er.Load(rule_roomId);
                if (n > er.m_capacity)
                {
                    ErrorS = "Rule" + rule + " Exceeds capacity in" + DropDownList_Rule1Room.Text; return(false);
                }
                foreach (ScheduledComponent c in scl1.m_List)
                {
                    if ((c.m_ComponentCode == rule) && (c.m_RoomId == Guid.Empty))
                    {
                        c.m_RoomId  = rule_roomId;
                        c.Save(); n = 0; RoomCapacity--;
                        foreach (Guid d in Components)
                        {
                            if (d == c.m_ComponentId)
                            {
                                number[n]--;
                            }
                            n++;
                        }
                    }
                }
                break;
            }
            ErrorS += "Success_Rule1";
            return(true);
        }
        protected void Button_Assign_Click(object sender, EventArgs e)
        {
            //now we are actually going to do it???

            string   ErrorS = "Success!";
            bool     Is_AM  = (bool)ViewState["Session_is_AM"];
            DateTime t0     = new DateTime();

            t0 = (DateTime)ViewState["EditDate"];
            DateTime t1 = new DateTime();
            DateTime t2 = new DateTime();

            t1 = (Is_AM) ? t0.AddHours(8) : t0.AddHours(13);
            t2 = (Is_AM) ? t0.AddHours(13) : t0.AddHours(18);
            DateTime time_last = new DateTime();



            List <Guid> Rooms = new List <Guid>();
            ListBox     lb    = ListBox_Rooms;

            foreach (ListItem l in lb.Items)
            {
                if (l.Selected)
                {
                    Rooms.Add(new Guid(l.Value));
                }
            }

            //if no rooms allocated flag error
            if (Rooms.Count == 0)
            {
                ErrorS = "...you haven't allocated Any rooms";
                goto ErrorExit;
            }


            ExamsUtility eu = new ExamsUtility();

            eu.ClearDeskAssignments(t1, t2);

            //ought to clear all room allocations first...
            //ought to do this by query
            int          n = 0;
            ExamsUtility u = new ExamsUtility();

            u.ClearRoomAssignments(t1, t2);

            ExamRoom er = new ExamRoom();

            n = 0;
            List <int> Room_Capacity = new List <int>();

            foreach (Guid d in Rooms)
            {
                er.Load(d);
                Room_Capacity.Add(er.m_capacity);
                n++;
            }
            int nmax = n - 1;

            ScheduledComponentList scl1 = new ScheduledComponentList();

            scl1.LoadList_Date(t1, t2);                              //order by  DateTime
            time_last = ((ScheduledComponent)scl1.m_List[0]).m_Date;
            string s = GetQueryStringDay(t0.Year, t0.Month, t0.Day); // gets from sc ordered by datetime,NUMBER

            List <Guid>     Components    = new List <Guid>();
            List <int>      number        = new List <int>();
            List <DateTime> Start_Time    = new List <DateTime>();
            Encode          en            = new Encode();
            string          db_connection = en.GetDbConnection();

            using (SqlConnection cn = new SqlConnection(db_connection))
            {
                cn.Open();
                using (SqlCommand cm = new SqlCommand(s, cn))
                {
                    using (SqlDataReader dr = cm.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            Components.Add(dr.GetGuid(1));
                            number.Add(dr.GetInt32(4));
                            Start_Time.Add(dr.GetDateTime(3));
                        }
                        dr.Close();
                    }
                }
                cn.Close();
            }

            //first apply rules... hopefully these will fit ... if not flag error back to ui

            int CurrentRoomCapacity = 0;

            string s_rule      = DropDownList_Rule1Source.SelectedItem.Text;
            Guid   rule_roomId = new Guid(DropDownList_Rule1Room.SelectedValue);

            n = 0; foreach (Guid d in Rooms)
            {
                if (d == rule_roomId)
                {
                    CurrentRoomCapacity = Room_Capacity[n]; break;
                }
            }
            if (!Apply_Rule(s_rule, rule_roomId, scl1, ref ErrorS, Components, number, ref CurrentRoomCapacity))
            {
                goto ErrorExit;
            }
            Room_Capacity[n] = CurrentRoomCapacity;
            if ((s_rule != "None") && (CheckBox1.Checked))
            {
                Rooms.Remove(rule_roomId); nmax--;
            }


            s_rule      = DropDownList_Rule2Source.SelectedItem.Text;
            rule_roomId = new Guid(DropDownList_Rule2Room.SelectedValue);
            n           = 0; foreach (Guid d in Rooms)
            {
                if (d == rule_roomId)
                {
                    CurrentRoomCapacity = Room_Capacity[n]; break;
                }
            }
            if (!Apply_Rule(s_rule, rule_roomId, scl1, ref ErrorS, Components, number, ref CurrentRoomCapacity))
            {
                goto ErrorExit;
            }
            if ((s_rule != "None") && (CheckBox2.Checked))
            {
                Rooms.Remove(rule_roomId); nmax--;
            }
            Room_Capacity[n] = CurrentRoomCapacity;


            s_rule      = DropDownList_Rule3Source.SelectedItem.Text;
            rule_roomId = new Guid(DropDownList_Rule3Room.SelectedValue);
            n           = 0; foreach (Guid d in Rooms)
            {
                if (d == rule_roomId)
                {
                    CurrentRoomCapacity = Room_Capacity[n]; break;
                }
            }
            if (!Apply_Rule(s_rule, rule_roomId, scl1, ref ErrorS, Components, number, ref CurrentRoomCapacity))
            {
                goto ErrorExit;
            }
            if ((s_rule != "None") && (CheckBox3.Checked))
            {
                Rooms.Remove(rule_roomId); nmax--;
            }
            Room_Capacity[n] = CurrentRoomCapacity;



            s_rule      = DropDownList_Rule4Source.SelectedItem.Text;
            rule_roomId = new Guid(DropDownList_Rule4Room.SelectedValue);
            n           = 0; foreach (Guid d in Rooms)
            {
                if (d == rule_roomId)
                {
                    CurrentRoomCapacity = Room_Capacity[n]; break;
                }
            }
            if (!Apply_Rule(s_rule, rule_roomId, scl1, ref ErrorS, Components, number, ref CurrentRoomCapacity))
            {
                goto ErrorExit;
            }
            if ((s_rule != "None") && (CheckBox4.Checked))
            {
                Rooms.Remove(rule_roomId); nmax--;
            }
            Room_Capacity[n] = CurrentRoomCapacity;



            s_rule      = DropDownList_Rule5Source.SelectedItem.Text;
            rule_roomId = new Guid(DropDownList_Rule5Room.SelectedValue);
            n           = 0; foreach (Guid d in Rooms)
            {
                if (d == rule_roomId)
                {
                    CurrentRoomCapacity = Room_Capacity[n]; break;
                }
            }
            if (!Apply_Rule(s_rule, rule_roomId, scl1, ref ErrorS, Components, number, ref CurrentRoomCapacity))
            {
                goto ErrorExit;
            }
            if ((s_rule != "None") && (CheckBox5.Checked))
            {
                Rooms.Remove(rule_roomId); nmax--;
            }
            Room_Capacity[n] = CurrentRoomCapacity;


            ScheduledComponentList scl2 = new ScheduledComponentList();

            foreach (ScheduledComponent c in scl1.m_List)
            {
                if (c.m_RoomId == Guid.Empty)
                {
                    scl2.m_List.Add(c);
                }
            }

            //now we apply the rest
            //idea is we find the sc with most students.... and put into biggest room first
            //first correct room capacity?
            n = 0;
            // well i think we have all the information....
            //going to assign biggest exam to biggest room first

            int index = 0;

            foreach (Guid d in Components)
            {
                //so new component....
                //if there is a complete gap before we start this component we can clear room allocations....
                //find the first (earliest) scheduled component
                foreach (ScheduledComponent c in scl2.m_List)
                {
                    if (c.m_ComponentId == d)
                    {
                        if (c.m_RoomId == Guid.Empty)
                        {
                            if (c.m_Date > time_last.AddMinutes(10))
                            {
                                //so this one starts at least 10 minutes after all sofar have finished....
                                time_last = c.m_Date.AddMinutes(c.m_TimeAllowed);
                                //so can reset rooms..... ie back to full capacity?
                                Room_Capacity.Clear(); n = 0;
                                foreach (Guid d1 in Rooms)
                                {
                                    er.Load(d1);
                                    Room_Capacity.Add(er.m_capacity);
                                    n++;
                                }
                                nmax = n - 1;
                            }
                        }
                    }
                }

                n = 0;
                while ((Room_Capacity[n] == 0) && (n <= nmax))
                {
                    n++;
                }
                if (n > nmax)
                {
                    ErrorS = "Ran out of room capacity !!"; goto ErrorExit;
                }
                //going to check if next one will fit in any room we have available... if so use it!  search smallest first?
                for (int i = nmax; i >= 0; i--)
                {
                    if (Room_Capacity[i] >= number[index])
                    {
                        n = i; break;
                    }
                }
                foreach (ScheduledComponent c in scl2.m_List)
                {
                    if (c.m_ComponentId == d)
                    {
                        if (c.m_RoomId == Guid.Empty)
                        {
                            if (c.m_Date.AddMinutes(c.m_TimeAllowed) > time_last)
                            {
                                time_last = c.m_Date.AddMinutes(c.m_TimeAllowed);
                            }

                            //really ought to check to see if he has any other componets in this session and assign the same room/...

                            foreach (ScheduledComponent c1 in scl1.m_List)
                            {
                                if (c1.m_StudentId == c.m_StudentId)
                                {
                                    c.m_RoomId = c1.m_RoomId;
                                }
                            }
                            if (c.m_RoomId == Guid.Empty)
                            {
                                c.m_RoomId = Rooms[n];
                                Room_Capacity[n]--;
                            }

                            c.Save();



                            foreach (ScheduledComponent c1 in scl2.m_List)
                            {
                                if ((c1.m_StudentId == c.m_StudentId) && (c1.m_RoomId == Guid.Empty))
                                {
                                    c.m_RoomId = Rooms[n];
                                    c.Save();
                                    //Room_Capacity[n]--;   should already have cleared clashes
                                }
                            }
                        }
                    }
                    while ((Room_Capacity[n] == 0) && (n < nmax))
                    {
                        n++;
                    }
                    if (n > nmax)
                    {
                        ErrorS = "Ran out of room capacity !!"; goto ErrorExit;
                    }
                }
                index++;
            }
            //check??
            //success;  open the summary panel

            Panel_left1.Visible             = false; Panel_right1.Visible = false;
            Label_message.Text              = "Rooms Allocated Successfully.";
            Label_message.Visible           = true;
            SqlDataSource3.SelectCommand    = GetQueryStringRoomSummary(t1, t2, true);
            SqlDataSource3.ConnectionString = en.GetDbConnection();
            SqlDataSource3.DataBind();
            return;

            ErrorExit : Label_message.Text = ErrorS;
            Label_message.BackColor        = System.Drawing.Color.Red;
            return;
        }