/// <summary>
 /// This method populates the controls on the page with values
 /// from the passed BehaviorIncident object
 /// </summary>
 /// <param name="boq">The BehaviorIncident object to fill the page controls</param>
 private void PopulatePage(Models.BehaviorIncident bi)
 {
     //Fill the controls from the object
     deIncidentDatetime.Value           = bi.IncidentDatetime;
     ddChild.SelectedItem               = ddChild.Items.FindByValue(bi.ChildFK);
     ddClassroom.SelectedItem           = ddClassroom.Items.FindByValue(bi.ClassroomFK);
     txtBehaviorDescription.Value       = bi.BehaviorDescription;
     ddProblemBehavior.SelectedItem     = ddProblemBehavior.Items.FindByValue(bi.ProblemBehaviorCodeFK);
     txtProblemBehaviorSpecify.Value    = bi.ProblemBehaviorSpecify;
     ddActivity.SelectedItem            = ddActivity.Items.FindByValue(bi.ActivityCodeFK);
     txtActivitySpecify.Value           = bi.ActivitySpecify;
     ddOthersInvolved.SelectedItem      = ddOthersInvolved.Items.FindByValue(bi.OthersInvolvedCodeFK);
     txtOthersInvolvedSpecify.Value     = bi.OthersInvolvedSpecify;
     ddPossibleMotivation.SelectedItem  = ddPossibleMotivation.Items.FindByValue(bi.PossibleMotivationCodeFK);
     txtPossibleMotivationSpecify.Value = bi.PossibleMotivationSpecify;
     ddStrategyResponse.SelectedItem    = ddStrategyResponse.Items.FindByValue(bi.StrategyResponseCodeFK);
     txtStrategyResponseSpecify.Value   = bi.StrategyResponseSpecify;
     ddAdminFollowUp.SelectedItem       = ddAdminFollowUp.Items.FindByValue(bi.AdminFollowUpCodeFK);
     txtAdminFollowUpSpecify.Value      = bi.AdminFollowUpSpecify;
     txtNotes.Value = bi.Notes;
 }
        /// <summary>
        /// This method fires when the user clicks the Save button in the
        /// submitBehaviorIncident user control
        /// </summary>
        /// <param name="sender">The submitBehaviorIncident control</param>
        /// <param name="e">The Click event</param>
        protected void submitBehaviorIncident_Click(object sender, EventArgs e)
        {
            if (currentProgramRole.AllowedToEdit.Value)
            {
                //To hold the success message
                string successMessageType = null;

                //Fill the fields of the object from the form
                currentBehaviorIncident.IncidentDatetime          = Convert.ToDateTime(deIncidentDatetime.Value);
                currentBehaviorIncident.BehaviorDescription       = txtBehaviorDescription.Value.ToString();
                currentBehaviorIncident.ProblemBehaviorCodeFK     = Convert.ToInt32(ddProblemBehavior.Value);
                currentBehaviorIncident.ProblemBehaviorSpecify    = (txtProblemBehaviorSpecify.Value == null ? null : txtProblemBehaviorSpecify.Value.ToString());
                currentBehaviorIncident.ActivityCodeFK            = Convert.ToInt32(ddActivity.Value);
                currentBehaviorIncident.ActivitySpecify           = (txtActivitySpecify.Value == null ? null : txtActivitySpecify.Value.ToString());
                currentBehaviorIncident.OthersInvolvedCodeFK      = Convert.ToInt32(ddOthersInvolved.Value);
                currentBehaviorIncident.OthersInvolvedSpecify     = (txtOthersInvolvedSpecify.Value == null ? null : txtOthersInvolvedSpecify.Value.ToString());
                currentBehaviorIncident.PossibleMotivationCodeFK  = Convert.ToInt32(ddPossibleMotivation.Value);
                currentBehaviorIncident.PossibleMotivationSpecify = (txtPossibleMotivationSpecify.Value == null ? null : txtPossibleMotivationSpecify.Value.ToString());
                currentBehaviorIncident.StrategyResponseCodeFK    = Convert.ToInt32(ddStrategyResponse.Value);
                currentBehaviorIncident.StrategyResponseSpecify   = (txtStrategyResponseSpecify.Value == null ? null : txtStrategyResponseSpecify.Value.ToString());
                currentBehaviorIncident.AdminFollowUpCodeFK       = Convert.ToInt32(ddAdminFollowUp.Value);
                currentBehaviorIncident.AdminFollowUpSpecify      = (txtAdminFollowUpSpecify.Value == null ? null : txtAdminFollowUpSpecify.Value.ToString());
                currentBehaviorIncident.Notes       = (txtNotes.Value == null ? null : txtNotes.Value.ToString());
                currentBehaviorIncident.ChildFK     = Convert.ToInt32(ddChild.Value);
                currentBehaviorIncident.ClassroomFK = Convert.ToInt32(ddClassroom.Value);

                //Check to see if this is an add or edit
                if (behaviorIncidentPK > 0)
                {
                    using (PyramidContext context = new PyramidContext())
                    {
                        //This is an edit
                        successMessageType = "BehaviorIncidentEdited";

                        //Fill the edit-specific fields
                        currentBehaviorIncident.EditDate = DateTime.Now;
                        currentBehaviorIncident.Editor   = User.Identity.Name;

                        //Get the existing database values
                        Models.BehaviorIncident existingBehaviorIncident = context.BehaviorIncident.Find(currentBehaviorIncident.BehaviorIncidentPK);

                        //Set the behavior incident object to the new values
                        context.Entry(existingBehaviorIncident).CurrentValues.SetValues(currentBehaviorIncident);

                        //Save the changes
                        context.SaveChanges();
                    }

                    //Redirect the user to the dashboard with the success message
                    Response.Redirect(string.Format("/Pages/BehaviorIncidentDashboard.aspx?messageType={0}", successMessageType));
                }
                else
                {
                    using (PyramidContext context = new PyramidContext())
                    {
                        //This is an add
                        successMessageType = "BehaviorIncidentAdded";

                        //Set the create-specific fields
                        currentBehaviorIncident.CreateDate = DateTime.Now;
                        currentBehaviorIncident.Creator    = User.Identity.Name;

                        //Add the behavior incident to the database and save
                        context.BehaviorIncident.Add(currentBehaviorIncident);
                        context.SaveChanges();
                    }

                    //Redirect the user to the dashboard with the success message
                    Response.Redirect(string.Format("/Pages/BehaviorIncidentDashboard.aspx?messageType={0}", successMessageType));
                }
            }
            else
            {
                msgSys.ShowMessageToUser("danger", "Error", "You are not authorized to make changes!", 120000);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Get the user's current program role
            currentProgramRole = Utilities.GetProgramRoleFromSession(Session);

            //Don't allow aggregate viewers into this page
            if (currentProgramRole.RoleFK.Value == (int)Utilities.ProgramRoleFKs.AGGREGATE_DATA_VIEWER)
            {
                Response.Redirect("/Pages/BehaviorIncidentDashboard.aspx?messageType=NotAuthorized");
            }

            //Get the BehaviorIncident PK from the query string
            if (!string.IsNullOrWhiteSpace(Request.QueryString["BehaviorIncidentPK"]))
            {
                int.TryParse(Request.QueryString["BehaviorIncidentPK"], out behaviorIncidentPK);
            }

            //Get the Behavior Incident from the database
            using (PyramidContext context = new PyramidContext())
            {
                //Get the Behavior Incident
                currentBehaviorIncident = context.BehaviorIncident
                                          .AsNoTracking()
                                          .Include(bi => bi.Classroom)
                                          .Include(bi => bi.Classroom.Program)
                                          .Where(bi => bi.BehaviorIncidentPK == behaviorIncidentPK)
                                          .FirstOrDefault();

                //If the Behavior Incident is null (this is an add)
                if (currentBehaviorIncident == null)
                {
                    //Set the current Behavior Incident to a blank Behavior Incident
                    currentBehaviorIncident = new Models.BehaviorIncident();

                    //Set the program label to the current user's program
                    lblProgram.Text = currentProgramRole.ProgramName;
                }
                else
                {
                    //Set the program label to the form's program
                    lblProgram.Text = currentBehaviorIncident.Classroom.Program.ProgramName;
                }
            }

            //Don't allow users to view Behavior Incidents from other programs
            if (currentBehaviorIncident.BehaviorIncidentPK > 0 && !currentProgramRole.ProgramFKs.Contains(currentBehaviorIncident.Classroom.ProgramFK))
            {
                //Redirect the user to the dashboard with an error message
                Response.Redirect(string.Format("/Pages/BehaviorIncidentDashboard.aspx?messageType={0}", "NoBehaviorIncident"));
            }

            //Get the proper program fk
            programFK = (currentBehaviorIncident.BehaviorIncidentPK > 0 ? currentBehaviorIncident.Classroom.ProgramFK : currentProgramRole.CurrentProgramFK.Value);

            //Set the max value for the incident datetime date edit
            deIncidentDatetime.MaxDate = DateTime.Now;

            if (!IsPostBack)
            {
                //Hide the master page title
                ((Dashboard)this.Master).HideTitle();

                //Bind the dropdowns
                BindDropDowns();

                //If this is an edit or view, populate the page with values
                if (behaviorIncidentPK != 0)
                {
                    PopulatePage(currentBehaviorIncident);
                }
                else
                {
                    ddChild.ReadOnly = true;
                }

                //Get the action
                string action;
                if (Request.QueryString["action"] != null)
                {
                    action = Request.QueryString["action"];
                }
                else
                {
                    action = "View";
                }

                //Allow adding/editing depending on the user's role and the action
                if (currentBehaviorIncident.BehaviorIncidentPK == 0 && currentProgramRole.AllowedToEdit.Value)
                {
                    //Show the submit button
                    submitBehaviorIncident.ShowSubmitButton = true;

                    //Show other controls
                    hfViewOnly.Value = "False";

                    //Lock the controls
                    EnableControls(true);

                    //Set the page title
                    lblPageTitle.Text = "Add New Behavior Incident Report";
                }
                else if (currentBehaviorIncident.BehaviorIncidentPK > 0 && action.ToLower() == "edit" && currentProgramRole.AllowedToEdit.Value)
                {
                    //Show the submit button
                    submitBehaviorIncident.ShowSubmitButton = true;

                    //Show other controls
                    hfViewOnly.Value = "False";

                    //Lock the controls
                    EnableControls(true);

                    //Set the page title
                    lblPageTitle.Text = "Edit Behavior Incident Report";
                }
                else
                {
                    //Hide the submit button
                    submitBehaviorIncident.ShowSubmitButton = false;

                    //Hide other controls
                    hfViewOnly.Value = "True";

                    //Lock the controls
                    EnableControls(false);

                    //Set the page title
                    lblPageTitle.Text = "View Behavior Incident Report";
                }

                //Set focus on the incident datetime field
                deIncidentDatetime.Focus();
            }
        }
        /// <summary>
        /// This method executes when the user clicks the delete button for a Behavior Incident
        /// and it deletes the Behavior Incident information from the database
        /// </summary>
        /// <param name="sender">The lbDeleteBehaviorIncident LinkButton</param>
        /// <param name="e">The Click event</param>
        protected void lbDeleteBehaviorIncident_Click(object sender, EventArgs e)
        {
            if (currentProgramRole.AllowedToEdit.Value)
            {
                //Get the PK from the hidden field
                int?removeBehaviorIncidentPK = (String.IsNullOrWhiteSpace(hfDeleteBehaviorIncidentPK.Value) ? (int?)null : Convert.ToInt32(hfDeleteBehaviorIncidentPK.Value));

                //Remove the role if the PK is not null
                if (removeBehaviorIncidentPK != null)
                {
                    try
                    {
                        using (PyramidContext context = new PyramidContext())
                        {
                            //Get the Behavior Incident program row to remove
                            Models.BehaviorIncident behaviorIncidentToRemove = context.BehaviorIncident.Find(removeBehaviorIncidentPK);

                            //Remove the Behavior Incident
                            context.BehaviorIncident.Remove(behaviorIncidentToRemove);
                            context.SaveChanges();

                            //Show a success message
                            msgSys.ShowMessageToUser("success", "Success", "Successfully deleted Behavior Incident Report!", 10000);
                        }
                    }
                    catch (DbUpdateException dbUpdateEx)
                    {
                        //Check if it is a foreign key error
                        if (dbUpdateEx.InnerException?.InnerException is SqlException)
                        {
                            //If it is a foreign key error, display a custom message
                            SqlException sqlEx = (SqlException)dbUpdateEx.InnerException.InnerException;
                            if (sqlEx.Number == 547)
                            {
                                msgSys.ShowMessageToUser("danger", "Error", "Could not delete the Behavior Incident Report, there are related records in the system!<br/><br/>If you do not know what related records exist, please contact tech support via ticket.", 120000);
                            }
                            else
                            {
                                msgSys.ShowMessageToUser("danger", "Error", "An error occurred while deleting the Behavior Incident Report!", 120000);
                            }
                        }
                        else
                        {
                            msgSys.ShowMessageToUser("danger", "Error", "An error occurred while deleting the Behavior Incident Report!", 120000);
                        }

                        //Log the error
                        Elmah.ErrorSignal.FromCurrentContext().Raise(dbUpdateEx);
                    }

                    //Rebind the Behavior Incident controls
                    bsGRBehaviorIncidents.DataBind();

                    //Bind the chart
                    BindProblemBehaviorChart();
                }
                else
                {
                    msgSys.ShowMessageToUser("danger", "Error", "Could not find the Behavior Incident Report to delete!", 120000);
                }
            }
            else
            {
                msgSys.ShowMessageToUser("danger", "Error", "You are not authorized to make changes!", 120000);
            }
        }