protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Patron"] == null)
                {
                    Response.Redirect("/");
                }
                var patron = (Patron)Session["Patron"];
                lblPID.Text = patron.PID.ToString();
                var prog = Programs.FetchObject(patron.ProgID);
                lblPGID.Text      = prog.PID.ToString();
                pnlReview.Visible = prog.PatronReviewFlag;

                // Load the Activity Types to log

                foreach (ActivityType val in Enum.GetValues(typeof(ActivityType)))
                {
                    var pgc = ProgramGamePointConversion.FetchObjectByActivityId(prog.PID, (int)val);
                    if (pgc != null && pgc.PointCount > 0)
                    {
                        rbActivityType.Items.Add(new ListItem(val.ToString(), ((int)val).ToString()));
                    }
                }
                rbActivityType.SelectedIndex = 0;
            }
        }
Example #2
0
        protected void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Session["SA"] = "0";
            if (e.CommandName == "pwd")
            {
                Session["SA"] = e.CommandArgument.ToString();
                Response.Redirect("~/Account/ChangeFamMemberPwd.aspx");
            }
            if (e.CommandName == "log")
            {
                Session["SA"] = e.CommandArgument.ToString();
                Response.Redirect("~/Account/EnterFamMemberLog.aspx");
            }
            if (e.CommandName == "login")
            {
                var newPID = int.Parse(e.CommandArgument.ToString());

                if ((int)Session["MasterAcctPID"] != newPID &&
                    !Patron.CanManageSubAccount((int)Session["MasterAcctPID"], newPID))
                {
                    // kick them out
                    Response.Redirect("~");
                }

                var newPatron = Patron.FetchObject(newPID);
                new SessionTools(Session).EstablishPatron(newPatron);


                var pgm = DAL.Programs.FetchObject(newPatron.ProgID);

                /* recalulate goal cache to accomdate changes in program length and point multipliers */
                ProgramGamePointConversion pgc = null;
                foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                {
                    int activityTypeId = (int)activityTypeValue;
                    var temp           = ProgramGamePointConversion.FetchObjectByActivityId(pgm.PID,
                                                                                            +activityTypeId);
                    if (temp != null && temp.PointCount > 0)
                    {
                        pgc = temp;
                    }
                }
                if (pgc != null)
                {
                    newPatron.RecalculateGoalCache(pgm, pgc);
                    newPatron.Update();
                }

                TestingBL.CheckPatronNeedsPreTest();
                TestingBL.CheckPatronNeedsPreTest();

                Response.Redirect("~");
            }
        }
        protected void Program_SelectedIndexChanged(object sender, EventArgs e)
        {
            int progID = FormatHelper.SafeToInt(((DropDownList)rptr.Items[0].FindControl("ProgID")).SelectedValue);

            if (progID == 0)
            {
                return; // no selection
            }

            var selectedProgram = Programs.FetchObject(progID);

            var goal = rptr.Items[0].FindControl("Goal") as TextBox;

            if (goal != null &&
                selectedProgram.GoalDefault > 0)
            {
                goal.Text = selectedProgram.GoalDefault.ToString();
            }

            // disable goal field when the user has a set goal
            ((TextBox)rptr.Items[0].FindControl("Goal")).Enabled = (selectedProgram.GoalMin != selectedProgram.GoalMax);


            // Goal needs to be modified by ProgramGamePointConversion
            /* If daily goal is enabled we need to find what method point system uses. Just select the first item that is relevant.. */
            foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
            {
                int activityTypeId = (int)activityTypeValue;
                var pgc            = ProgramGamePointConversion.FetchObjectByActivityId(progID,
                                                                                        activityTypeId);

                if (pgc != null && pgc.PointCount > 0)
                {
                    var range = (RangeValidator)rptr.Items[0].FindControl("GoalRangeValidator");

                    range.MinimumValue = selectedProgram.GoalMin.ToString();
                    range.MaximumValue = selectedProgram.GoalMax.ToString();
                    range.Text         = $"{range.MinimumValue}-{range.MaximumValue}";

                    /* save the activity type id */
                    ViewState["ActivityTypeId"] = activityTypeId.ToString();

                    var intervalString = selectedProgram.GetGoalInterval.ToString();

                    ((Literal)rptr.Items[0].FindControl("GoalLabel")).Text = $"{intervalString} Goal ({activityTypeValue.ToString()}):";
                    // found a valid point conversion for goal so break
                    break;
                }
            }
        }
Example #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var basePage = (BaseSRPPage)Page;

            if (!IsPostBack)
            {
                var patron = (Patron)Session["Patron"];
                rptr.DataSource = Patron.GetPatronForEdit(patron.PID);
                rptr.DataBind();

                Programs program = Programs.FetchObject(patron.ProgID);

                // Goal needs to be modified by ProgramGamePointConversion
                /* If daily goal is enabled we need to find what method point system uses. Just select the first item that is relevant.. */
                foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                {
                    int activityTypeId = (int)activityTypeValue;
                    var pgc            = ProgramGamePointConversion.FetchObjectByActivityId(patron.ProgID,
                                                                                            activityTypeId);

                    if (pgc != null && pgc.PointCount > 0)
                    {
                        var range = (RangeValidator)rptr.Items[0].FindControl("GoalRangeValidator");

                        range.MinimumValue = program.GoalMin.ToString();
                        range.MaximumValue = program.GoalMax.ToString();
                        range.Text         = $"{range.MinimumValue}-{range.MaximumValue}";

                        /* save the activity type id */
                        ViewState["ActivityTypeId"] = activityTypeId.ToString();

                        var intervalString = program.GetGoalInterval.ToString();

                        ((Label)rptr.Items[0].FindControl("GoalLabel")).Text = $"{intervalString} Goal ({activityTypeValue.ToString()})";
                        // found a valid point conversion for goal so break
                        break;
                    }
                }

                basePage.TranslateStrings(rptr);
                ReloadLibraryDistrict();
            }
            this.SaveButtonText = basePage.GetResourceString("family-member-add-save");
        }
        public void DoBusinessRulesNext(int curStep)
        {
            // code needs to have the steps in order for the ifs to flow properly on panels with now fields showing

            if (curStep == 1)
            {
                //get Age

                var sDOB   = ((TextBox)rptr.Items[0].FindControl("DOB")).Text;
                var sAge   = ((TextBox)rptr.Items[0].FindControl("Age")).Text;
                var sGrade = ((TextBox)rptr.Items[0].FindControl("SchoolGrade")).Text;

                var age = -1;
                if (!string.IsNullOrEmpty(sDOB))
                {
                    var DOB = DateTime.Parse(sDOB);
                    age = DateTime.Now.Year - DOB.Year;
                }
                else
                {
                    int.TryParse(sAge, out age);
                }

                RegistrationAge.Text = age.ToString();

                // Get Default Program for the Age
                // Set Program to that
                var grade = -1;
                if (sGrade.Length > 0)
                {
                    int.TryParse(sGrade, out grade);
                }

                var pgmDD = (DropDownList)rptr.Items[0].FindControl("ProgID");
                if (pgmDD.Items.Count == 2)
                {
                    // single program - just select the program
                    pgmDD.SelectedIndex = 1;
                }
                else if (pgmDD.SelectedValue == "0" || string.IsNullOrEmpty(pgmDD.SelectedValue))
                {
                    var defaultProgram = Programs.GetDefaultProgramForAgeAndGrade(age, grade).ToString();
                    if (pgmDD.Items.FindByValue(defaultProgram) != null)
                    {
                        pgmDD.SelectedValue = defaultProgram;
                    }
                }


                if (MasterPID.Text.Length > 0)    // Already registered the master account and now looping for family accounts
                {
                    var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                    var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 2).ToString());

                    curPanel.Visible = false;
                    newPanel.Visible = true;

                    Step.Text = (curStep + 2).ToString();
                }
                else
                {
                    if (age > 17 && SRPSettings.GetSettingValue("AllowFamilyAccounts").SafeToBoolYes())
                    {
                        // Ask about adult
                        var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                        var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                        curPanel.Visible = false;
                        newPanel.Visible = true;

                        Step.Text = (curStep + 1).ToString();
                    }
                    else
                    {
                        var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                        var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 2).ToString());

                        curPanel.Visible = false;
                        newPanel.Visible = true;

                        Step.Text = (curStep + 2).ToString();
                    }
                }
            }
            // Finished Current Step = 1

            if (curStep == 2)
            {
                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();
            }
            // Finished Current Step = 2

            if (curStep == 3)
            {
                var pgmDD           = (DropDownList)rptr.Items[0].FindControl("ProgID");
                var selectedProgram = DAL.Programs.FetchObject(int.Parse(pgmDD.SelectedValue));
                if (!selectedProgram.IsRegistrationOpen)
                {
                    string programNotOpen;
                    if (DateTime.Now < selectedProgram.StartDate)
                    {
                        programNotOpen = string.Format("This program opens for registration on {0}", selectedProgram.StartDate.ToLongDateString());
                    }
                    else
                    {
                        programNotOpen = string.Format("Registration for this program ended on {0}", selectedProgram.EndDate.ToLongDateString());
                    }

                    new SessionTools(Session).AlertPatron(programNotOpen,
                                                          PatronMessageLevels.Danger,
                                                          "exclamation-sign");
                    return;
                }

                var goal = rptr.Items[0].FindControl("Goal") as TextBox;
                if (goal != null &&
                    selectedProgram.GoalDefault > 0)
                {
                    goal.Text = selectedProgram.GoalDefault.ToString();
                }

                var sReqField = (HiddenField)rptr.Items[0].FindControl("ASchoolFieldIsRequired");
                var aSchoolFieldIsRequired = bool.Parse(sReqField.Value) == true;

                if (selectedProgram.HideSchoolInRegistration == true &&
                    aSchoolFieldIsRequired == false)
                {
                    ((Panel)rptr.Items[0].FindControl("SchoolArea")).Visible = false;
                }
                else
                {
                    ((Panel)rptr.Items[0].FindControl("SchoolArea")).Visible = true;
                }

                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();

                // do we show this next panel?
                var newPanelVisibility = ((TextBox)rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString() + "Visibility")).Text;
                if (newPanelVisibility == "0")
                {
                    curStep = curStep + 1;  // If not, move to the next panel
                }
            }
            // Finished Current Step = 3

            if (curStep == 4)
            {
                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();

                var PID             = int.Parse(((DropDownList)rptr.Items[0].FindControl("ProgID")).SelectedValue);
                var selectedProgram = DAL.Programs.FetchObject(PID);

                // disable goal field when the user has a set goal
                ((TextBox)rptr.Items[0].FindControl("Goal")).Enabled = (selectedProgram.GoalMin != selectedProgram.GoalMax);


                // Goal needs to be modified by ProgramGamePointConversion
                /* If daily goal is enabled we need to find what method point system uses. Just select the first item that is relevant.. */
                foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                {
                    int activityTypeId = (int)activityTypeValue;
                    var pgc            = ProgramGamePointConversion.FetchObjectByActivityId(PID,
                                                                                            activityTypeId);

                    if (pgc != null && pgc.PointCount > 0)
                    {
                        var range = (RangeValidator)rptr.Items[0].FindControl("GoalRangeValidator");

                        range.MinimumValue = selectedProgram.GoalMin.ToString();
                        range.MaximumValue = selectedProgram.GoalMax.ToString();
                        range.Text         = $"{range.MinimumValue}-{range.MaximumValue}";

                        var limitsInfoText = StringResources.getString("registration-goal-limits-note");
                        ((Label)rptr.Items[0].FindControl("RegistrationGoalInfoNoteLabel")).Text = String.Format(limitsInfoText, range.MinimumValue, range.MaximumValue);

                        /* save the activity type id */
                        ViewState["ActivityTypeId"] = activityTypeId.ToString();

                        var intervalString = selectedProgram.GetGoalInterval.ToString();

                        ((Literal)rptr.Items[0].FindControl("GoalLabel")).Text = $"{intervalString} Goal ({activityTypeValue.ToString()}):";
                        // found a valid point conversion for goal so break
                        break;
                    }
                }

                // do we show this next panel?
                var newPanelVisibility = ((TextBox)rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString() + "Visibility")).Text;
                if (newPanelVisibility == "0")
                {
                    curStep = curStep + 1;  // If not, move to the next panel
                }
            }
            // Finished Current Step = 4

            if (curStep == 5)
            {
                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();

                // deal with parental consent, by program
                var PID  = int.Parse(((DropDownList)rptr.Items[0].FindControl("ProgID")).SelectedValue);
                var prog = new Programs();
                prog.Fetch(PID);
                ((Literal)rptr.Items[0].FindControl("lblConsent")).Text = Server.HtmlDecode(prog.ParentalConsentText);

                ((Panel)rptr.Items[0].FindControl("pnlConsent")).Visible = prog.ParentalConsentFlag;

                // do we show this next panel?
                var newPanelVisibility = ((TextBox)rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString() + "Visibility")).Text;
                if (newPanelVisibility == "0" && !prog.ParentalConsentFlag)
                {
                    curStep = curStep + 1;  // If not, move to the next panel
                }
            }
            // Finished Current Step = 5

            if (curStep == 6)
            {
                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();
            }
            // Finished Current Step = 6

            if (curStep == 7)
            {
                if (!SaveAccount())
                {
                    return;
                }

                var curPanel = rptr.Items[0].FindControl("Panel" + curStep.ToString());
                var newPanel = FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                //newPanel.Visible = true;

                Step.Text = (curStep + 1).ToString();

                var famAcct = (DropDownList)rptr.Items[0].FindControl("FamilyAccount");
                if (famAcct.SelectedValue == "Yes")
                {
                    curStep          = 9; // Move to the next panel
                    Step.Text        = "9";
                    curPanel         = FindControl("Panel" + curStep.ToString());
                    curPanel.Visible = true;
                    btnPrev.Enabled  = false;
                    btnDone.Visible  = true;
                    return;
                }
                else
                {
                    // we're done with registration, we can just jump right in
                    TestingBL.CheckPatronNeedsPreTest();
                    TestingBL.CheckPatronNeedsPostTest();

                    Session[SessionKey.PatronMessage]          = ((BaseSRPPage)Page).GetResourceString("registration-success");
                    Session[SessionKey.PatronMessageGlyphicon] = "thumbs-up";
                    Response.Redirect("~");
                }

                newPanel.Visible = true;
                btnPrev.Enabled  = false;
            }
            // Finished Current Step = 7

            if (curStep == 8)
            {
                var curPanel = FindControl("Panel" + curStep.ToString());
                var newPanel = FindControl("Panel" + (curStep + 1).ToString());

                curPanel.Visible = false;
                newPanel.Visible = true;

                Step.Text       = (curStep + 1).ToString();
                btnPrev.Enabled = false;

                // log them in and take them home

                Response.Redirect(GoToUrl);
            }
            // Finished Current Step = 8

            if (curStep == 9)
            {
                // Reset Steps, flag as family members, restart the wizard

                var curPanel = FindControl("Panel" + curStep.ToString());
                var newPanel = rptr.Items[0].FindControl("Panel1");

                curPanel.Visible = false;
                newPanel.Visible = true;

                btnPrev.Enabled        = false;
                btnDone.Visible        = false;
                Step.Text              = "1";
                Panel0.Visible         = true;
                RegisteringFamily.Text = "1";
                RegistrationAge.Text   = "0";

                ((TextBox)rptr.Items[0].FindControl("ParentGuardianFirstName")).Text  = parentGuardianFirst.Text;
                ((TextBox)rptr.Items[0].FindControl("ParentGuardianMiddleName")).Text = parentGuardianMiddle.Text;
                ((TextBox)rptr.Items[0].FindControl("ParentGuardianLastName")).Text   = parentGuardianLast.Text;

                ((TextBox)rptr.Items[0].FindControl("Username")).Text = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("Password")).Text = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("Password")).Attributes.Add("Value", string.Empty);
                ((TextBox)rptr.Items[0].FindControl("Password2")).Text = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("Password2")).Attributes.Add("Value", string.Empty);
                ((TextBox)rptr.Items[0].FindControl("Age")).Text                  = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("DOB")).Text                  = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("SchoolGrade")).Text          = string.Empty;
                ((DropDownList)rptr.Items[0].FindControl("ProgID")).SelectedValue = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("FirstName")).Text            = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("MiddleName")).Text           = string.Empty;
                ((DropDownList)rptr.Items[0].FindControl("Gender")).SelectedValue = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("LiteracyLevel1")).Text       = string.Empty;
                ((TextBox)rptr.Items[0].FindControl("LiteracyLevel2")).Text       = string.Empty;
            }
            // Finished Current Step = 9
        }
        protected void loginPopupClick(object sender, EventArgs e)
        {
            if (!(string.IsNullOrEmpty(loginPopupUsername.Text.Trim()) ||
                  string.IsNullOrEmpty(loginPopupPassword.Text.Trim())))
            {
                var patron = new Patron();
                if (Patron.Login(loginPopupUsername.Text.Trim(), loginPopupPassword.Text))
                {
                    var bp = Patron.GetObjectByUsername(loginPopupUsername.Text.Trim());

                    var pgm = DAL.Programs.FetchObject(bp.ProgID);
                    if (pgm == null)
                    {
                        int schoolGrade;
                        int.TryParse(bp.SchoolGrade, out schoolGrade);
                        var progID = Programs.GetDefaultProgramForAgeAndGrade(bp.Age, schoolGrade);
                        bp.ProgID = progID;
                        bp.Update();
                    }


                    /* recalulate goal cache to accomdate changes in program length and point multipliers */
                    ProgramGamePointConversion pgc = null;

                    foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                    {
                        int activityTypeId = (int)activityTypeValue;
                        var temp           = ProgramGamePointConversion.FetchObjectByActivityId(pgm.PID,
                                                                                                activityTypeId);


                        if (temp != null && temp.PointCount > 0)
                        {
                            if (activityTypeValue == ActivityType.Minutes || activityTypeValue == ActivityType.Pages)
                            {
                                pgc = temp;
                                break;
                            }
                        }
                    }

                    if (pgc != null)
                    {
                        bp.RecalculateGoalCache(pgm, pgc);
                        bp.Update();
                    }


                    new SessionTools(Session).EstablishPatron(bp);

                    TestingBL.CheckPatronNeedsPreTest();
                    TestingBL.CheckPatronNeedsPostTest();

                    if (loginPopupRememberMe.Checked)
                    {
                        var loginUsernameCookie = new HttpCookie(CookieKey.Username);
                        loginUsernameCookie.Expires = DateTime.Now.AddDays(14);
                        loginUsernameCookie.Value   = loginPopupUsername.Text.Trim();
                        Response.SetCookie(loginUsernameCookie);
                    }
                    else
                    {
                        if (Request.Cookies[CookieKey.Username] != null)
                        {
                            Response.Cookies[CookieKey.Username].Expires = DateTime.Now.AddDays(-1);
                        }
                    }

                    if (Session[SessionKey.RequestedPath] != null)
                    {
                        string requestedPath = Session[SessionKey.RequestedPath].ToString();
                        Session.Remove(SessionKey.RequestedPath);
                        Response.Redirect(requestedPath);
                    }
                    else if (ViewState[SessionKey.RequestedPath] != null)
                    {
                        string requestedPath = ViewState[SessionKey.RequestedPath].ToString();
                        Response.Redirect(requestedPath);
                    }
                    else
                    {
                        Response.Redirect("~");
                    }
                }
                else
                {
                    LoginPopupErrorMessage = "Invalid username or password.";
                    new SessionTools(Session).ClearPatron();
                }
            }
        }
        protected void ImageButton1_Command(object sender, CommandEventArgs e)
        {
            var masterPage = (IControlRoomMaster)((BaseControlRoomPage)Page).Master;

            lblError.Text = "";
            Page.Validate();
            if (Page.IsValid)
            {
                var patron = Patron.FetchObject(int.Parse(PID.Text));
                var pgm    = Programs.FetchObject(patron.ProgID);


                if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback")
                {
                    //var p = new Patron();
                    var o       = new PatronPoints();
                    var sBadges = "";
                    var pa      = new AwardPoints(patron.PID);
                    var points  = int.Parse(NumPoints.Text);

                    if (!IsAdd())
                    {
                        //p = Patron.FetchObject(int.Parse(PID.Text));
                        o = PatronPoints.FetchObject(int.Parse(PatronPointsID));
                        o.Delete();

                        var pl = PatronReadingLog.FetchObject(o.LogID);
                        if (pl != null && pl.HasReview)
                        {
                            var r = PatronReview.FetchObjectByLogId(o.LogID);
                            if (r != null)
                            {
                                r.Delete();
                            }
                        }
                        if (pl != null)
                        {
                            pl.Delete();
                        }
                    }

                    //o.PID = patron.PID;
                    //o.NumPoints = int.Parse(NumPoints.Text);
                    //o.AwardDate = DateTime.Parse(AwardDate.Text);
                    //o.AwardReasonCd = int.Parse(AwardReasonCd.SelectedValue);
                    //o.AwardReason = PatronPoints.PointAwardReasonCdToDescription((PointAwardReason)o.AwardReasonCd);
                    //o.isReading = o.isBookList = o.isEvent = o.isGame = o.isGameLevelActivity = false;
                    if ((PointAwardReason)o.AwardReasonCd == PointAwardReason.Reading)
                    {
                        var pc = new ProgramGamePointConversion();
                        pc.FetchByActivityId(pgm.PID, 1);//ActivityType.Pages);
                        var pages = 1;
                        try { Convert.ToInt32(pc.ActivityCount * points / pc.PointCount); } catch {}
                        sBadges = pa.AwardPointsToPatron(points, PointAwardReason.Reading,
                                                         0,
                                                         ActivityType.Pages, pages, "", "", "", forceDate: DateTime.Parse(AwardDate.Text));
                    }


                    if ((PointAwardReason)o.AwardReasonCd == PointAwardReason.EventAttendance)
                    {
                        var ds = Event.GetEventByEventCode(pa.pgm.StartDate.ToShortDateString(),
                                                           DateTime.Now.ToShortDateString(), EventCode.Text);
                        var EID = 0;
                        if (ds.Tables[0].Rows.Count == 0)
                        {
                            EID = 0;
                        }
                        else
                        {
                            EID = (int)ds.Tables[0].Rows[0]["EID"];
                        }
                        sBadges = pa.AwardPointsToPatron(points, PointAwardReason.EventAttendance,
                                                         eventCode: EventCode.Text, eventID: EID, forceDate: DateTime.Parse(AwardDate.Text));
                    }
                    if ((PointAwardReason)o.AwardReasonCd == PointAwardReason.BookListCompletion)
                    {
                        var BLID = 0;
                        int.TryParse(lblBookList.Text, out BLID);
                        sBadges = pa.AwardPointsToPatron(points, PointAwardReason.BookListCompletion,
                                                         bookListID: BLID, forceDate: DateTime.Parse(AwardDate.Text));
                    }
                    if ((PointAwardReason)o.AwardReasonCd == PointAwardReason.GameCompletion)
                    {
                        var GID = 0;
                        int.TryParse(lblGame.Text, out GID);
                        sBadges = pa.AwardPointsToPatron(points, PointAwardReason.GameCompletion, GID, forceDate: DateTime.Parse(AwardDate.Text));
                    }
                    if ((PointAwardReason)o.AwardReasonCd == PointAwardReason.MiniGameCompletion)
                    {
                        var MGID = 0;
                        int.TryParse(lblMGame.Text, out MGID);
                        sBadges = pa.AwardPointsToPatron(points, PointAwardReason.MiniGameCompletion, MGID, forceDate: DateTime.Parse(AwardDate.Text));
                    }

                    PatronPointsID = PatronPoints.GetLastPatronEntryID(int.Parse(PatronID)).ToString();

                    LoadControl();
                    masterPage.PageMessage = SRPResources.AddedOK;

                    if (e.CommandName.ToLower() == "saveandback")
                    {
                        Response.Redirect("PatronLog.aspx");
                    }
                }
            }
        }
        public bool SaveAccount()
        {
            try {
                //var patron = (Patron)Session["Patron"];
                Patron patron = null;
                if ((int)Session["MasterAcctPID"] == 0)
                {
                    // we are the parent
                    patron = (Patron)Session["Patron"];
                }
                else
                {
                    patron = Patron.FetchObject((int)Session["MasterAcctPID"]);
                }
                var      p = new Patron();
                DateTime _d;
                var      DOB = rptr.Items[0].FindControl("DOB") as TextBox;
                if (DOB != null && !string.IsNullOrEmpty(DOB.Text))
                {
                    if (DateTime.TryParse(DOB.Text, out _d))
                    {
                        p.DOB = _d;
                    }
                }

                p.Age = FormatHelper.SafeToInt(((TextBox)rptr.Items[0].FindControl("Age")).Text);

                p.ProgID      = FormatHelper.SafeToInt(((DropDownList)rptr.Items[0].FindControl("ProgID")).SelectedValue);
                p.Username    = ((TextBox)rptr.Items[0].FindControl("Username")).Text;
                p.NewPassword = ((TextBox)rptr.Items[0].FindControl("Password")).Text;

                p.IsMasterAccount = false;
                p.MasterAcctPID   = patron.PID;

                p.SchoolGrade    = ((TextBox)rptr.Items[0].FindControl("SchoolGrade")).Text;
                p.FirstName      = ((TextBox)rptr.Items[0].FindControl("FirstName")).Text;
                p.MiddleName     = ((TextBox)rptr.Items[0].FindControl("MiddleName")).Text;
                p.LastName       = ((TextBox)rptr.Items[0].FindControl("LastName")).Text;
                p.Gender         = ((DropDownList)rptr.Items[0].FindControl("Gender")).SelectedValue;
                p.EmailAddress   = ((TextBox)rptr.Items[0].FindControl("EmailAddress")).Text;
                p.PhoneNumber    = ((TextBox)rptr.Items[0].FindControl("PhoneNumber")).Text;
                p.PhoneNumber    = FormatHelper.FormatPhoneNumber(p.PhoneNumber);
                p.StreetAddress1 = ((TextBox)rptr.Items[0].FindControl("StreetAddress1")).Text;
                p.StreetAddress2 = ((TextBox)rptr.Items[0].FindControl("StreetAddress2")).Text;
                p.City           = ((TextBox)rptr.Items[0].FindControl("City")).Text;
                p.State          = ((TextBox)rptr.Items[0].FindControl("State")).Text;
                p.ZipCode        = ((TextBox)rptr.Items[0].FindControl("ZipCode")).Text;
                p.ZipCode        = FormatHelper.FormatZipCode(p.ZipCode);

                p.Country = ((TextBox)rptr.Items[0].FindControl("Country")).Text;
                p.County  = ((TextBox)rptr.Items[0].FindControl("County")).Text;
                p.ParentGuardianFirstName  = ((TextBox)rptr.Items[0].FindControl("ParentGuardianFirstName")).Text;
                p.ParentGuardianLastName   = ((TextBox)rptr.Items[0].FindControl("ParentGuardianLastName")).Text;
                p.ParentGuardianMiddleName = ((TextBox)rptr.Items[0].FindControl("ParentGuardianMiddleName")).Text;
                p.LibraryCard = ((TextBox)rptr.Items[0].FindControl("LibraryCard")).Text;
                p.Goal        = FormatHelper.SafeToInt(((TextBox)(rptr.Items[0]).FindControl("Goal")).Text);

                //p.District = ((DropDownList)rptr.Items[0].FindControl("District")).SelectedValue;
                //p.SDistrict = ((DropDownList)rptr.Items[0].FindControl("SDistrict")).SelectedValue.SafeToInt();

                p.PrimaryLibrary = FormatHelper.SafeToInt(((DropDownList)rptr.Items[0].FindControl("PrimaryLibrary")).SelectedValue);
                p.SchoolName     = ((DropDownList)rptr.Items[0].FindControl("SchoolName")).SelectedValue;
                p.SchoolType     = FormatHelper.SafeToInt(((DropDownList)rptr.Items[0].FindControl("SchoolType")).SelectedValue);

                var lc = LibraryCrosswalk.FetchObjectByLibraryID(p.PrimaryLibrary);
                if (lc != null)
                {
                    p.District = lc.DistrictID == 0 ? ((DropDownList)rptr.Items[0].FindControl("District")).SelectedValue : lc.DistrictID.ToString();
                }
                else
                {
                    p.District = ((DropDownList)rptr.Items[0].FindControl("District")).SelectedValue;
                }
                var sc = SchoolCrosswalk.FetchObjectBySchoolID(p.SchoolName.SafeToInt());
                if (sc != null)
                {
                    p.SDistrict  = sc.DistrictID == 0 ? ((DropDownList)rptr.Items[0].FindControl("SDistrict")).SelectedValue.SafeToInt() : sc.DistrictID;
                    p.SchoolType = sc.SchTypeID == 0 ? FormatHelper.SafeToInt(((DropDownList)rptr.Items[0].FindControl("SchoolType")).SelectedValue) : sc.SchTypeID;
                }
                else
                {
                    p.SDistrict = ((DropDownList)rptr.Items[0].FindControl("SDistrict")).SelectedValue.SafeToInt();
                }

                p.Teacher        = ((TextBox)rptr.Items[0].FindControl("Teacher")).Text;
                p.GroupTeamName  = ((TextBox)rptr.Items[0].FindControl("GroupTeamName")).Text;
                p.LiteracyLevel1 = FormatHelper.SafeToInt(((TextBox)rptr.Items[0].FindControl("LiteracyLevel1")).Text);
                p.LiteracyLevel2 = FormatHelper.SafeToInt(((TextBox)rptr.Items[0].FindControl("LiteracyLevel2")).Text);

                p.ParentPermFlag = true;
                p.Over18Flag     = p.Age >= 18;
                p.ShareFlag      = ((CheckBox)rptr.Items[0].FindControl("ShareFlag")).Checked;
                p.TermsOfUseflag = true;

                p.Custom1 = string.IsNullOrEmpty(this.CustomFields.DDValues1)
                    ? ((TextBox)rptr.Items[0].FindControl("Custom1")).Text
                    : ((DropDownList)rptr.Items[0].FindControl("Custom1DD")).SelectedValue;
                p.Custom2 = string.IsNullOrEmpty(this.CustomFields.DDValues2)
                    ? ((TextBox)rptr.Items[0].FindControl("Custom2")).Text
                    : ((DropDownList)rptr.Items[0].FindControl("Custom2DD")).SelectedValue;
                p.Custom3 = string.IsNullOrEmpty(this.CustomFields.DDValues3)
                    ? ((TextBox)rptr.Items[0].FindControl("Custom3")).Text
                    : ((DropDownList)rptr.Items[0].FindControl("Custom3DD")).SelectedValue;
                p.Custom4 = string.IsNullOrEmpty(this.CustomFields.DDValues4)
                    ? ((TextBox)rptr.Items[0].FindControl("Custom4")).Text
                    : ((DropDownList)rptr.Items[0].FindControl("Custom4DD")).SelectedValue;
                p.Custom5 = string.IsNullOrEmpty(this.CustomFields.DDValues5)
                    ? ((TextBox)rptr.Items[0].FindControl("Custom5")).Text
                    : ((DropDownList)rptr.Items[0].FindControl("Custom5DD")).SelectedValue;

                if (p.IsValid(BusinessRulesValidationMode.INSERT))
                {
                    var prog = Programs.FetchObject(p.ProgID);

                    /* recalulate goal cache to accomodate changes in program length and point multipliers */
                    ProgramGamePointConversion pgc = null;
                    foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                    {
                        int activityTypeId = (int)activityTypeValue;
                        var temp           = ProgramGamePointConversion.FetchObjectByActivityId(prog.PID, activityTypeId);
                        if (temp != null && temp.PointCount > 0)
                        {
                            pgc = temp;
                        }
                    }
                    if (pgc != null)
                    {
                        p.RecalculateGoalCache(prog, pgc);
                    }

                    p.Insert();

                    var list = new List <Badge>();
                    if (prog.RegistrationBadgeID != 0)
                    {
                        AwardPoints.AwardBadgeToPatron(prog.RegistrationBadgeID, p, ref list);
                    }

                    try {
                        AwardPoints.AwardBadgeToPatronViaMatchingAwards(p, ref list);
                    } catch (Exception ex) {
                        this.Log().Error("Unable to run AwardBadgeToPatronViaMatchingAwards: {0} - {1}",
                                         ex.Message,
                                         ex.StackTrace);
                    }

                    patron.IsMasterAccount = true;
                    patron.Update();

                    // update patron session for things like MasterAcctPID and IsMasterAccount
                    new SessionTools(Session).EstablishPatron(patron);

                    new SessionTools(Session).AlertPatron("Your family member has been added!",
                                                          glyphicon: "check");
                }
                else
                {
                    StringBuilder message = new StringBuilder("<strong>");
                    message.AppendFormat(SRPResources.ApplicationError1, "<ul>");
                    foreach (BusinessRulesValidationMessage m in p.ErrorCodes)
                    {
                        message.AppendFormat("<li>{0}</li>", m.ErrorMessage);
                    }
                    message.Append("</ul></strong>");
                    new SessionTools(Session).AlertPatron(message.ToString(),
                                                          PatronMessageLevels.Warning,
                                                          "exclamation-sign");
                    return(false);
                }
            } catch (Exception ex) {
                this.Log().Error(string.Format("An exception was thrown adding a family member: {0}",
                                               ex.Message));
                this.Log().Error(string.Format("Stack trace: {0}", ex.StackTrace));
                new SessionTools(Session).AlertPatron(string.Format("<strong>{0}</strong>",
                                                                    ex.Message),
                                                      PatronMessageLevels.Warning,
                                                      "exclamation-sign");
                return(false);
            }
            return(true);
        }
Example #9
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var txtCount = txtCountSubmitted.Text.Trim();
            var txtCode  = txtProgramCode.Text.Trim();

            // ---------------------------------------------------------------------------------------------------
            if (txtCount.Length > 0 && txtCode.Length > 0)
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text      = "Please enter either how much you have read OR a code, but not both.<br><br>";
                return;
            }

            if (txtCount.Length == 0 && txtCode.Length == 0)
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text      = "Please enter either how much you have read OR a code.<br><br>";
                return;
            }
            // ---------------------------------------------------------------------------------------------------

            int PID            = int.Parse(lblPID.Text);
            int PGID           = int.Parse(lblPGID.Text);
            var StartingPoints = PatronPoints.GetTotalPatronPoints(PID);


            var pa      = new AwardPoints(PID);
            var sBadges = "";

            #region Reading
            // ---------------------------------------------------------------------------------------------------
            // Logging reading ...

            //Badge EarnedBadge;
            if (txtCount.Length > 0)
            {
                var intCount = 0;
                if (!int.TryParse(txtCount, out intCount))
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = "How much was read must be a number.";
                    return;
                }

                if (intCount < 0)
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = "Hmmm, you must enter a positive number...<br><br>";
                    return;
                }

                int maxAmountForLogging       = 0;
                int maxPointsPerDayForLogging = SRPSettings.GetSettingValue("MaxPtsDay").SafeToInt();
                switch (int.Parse(rbActivityType.SelectedValue))
                {
                case 0: maxAmountForLogging = SRPSettings.GetSettingValue("MaxBook").SafeToInt();
                    break;

                case 1: maxAmountForLogging = SRPSettings.GetSettingValue("MaxPage").SafeToInt();
                    break;

                //case 2: maxAmountForLogging = SRPSettings.GetSettingValue("MaxPar").SafeToInt();
                //    break;
                case 3: maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                    break;

                default: maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                    break;
                }

                if (intCount > maxAmountForLogging)
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = string.Format("That is an awful lot of reading... unfortunately the maximum you can submit at one time is {0} {1}.<br><br>",
                                                         maxAmountForLogging, ((ActivityType)int.Parse(rbActivityType.SelectedValue)).ToString());
                    return;
                }

                // convert pages/minutes/etc. to points
                var pc = new ProgramGamePointConversion();
                pc.FetchByActivityId(PGID, int.Parse(rbActivityType.SelectedValue));
                var points = Convert.ToInt32(intCount * pc.PointCount / pc.ActivityCount);

                var allPointsToday = PatronPoints.GetTotalPatronPoints(PID, DateTime.Now);
                if (intCount + allPointsToday > maxPointsPerDayForLogging)
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = string.Format("We are sorry, you have reached the maximum amount of points you are allowed to log in a single day, regardless of how the points were earned. Please come back and and log them tomorrow.<br><br>");
                    return;
                }


                //// convert pages/minutes/etc. to points
                //var pc = new ProgramGamePointConversion();
                //pc.FetchByActivityId(PGID, int.Parse(rbActivityType.SelectedValue));
                //var points = Convert.ToInt32(intCount * pc.PointCount / pc.ActivityCount);

                sBadges = pa.AwardPointsToPatron(points, PointAwardReason.Reading,
                                                 0,
                                                 (ActivityType)pc.ActivityTypeId, intCount, txtAuthor.Text.Trim(), txtTitle.Text.Trim(), Review.Text.Trim());
            }
            #endregion

            #region Event Attendance
            // Logging event attendance
            if (txtCode.Length > 0)
            {
                // verify event code was not previously redeemed
                if (PatronPoints.HasRedeemedKeywordPoints(PID, txtCode))
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = "This code has already been redeemend for this account.";
                    return;
                }

                // get event for that code, get the # points
                var ds = Event.GetEventByEventCode(pa.pgm.StartDate.ToShortDateString(),
                                                   DateTime.Now.ToShortDateString(), txtCode);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text      = "This code is not valid.";
                    return;
                }
                var EID    = (int)ds.Tables[0].Rows[0]["EID"];
                var evt    = Event.GetEvent(EID);
                var points = evt.NumberPoints;
                //var newPBID = 0;

                if (evt.BadgeID != 0)
                {
                    sBadges = pa.AwardPointsToPatron(points, PointAwardReason.EventAttendance,
                                                     eventCode: txtCode, eventID: EID);
                }
            }
            #endregion

            var EndingPoints = PatronPoints.GetTotalPatronPoints(PID);

            // No need to announcve the badge award

            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Text      = (EndingPoints - StartingPoints).ToInt() + @" points have been added to the account!";

            txtAuthor.Text      = txtTitle.Text = txtCountSubmitted.Text = Review.Text = txtProgramCode.Text = "";
            btnSubmit.Visible   = false;
            btnReSubmit.Visible = true;
            EntryTable.Visible  = false;
        }
        protected void SubmitActivity()
        {
            var txtCount = readingActivityField.Text.Trim();
            var intCount = 0;

            if (txtCount.Length == 0 || !int.TryParse(txtCount, out intCount) || intCount < 0)
            {
                Session[SessionKey.PatronMessage]          = "You must enter how much you've read as a positive whole number.";
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Danger;
                Session[SessionKey.PatronMessageGlyphicon] = "remove";
                return;
            }

            var selectedActivityType = activityTypeSelector.SelectedValue;

            // check that we aren't over the max
            int maxAmountForLogging = 0;

            switch (int.Parse(selectedActivityType))
            {
            case 0:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxBook").SafeToInt();
                break;

            case 1:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxPage").SafeToInt();
                break;

            //case 2: maxAmountForLogging = SRPSettings.GetSettingValue("MaxPar").SafeToInt();
            //    break;
            case 3:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                break;

            default:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                break;
            }
            if (intCount > maxAmountForLogging)
            {
                Session[SessionKey.PatronMessage] = string.Format("That's an awful lot of reading! You can only submit {0} {1} at a time.",
                                                                  maxAmountForLogging,
                                                                  ((ActivityType)int.Parse(selectedActivityType)).ToString());
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                return;
            }

            var patronId      = ((Patron)Session[SessionKey.Patron]).PID;
            var programGameId = int.Parse(ViewState["ProgramGameId"].ToString());

            var pa     = new AwardPoints(patronId);
            var points = 0;

            // convert pages/minutes/etc. to points
            var pc = new ProgramGamePointConversion();

            pc.FetchByActivityId(programGameId, int.Parse(activityTypeSelector.SelectedValue));
            // round up to ensure they get at least 1 point
            decimal computedPoints = intCount * pc.PointCount / pc.ActivityCount;

            points = (int)Math.Ceiling(computedPoints);

            // ensure they aren't over teh day total
            var allPointsToday            = PatronPoints.GetTotalPatronPoints(patronId, DateTime.Now);
            int maxPointsPerDayForLogging = SRPSettings.GetSettingValue("MaxPtsDay").SafeToInt();

            if (intCount + allPointsToday > maxPointsPerDayForLogging)
            {
                Session[SessionKey.PatronMessage]          = "Sorry but you have already reached the maximum amount of points that you can log in a day. Keep reading and come back tomorrow!";
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                return;
            }

            var earnedBadges = pa.AwardPointsToPatron(points: points,
                                                      reason: PointAwardReason.Reading,
                                                      MGID: 0,
                                                      readingActivity: (ActivityType)pc.ActivityTypeId,
                                                      readingAmount: intCount,
                                                      author: authorField.Text,
                                                      title: titleField.Text);

            // clear out the form
            var bookButton = activityTypeSelector.Items.Count == 1 &&
                             int.Parse(activityTypeSelector.Items[0].Value) == (int)ActivityType.Books;

            if (!bookButton)
            {
                readingActivityField.Text = string.Empty;
            }
            authorField.Text = string.Empty;
            titleField.Text  = string.Empty;

            // set message and earned badges
            string earnedMessage = new PointCalculation().EarnedMessage(earnedBadges, points);

            if (string.IsNullOrEmpty(earnedMessage))
            {
                Session[SessionKey.PatronMessage] = "<strong>Good job!</strong> Your reading activity has been logged.";
            }
            else
            {
                Session[SessionKey.PatronMessage] = string.Format("<strong>Good job!</strong> Your reading activity has been logged. <strong>{0}</strong>",
                                                                  earnedMessage);
            }
            Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Success;
            Session[SessionKey.PatronMessageGlyphicon] = "thumbs-up";
            new SessionTools(Session).EarnedBadges(earnedBadges);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Patron"] == null)
                {
                    Response.Redirect("~");
                }
                var patron  = (Patron)Session[SessionKey.Patron];
                var program = Programs.FetchObject(patron.ProgID);

                if (program == null || !program.IsOpen)
                {
                    readingLogControlPanel.Visible = false;
                    return;
                }

                ViewState["ProgramGameId"] = program.PID.ToString();

                if (Request.Cookies[CookieKey.LogBookDetails] != null)
                {
                    enterBookDetails.Checked = true;
                }

                foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                {
                    int    activityTypeId = (int)activityTypeValue;
                    string lookupString   = string.Format("{0}.{1}.{2}",
                                                          CacheKey.PointGameConversionStub,
                                                          patron.ProgID,
                                                          activityTypeId);
                    var pgc = Cache[lookupString] as ProgramGamePointConversion;
                    if (pgc == null)
                    {
                        this.Log().Debug("Cache miss looking up {0}", lookupString);
                        pgc = ProgramGamePointConversion.FetchObjectByActivityId(patron.ProgID,
                                                                                 activityTypeId);
                        Cache[lookupString] = pgc;
                    }

                    if (pgc != null && pgc.PointCount > 0)
                    {
                        activityTypeSelector.Items.Add(new ListItem(activityTypeValue.ToString(),
                                                                    activityTypeId.ToString()));
                    }
                }

                if (activityTypeSelector.Items.Count == 1)
                {
                    var singleOption = activityTypeSelector.Items[0];

                    if (int.Parse(singleOption.Value) == (int)ActivityType.Books)
                    {
                        countSubmittedLabel.Visible = false;
                        readingActivityField.Text   = "1";
                        readingActivityField.Attributes.Remove("style");
                        readingActivityField.Attributes.Add("style", "display: none;");
                        activityTypeSelector.Attributes.Remove("style");
                        activityTypeSelector.Attributes.Add("style", "display: none;");
                        activityTypeSingleLabel.Visible = false;
                        submitButton.Text = StringResources.getString("readinglog-read-a-book");
                    }
                    else
                    {
                        activityTypeSelector.Attributes.Remove("style");
                        activityTypeSelector.Attributes.Add("style", "display: none;");
                        activityTypeSingleLabel.Text    = singleOption.Text;
                        activityTypeSingleLabel.Visible = true;
                    }
                }
                else
                {
                    activityTypeSingleLabel.Visible = false;
                }
            }
        }
Example #12
0
        protected void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (Page.IsValid)
            {
                if (e.CommandName == "save")
                {
                    var      p = Patron.FetchObject(((Patron)Session["Patron"]).PID);
                    DateTime _d;

                    var DOB = e.Item.FindControl("DOB") as TextBox;
                    if (DOB != null && !string.IsNullOrEmpty(DOB.Text))
                    {
                        if (DateTime.TryParse(DOB.Text, out _d))
                        {
                            p.DOB = _d;
                        }
                    }

                    p.Age = FormatHelper.SafeToInt(((TextBox)(e.Item).FindControl("Age")).Text);
                    //p.Custom2 = (((TextBox)(e.Item).FindControl("Custom2")).Text);

                    p.SchoolGrade    = ((TextBox)(e.Item).FindControl("SchoolGrade")).Text;
                    p.FirstName      = ((TextBox)(e.Item).FindControl("FirstName")).Text;
                    p.MiddleName     = ((TextBox)(e.Item).FindControl("MiddleName")).Text;
                    p.LastName       = ((TextBox)(e.Item).FindControl("LastName")).Text;
                    p.Gender         = ((DropDownList)(e.Item).FindControl("Gender")).SelectedValue;
                    p.EmailAddress   = ((TextBox)(e.Item).FindControl("EmailAddress")).Text;
                    p.PhoneNumber    = ((TextBox)(e.Item).FindControl("PhoneNumber")).Text;
                    p.PhoneNumber    = FormatHelper.FormatPhoneNumber(p.PhoneNumber);
                    p.StreetAddress1 = ((TextBox)(e.Item).FindControl("StreetAddress1")).Text;
                    p.StreetAddress2 = ((TextBox)(e.Item).FindControl("StreetAddress2")).Text;
                    p.City           = ((TextBox)(e.Item).FindControl("City")).Text;
                    p.State          = ((TextBox)(e.Item).FindControl("State")).Text;
                    p.ZipCode        = ((TextBox)(e.Item).FindControl("ZipCode")).Text;
                    p.ZipCode        = FormatHelper.FormatZipCode(p.ZipCode);

                    p.Country = ((TextBox)(e.Item).FindControl("Country")).Text;
                    p.County  = ((TextBox)(e.Item).FindControl("County")).Text;
                    p.ParentGuardianFirstName  = ((TextBox)(e.Item).FindControl("ParentGuardianFirstName")).Text;
                    p.ParentGuardianLastName   = ((TextBox)(e.Item).FindControl("ParentGuardianLastName")).Text;
                    p.ParentGuardianMiddleName = ((TextBox)(e.Item).FindControl("ParentGuardianMiddleName")).Text;
                    p.LibraryCard = ((TextBox)(e.Item).FindControl("LibraryCard")).Text;

                    int goalValue = FormatHelper.SafeToInt(((TextBox)(e.Item).FindControl("Goal")).Text);
                    p.Goal = goalValue;

                    if (ViewState["ActivityTypeId"] != null)
                    {
                        int activityTypeId = 0;

                        if (int.TryParse(ViewState["ActivityTypeId"] as string, out activityTypeId))
                        {
                            ProgramGamePointConversion pgc = ProgramGamePointConversion.FetchObjectByActivityId(p.ProgID, activityTypeId);

                            if (pgc != null)
                            {
                                Programs program = Programs.FetchObject(p.ProgID);

                                p.RecalculateGoalCache(program, pgc);
                            }
                        }
                    }


                    //p.PrimaryLibrary = FormatHelper.SafeToInt(((DropDownList)(e.Item).FindControl("PrimaryLibrary")).SelectedValue);
                    //p.SchoolName = ((DropDownList)(e.Item).FindControl("SchoolName")).SelectedValue;
                    //p.SchoolType = FormatHelper.SafeToInt(((DropDownList)(e.Item).FindControl("SchoolType")).SelectedValue);

                    //p.District = ((DropDownList)(e.Item).FindControl("District")).SelectedValue;
                    //p.SDistrict = ((DropDownList)(e.Item).FindControl("SDistrict")).SelectedValue.SafeToInt();

                    p.PrimaryLibrary = FormatHelper.SafeToInt(((DropDownList)(e.Item).FindControl("PrimaryLibrary")).SelectedValue);
                    p.SchoolName     = ((DropDownList)(e.Item).FindControl("SchoolName")).SelectedValue;
                    p.SchoolType     = FormatHelper.SafeToInt(((DropDownList)(e.Item).FindControl("SchoolType")).SelectedValue);

                    var lc = LibraryCrosswalk.FetchObjectByLibraryID(p.PrimaryLibrary);
                    if (lc != null)
                    {
                        p.District = lc.DistrictID == 0 ? ((DropDownList)(e.Item).FindControl("District")).SelectedValue : lc.DistrictID.ToString();
                    }
                    else
                    {
                        p.District = ((DropDownList)(e.Item).FindControl("District")).SelectedValue;
                    }
                    var sc = SchoolCrosswalk.FetchObjectBySchoolID(p.SchoolName.SafeToInt());
                    if (sc != null)
                    {
                        p.SDistrict  = sc.DistrictID == 0 ? ((DropDownList)(e.Item).FindControl("SDistrict")).SelectedValue.SafeToInt() : sc.DistrictID;
                        p.SchoolType = sc.SchTypeID == 0 ? FormatHelper.SafeToInt(((DropDownList)(e.Item).FindControl("SchoolType")).SelectedValue) : sc.SchTypeID;
                    }
                    else
                    {
                        p.SDistrict = ((DropDownList)(e.Item).FindControl("SDistrict")).SelectedValue.SafeToInt();
                    }


                    p.Teacher        = ((TextBox)(e.Item).FindControl("Teacher")).Text;
                    p.GroupTeamName  = ((TextBox)(e.Item).FindControl("GroupTeamName")).Text;
                    p.LiteracyLevel1 = FormatHelper.SafeToInt(((TextBox)(e.Item).FindControl("LiteracyLevel1")).Text);
                    p.LiteracyLevel2 = FormatHelper.SafeToInt(((TextBox)(e.Item).FindControl("LiteracyLevel2")).Text);

                    p.Custom1 = string.IsNullOrEmpty(this.CustomFields.DDValues1)
                        ? ((TextBox)(e.Item).FindControl("Custom1")).Text
                        : ((DropDownList)(e.Item).FindControl("Custom1DD")).SelectedValue;
                    p.Custom2 = string.IsNullOrEmpty(this.CustomFields.DDValues2)
                        ? ((TextBox)(e.Item).FindControl("Custom2")).Text
                        : ((DropDownList)(e.Item).FindControl("Custom2DD")).SelectedValue;
                    p.Custom3 = string.IsNullOrEmpty(this.CustomFields.DDValues3)
                        ? ((TextBox)(e.Item).FindControl("Custom3")).Text
                        : ((DropDownList)(e.Item).FindControl("Custom3DD")).SelectedValue;
                    p.Custom4 = string.IsNullOrEmpty(this.CustomFields.DDValues4)
                        ? ((TextBox)(e.Item).FindControl("Custom4")).Text
                        : ((DropDownList)(e.Item).FindControl("Custom4DD")).SelectedValue;
                    p.Custom5 = string.IsNullOrEmpty(this.CustomFields.DDValues5)
                        ? ((TextBox)(e.Item).FindControl("Custom5")).Text
                        : ((DropDownList)(e.Item).FindControl("Custom5DD")).SelectedValue;
                    // do the save
                    p.Update();
                    Session["Patron"] = p;

                    rptr.DataSource = Patron.GetPatronForEdit(p.PID);
                    rptr.DataBind();

                    ((BaseSRPPage)Page).TranslateStrings(rptr);

                    Session[SessionKey.PatronMessage]          = "Your account information has been updated!";
                    Session[SessionKey.PatronMessageGlyphicon] = "check";
                }
            }
        }
        protected void SubmitActivity()
        {
            var txtCount = readingActivityField.Text.Trim();
            var intCount = 0;

            if (txtCount.Length == 0 || !int.TryParse(txtCount, out intCount) || intCount < 0)
            {
                Session[SessionKey.PatronMessage]          = StringResources.getString("readinglog-entry-invalid");
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Danger;
                Session[SessionKey.PatronMessageGlyphicon] = "remove";
                return;
            }

            var selectedActivityType = activityTypeSelector.SelectedValue;

            // check that we aren't over the max
            int maxAmountForLogging = 0;

            switch (int.Parse(selectedActivityType))
            {
            case 0:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxBook").SafeToInt();
                break;

            case 1:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxPage").SafeToInt();
                break;

            //case 2: maxAmountForLogging = SRPSettings.GetSettingValue("MaxPar").SafeToInt();
            //    break;
            case 3:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                break;

            default:
                maxAmountForLogging = SRPSettings.GetSettingValue("MaxMin").SafeToInt();
                break;
            }
            if (intCount > maxAmountForLogging)
            {
                Session[SessionKey.PatronMessage] = string.Format(StringResources.getString("readinglog-entry-limit"),
                                                                  maxAmountForLogging,
                                                                  ((ActivityType)int.Parse(selectedActivityType)).ToString());
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                return;
            }

            var patronId      = ((Patron)Session[SessionKey.Patron]).PID;
            var programGameId = int.Parse(ViewState[ProgramGameIdKey].ToString());

            var pa     = new AwardPoints(patronId);
            var points = 0;

            // convert pages/minutes/etc. to points
            var pc = new ProgramGamePointConversion();

            pc.FetchByActivityId(programGameId, int.Parse(activityTypeSelector.SelectedValue));
            // round up to ensure they get at least 1 point
            decimal computedPoints = intCount * pc.PointCount / pc.ActivityCount;

            points = (int)Math.Ceiling(computedPoints);


            // ensure they aren't over teh day total
            var allPointsToday            = PatronPoints.GetTotalPatronPointsOnDate(patronId, DateTime.Now);
            int maxPointsPerDayForLogging = SRPSettings.GetSettingValue("MaxPtsDay").SafeToInt();

            if (intCount + allPointsToday > maxPointsPerDayForLogging)
            {
                Session[SessionKey.PatronMessage]          = StringResources.getString("readinglog-daily-limit");
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                return;
            }

            var review = "";

            if (ViewState[PatronCanReviewKey] as bool? == true)
            {
                review = reviewField.Text;
            }

            var earnedBadges = pa.AwardPointsToPatron(points: points,
                                                      reason: PointAwardReason.Reading,
                                                      MGID: 0,
                                                      readingActivity: (ActivityType)pc.ActivityTypeId,
                                                      readingAmount: intCount,
                                                      author: authorField.Text,
                                                      title: titleField.Text,
                                                      review: review);

            // clear out the form
            var bookButton = activityTypeSelector.Items.Count == 1 &&
                             int.Parse(activityTypeSelector.Items[0].Value) == (int)ActivityType.Books;

            if (!bookButton)
            {
                readingActivityField.Text = string.Empty;
            }
            authorField.Text = string.Empty;
            titleField.Text  = string.Empty;
            reviewField.Text = string.Empty;

            // set message and earned badges
            string earnedMessage = new PointCalculation().EarnedMessage(earnedBadges, points);

            if (string.IsNullOrEmpty(earnedMessage))
            {
                Session[SessionKey.PatronMessage] = "<strong>Good job!</strong> Your reading activity has been logged.";
            }
            else
            {
                Session[SessionKey.PatronMessage] = string.Format("<strong>Good job!</strong> Your reading activity has been logged. <strong>{0}</strong>",
                                                                  earnedMessage);
            }
            Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Success;
            Session[SessionKey.PatronMessageGlyphicon] = "thumbs-up";
            new SessionTools(Session).EarnedBadges(earnedBadges);
        }
        public bool SaveAccount()
        {
            try
            {
                var      p = new Patron();
                DateTime _d;
                var      DOB = rptr.Items[0].FindControl("DOB") as TextBox;
                if (DOB != null && !string.IsNullOrEmpty(DOB.Text))
                {
                    if (DateTime.TryParse(DOB.Text, out _d))
                    {
                        p.DOB = _d;
                    }
                }

                p.Age = FormatHelper.SafeToInt(((TextBox)(rptr.Items[0]).FindControl("Age")).Text);

                p.ProgID      = FormatHelper.SafeToInt(((DropDownList)(rptr.Items[0]).FindControl("ProgID")).SelectedValue);
                p.Username    = ((TextBox)(rptr.Items[0]).FindControl("Username")).Text;
                p.NewPassword = ((TextBox)(rptr.Items[0]).FindControl("Password")).Text;

                var famAcct = (DropDownList)rptr.Items[0].FindControl("FamilyAccount");
                p.IsMasterAccount = (famAcct.SelectedValue == "Yes" && MasterPID.Text.Length == 0);

                p.SchoolGrade    = ((TextBox)(rptr.Items[0]).FindControl("SchoolGrade")).Text;
                p.FirstName      = ((TextBox)(rptr.Items[0]).FindControl("FirstName")).Text;
                p.MiddleName     = ((TextBox)(rptr.Items[0]).FindControl("MiddleName")).Text;
                p.LastName       = ((TextBox)(rptr.Items[0]).FindControl("LastName")).Text;
                p.Gender         = ((DropDownList)(rptr.Items[0]).FindControl("Gender")).SelectedValue;
                p.EmailAddress   = ((TextBox)(rptr.Items[0]).FindControl("EmailAddress")).Text;
                p.PhoneNumber    = ((TextBox)(rptr.Items[0]).FindControl("PhoneNumber")).Text;
                p.PhoneNumber    = FormatHelper.FormatPhoneNumber(p.PhoneNumber);
                p.StreetAddress1 = ((TextBox)(rptr.Items[0]).FindControl("StreetAddress1")).Text;
                p.StreetAddress2 = ((TextBox)(rptr.Items[0]).FindControl("StreetAddress2")).Text;
                p.City           = ((TextBox)(rptr.Items[0]).FindControl("City")).Text;
                p.State          = ((TextBox)(rptr.Items[0]).FindControl("State")).Text;
                p.ZipCode        = ((TextBox)(rptr.Items[0]).FindControl("ZipCode")).Text;
                p.ZipCode        = FormatHelper.FormatZipCode(p.ZipCode);

                p.Country = ((TextBox)(rptr.Items[0]).FindControl("Country")).Text;
                p.County  = ((TextBox)(rptr.Items[0]).FindControl("County")).Text;
                p.ParentGuardianFirstName  = ((TextBox)(rptr.Items[0]).FindControl("ParentGuardianFirstName")).Text;
                p.ParentGuardianLastName   = ((TextBox)(rptr.Items[0]).FindControl("ParentGuardianLastName")).Text;
                p.ParentGuardianMiddleName = ((TextBox)(rptr.Items[0]).FindControl("ParentGuardianMiddleName")).Text;
                p.LibraryCard = ((TextBox)(rptr.Items[0]).FindControl("LibraryCard")).Text;

                int goalValue = FormatHelper.SafeToInt(((TextBox)(rptr.Items[0]).FindControl("Goal")).Text);
                p.Goal        = goalValue;
                p.AvatarState = "";

                if (ViewState["ActivityTypeId"] != null)
                {
                    int activityTypeId = 0;

                    if (int.TryParse(ViewState["ActivityTypeId"] as string, out activityTypeId))
                    {
                        ProgramGamePointConversion pgc = ProgramGamePointConversion.FetchObjectByActivityId(p.ProgID, activityTypeId);

                        if (pgc != null)
                        {
                            Programs program = Programs.FetchObject(p.ProgID);
                            p.RecalculateGoalCache(program, pgc);
                        }
                    }
                }


                p.PrimaryLibrary = FormatHelper.SafeToInt(((DropDownList)(rptr.Items[0]).FindControl("PrimaryLibrary")).SelectedValue);
                p.SchoolName     = ((DropDownList)(rptr.Items[0]).FindControl("SchoolName")).SelectedValue;
                p.SchoolType     = FormatHelper.SafeToInt(((DropDownList)(rptr.Items[0]).FindControl("SchoolType")).SelectedValue);

                var lc = LibraryCrosswalk.FetchObjectByLibraryID(p.PrimaryLibrary);
                if (lc != null)
                {
                    p.District = lc.DistrictID == 0
                        ? ((DropDownList)(rptr.Items[0]).FindControl("District")).SelectedValue
                        : lc.DistrictID.ToString();
                }
                else
                {
                    p.District = ((DropDownList)(rptr.Items[0]).FindControl("District")).SelectedValue;
                }
                var sc = SchoolCrosswalk.FetchObjectBySchoolID(p.SchoolName.SafeToInt());
                if (sc != null)
                {
                    p.SDistrict = sc.DistrictID == 0
                        ? ((DropDownList)(rptr.Items[0]).FindControl("SDistrict")).SelectedValue.SafeToInt()
                        : sc.DistrictID;

                    p.SchoolType = sc.SchTypeID == 0
                        ? FormatHelper.SafeToInt(((DropDownList)(rptr.Items[0]).FindControl("SchoolType")).SelectedValue)
                        : sc.SchTypeID;
                }
                else
                {
                    p.SDistrict = ((DropDownList)(rptr.Items[0]).FindControl("SDistrict")).SelectedValue.SafeToInt();
                }


                p.Teacher        = ((TextBox)(rptr.Items[0]).FindControl("Teacher")).Text;
                p.GroupTeamName  = ((TextBox)(rptr.Items[0]).FindControl("GroupTeamName")).Text;
                p.LiteracyLevel1 = FormatHelper.SafeToInt(((TextBox)(rptr.Items[0]).FindControl("LiteracyLevel1")).Text);
                p.LiteracyLevel2 = FormatHelper.SafeToInt(((TextBox)(rptr.Items[0]).FindControl("LiteracyLevel2")).Text);

                p.ParentPermFlag = ((CheckBox)(rptr.Items[0]).FindControl("ParentPermFlag")).Checked;
                p.Over18Flag     = int.Parse(RegistrationAge.Text) >= 18;
                p.ShareFlag      = ((CheckBox)(rptr.Items[0]).FindControl("ShareFlag")).Checked;
                p.TermsOfUseflag = ((CheckBox)(rptr.Items[0]).FindControl("TermsOfUseflag")).Checked;

                var cr = this.CustomFields;
                p.Custom1 = string.IsNullOrEmpty(cr.DDValues1)
                    ? ((TextBox)(rptr.Items[0]).FindControl("Custom1")).Text
                    : ((DropDownList)(rptr.Items[0]).FindControl("Custom1DD")).SelectedValue;

                p.Custom2 = string.IsNullOrEmpty(cr.DDValues2)
                    ? ((TextBox)(rptr.Items[0]).FindControl("Custom2")).Text
                    : ((DropDownList)(rptr.Items[0]).FindControl("Custom2DD")).SelectedValue;

                p.Custom3 = string.IsNullOrEmpty(cr.DDValues3)
                    ? ((TextBox)(rptr.Items[0]).FindControl("Custom3")).Text
                    : ((DropDownList)(rptr.Items[0]).FindControl("Custom3DD")).SelectedValue;

                p.Custom4 = string.IsNullOrEmpty(cr.DDValues4)
                    ? ((TextBox)(rptr.Items[0]).FindControl("Custom4")).Text
                    : ((DropDownList)(rptr.Items[0]).FindControl("Custom4DD")).SelectedValue;

                p.Custom5 = string.IsNullOrEmpty(cr.DDValues5)
                    ? ((TextBox)(rptr.Items[0]).FindControl("Custom5")).Text
                    : ((DropDownList)(rptr.Items[0]).FindControl("Custom5DD")).SelectedValue;

                var registeringMasterAccount = true;
                if (!RegisteringFamily.Text.Equals("0"))
                {
                    registeringMasterAccount = false;
                    p.MasterAcctPID          = int.Parse(MasterPID.Text);
                }

                if (p.IsValid(BusinessRulesValidationMode.INSERT))
                {
                    p.Insert();

                    var prog             = Programs.FetchObject(p.ProgID);
                    var earnedBadgesList = new List <Badge>();
                    if (prog.RegistrationBadgeID != 0)
                    {
                        AwardPoints.AwardBadgeToPatron(prog.RegistrationBadgeID,
                                                       p,
                                                       ref earnedBadgesList);
                    }
                    AwardPoints.AwardBadgeToPatronViaMatchingAwards(p, ref earnedBadgesList);

                    var earnedBadges = string.Join("|", earnedBadgesList.Select(b => b.BID).Distinct());

                    if (p.IsMasterAccount && earnedBadges.Length > 0)
                    {
                        // if family account and is master, and has badges, rememebr to show them
                        new SessionTools(Session).EarnedBadges(earnedBadges);
                    }
                    if (!p.IsMasterAccount && p.MasterAcctPID == 0 && earnedBadges.Length > 0)
                    {
                        // if not family master or not family at all and badges, rememebr to show ...
                        new SessionTools(Session).EarnedBadges(earnedBadges);
                    }

                    if (p.IsMasterAccount)
                    {
                        parentGuardianFirst.Text  = p.FirstName;
                        parentGuardianMiddle.Text = p.MiddleName;
                        parentGuardianLast.Text   = p.LastName;
                    }

                    if (registeringMasterAccount)
                    {
                        MasterPID.Text = p.PID.ToString();
                        new SessionTools(Session).EstablishPatron(p);
                    }
                }
                else
                {
                    StringBuilder message = new StringBuilder("<strong>");
                    message.AppendFormat(SRPResources.ApplicationError1, "<ul>");
                    foreach (BusinessRulesValidationMessage m in p.ErrorCodes)
                    {
                        message.AppendFormat("<li>{0}</li>", m.ErrorMessage);
                    }
                    message.Append("</ul></strong>");
                    Session[SessionKey.PatronMessage]          = message.ToString();
                    Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                    Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                    return(false);
                }
            }
            catch (Exception ex)
            {
                this.Log().Error(string.Format("A problem occurred during registration: {0}",
                                               ex.Message));
                Session[SessionKey.PatronMessage] = string.Format("<strong>{0}</strong>",
                                                                  ex.Message);
                Session[SessionKey.PatronMessageLevel]     = PatronMessageLevels.Warning;
                Session[SessionKey.PatronMessageGlyphicon] = "exclamation-sign";
                return(false);
            }
            return(true);
        }
Example #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(Request["SA"]) && (Session["SA"] == null || Session["SA"].ToString() == ""))
                {
                    Response.Redirect("~/FamilyAccountList.aspx");
                }
                if (!string.IsNullOrEmpty(Request["SA"]))
                {
                    lblPID.Text   = Request["SA"];
                    Session["SA"] = lblPID.Text;
                }
                else
                {
                    lblPID.Text = Session["SA"].ToString();
                }

                var parent = (Patron)Session["Patron"];
                lblParentPID.Text = parent.PID.ToString();

                // now validate user can change manage log for SA Sub Account
                if (!parent.IsMasterAccount)
                {
                    // kick them out
                    Response.Redirect("~/Logout.aspx");
                }

                if (!Patron.CanManageSubAccount(parent.PID, int.Parse(lblPID.Text)))
                {
                    // kick them out
                    Response.Redirect("~/Logout.aspx");
                }


                var patron = Patron.FetchObject(int.Parse(lblPID.Text));
                var prog   = Programs.FetchObject(patron.ProgID);
                if (prog == null)
                {
                    var progID = Programs.GetDefaultProgramForAgeAndGrade(patron.Age, patron.SchoolGrade.SafeToInt());
                    prog          = Programs.FetchObject(progID);
                    patron.ProgID = progID;
                    patron.Update();
                }

                lblPGID.Text      = prog.PID.ToString();
                pnlReview.Visible = prog.PatronReviewFlag;

                lblAccount.Text = (patron.FirstName + " " + patron.LastName).Trim();
                if (lblAccount.Text.Length == 0)
                {
                    lblAccount.Text = patron.Username;
                }


                // Load the Acticity Types to log
                foreach (ActivityType val in Enum.GetValues(typeof(ActivityType)))
                {
                    var pgc = ProgramGamePointConversion.FetchObjectByActivityId(prog.PID, (int)val);
                    if (pgc != null && pgc.PointCount > 0)
                    {
                        rbActivityType.Items.Add(new ListItem(val.ToString(), ((int)val).ToString()));
                    }
                }
                rbActivityType.SelectedIndex = 0;
            }
        }
        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Programs/ProgramList.aspx";

            if (e.CommandName.ToLower() == "back")
            {
                Response.Redirect(returnURL);
            }
            if (e.CommandName.ToLower() == "refresh")
            {
                try
                {
                    odsData.DataBind();
                    dv.DataBind();
                    dv.ChangeMode(DetailsViewMode.Edit);

                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                    {
                        masterPage.PageMessage = SRPResources.RefreshOK;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback")
            {
                try
                {
                    var obj = new DAL.Programs();
                    //obj.GenNotificationFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("GenNotificationFlag")).Checked;

                    obj.AdminName = ((TextBox)((DetailsView)sender).FindControl("AdminName")).Text;
                    obj.Title     = ((TextBox)((DetailsView)sender).FindControl("Title")).Text;
                    obj.TabName   = ((TextBox)((DetailsView)sender).FindControl("TabName")).Text;
                    //obj.POrder = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("POrder")).Text);
                    obj.IsActive  = ((CheckBox)((DetailsView)sender).FindControl("IsActive")).Checked;
                    obj.IsHidden  = ((CheckBox)((DetailsView)sender).FindControl("IsHidden")).Checked;
                    obj.StartDate = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("StartDate")).Text);
                    obj.EndDate   = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("EndDate")).Text);
                    //obj.MaxAge = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("MaxAge")).Text);
                    //obj.MaxGrade = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("MaxGrade")).Text);
                    obj.LoggingStart     = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("LoggingStart")).Text);
                    obj.LoggingEnd       = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("LoggingEnd")).Text);
                    obj.CompletionPoints = 0;
                    //obj.ParentalConsentFlag = ((CheckBox)((DetailsView)sender).FindControl("ParentalConsentFlag")).Checked;
                    //obj.ParentalConsentText = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("ParentalConsentText")).Text;
                    //obj.PatronReviewFlag = ((CheckBox)((DetailsView)sender).FindControl("PatronReviewFlag")).Checked;
                    //obj.LogoutURL = ((TextBox)((DetailsView)sender).FindControl("LogoutURL")).Text;
                    //obj.ProgramGameID = FormatHelper.SafeToInt(((DropDownList) ((DetailsView) sender).FindControl("ProgramGameID")).SelectedValue);
                    //obj.HTML1 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML1")).Text;
                    //obj.HTML2 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML2")).Text;
                    //obj.HTML3 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML3")).Text;
                    //obj.HTML4 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML4")).Text;
                    //obj.HTML5 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML5")).Text;
                    //obj.HTML6 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("HTML6")).Text;
                    //obj.BannerImage = ((TextBox)((DetailsView)sender).FindControl("BannerImage")).Text;
                    //obj.RegistrationBadgeID = FormatHelper.SafeToInt(((DropDownList) ((DetailsView) sender).FindControl("RegistrationBadgeID")).SelectedValue);

                    obj.AddedDate   = DateTime.Now;
                    obj.AddedUser   = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A";  // Get from session
                    obj.LastModDate = obj.AddedDate;
                    obj.LastModUser = obj.AddedUser;

                    if (obj.IsValid(BusinessRulesValidationMode.INSERT))
                    {
                        obj.Insert();

                        File.Copy(Server.MapPath("~/css/program/default.css"), Server.MapPath("~/css/program/" + obj.PID.ToString() + ".css"), true);
                        File.Copy(Server.MapPath("~/images/banners/default.png"), Server.MapPath("~/images/banners/" + obj.PID.ToString() + ".png"), true);
                        File.Copy(Server.MapPath("~/resources/program.default.en-US.txt"), Server.MapPath("~/resources/program." + obj.PID.ToString() + ".en-US.txt"), true);
                        //CompileResourceFile(Server.MapPath("~/resources/program." + obj.PID.ToString() + ".en-US.txt"));

                        foreach (ActivityType val in Enum.GetValues(typeof(ActivityType)))
                        {
                            var o = new ProgramGamePointConversion();
                            o.PGID           = obj.PID;
                            o.ActivityTypeId = (int)val;
                            o.ActivityCount  = 1;
                            o.PointCount     = 0;
                            o.AddedDate      = obj.AddedDate;
                            o.AddedUser      = obj.AddedUser;
                            o.LastModDate    = o.AddedDate;
                            o.LastModUser    = o.AddedUser;

                            o.Insert();
                        }

                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text = obj.PID.ToString();

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.AddedOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback")
            {
                try
                {
                    var obj = new DAL.Programs();
                    int pk  = int.Parse(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("PID")).Text);
                    obj.Fetch(pk);

                    obj.AdminName = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("AdminName")).Text;
                    obj.Title     = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("Title")).Text;
                    obj.TabName   = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("TabName")).Text;
                    //obj.POrder = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("POrder")).Text);
                    obj.IsActive            = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("IsActive")).Checked;
                    obj.IsHidden            = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("IsHidden")).Checked;
                    obj.StartDate           = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("StartDate")).Text);
                    obj.EndDate             = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("EndDate")).Text);
                    obj.MaxAge              = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("MaxAge")).Text);
                    obj.MaxGrade            = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("MaxGrade")).Text);
                    obj.LoggingStart        = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("LoggingStart")).Text);
                    obj.LoggingEnd          = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("LoggingEnd")).Text);
                    obj.ParentalConsentFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("ParentalConsentFlag")).Checked;
                    obj.ParentalConsentText = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("ParentalConsentText")).Text;
                    obj.PatronReviewFlag    = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("PatronReviewFlag")).Checked;
                    obj.LogoutURL           = ((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel1").FindControl("LogoutURL")).Text;

                    obj.CompletionPoints = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("CompletionPoints")).Text);
                    obj.ProgramGameID    = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("ProgramGameID")).Text);
                    //obj.ProgramGameID = 0;
                    obj.RegistrationBadgeID = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("RegistrationBadgeID")).Text);
                    //obj.RegistrationBadgeID = 0;
                    obj.HTML1 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("HTML1")).Text;
                    obj.HTML2 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("HTML2")).Text;

                    obj.HTML3 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel3").FindControl("HTML3")).Text;
                    obj.HTML4 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel3").FindControl("HTML4")).Text;

                    obj.HTML5 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel4").FindControl("HTML5")).Text;
                    obj.HTML6 = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel4").FindControl("HTML6")).Text;

                    obj.BannerImage = "";//((TextBox)((DetailsView)sender).FindControl("BannerImage")).Text;


                    obj.LastModDate = DateTime.Now;
                    obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username;  //"N/A";  // Get from session

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();

                        var rptr = ((Repeater)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel5").FindControl("rptr"));
                        if (rptr != null)
                        {
                            foreach (RepeaterItem item in rptr.Items)
                            {
                                var PGCID = int.Parse(((TextBox)item.FindControl("PGCID")).Text);
                                var ActivityCountTxt = ((TextBox)item.FindControl("ActivityCount")).Text;
                                var PointCountTxt = ((TextBox)item.FindControl("PointCount")).Text;
                                int ActivityCount = 1, PointCount = 0;
                                int.TryParse(ActivityCountTxt, out ActivityCount);
                                int.TryParse(PointCountTxt, out PointCount);

                                var o = ProgramGamePointConversion.FetchObject(PGCID);
                                if (o == null)
                                {
                                    continue;
                                }
                                o.ActivityCount = ActivityCount;
                                o.PointCount    = PointCount;
                                o.LastModDate   = obj.LastModDate;
                                o.LastModUser   = obj.LastModUser;
                                o.Update();
                            }
                        }


                        if (e.CommandName.ToLower() == "saveandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.SaveOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "gen")
            {
                int PK = int.Parse(lblPK.Text);
                var ds = ProgramCodes.GetProgramStats(PK);

                int TotalCodes = (int)ds.Tables[0].Rows[0]["TotalCodes"];
                var txt        = (TextBox)dv.FindControl("TabContainer1").FindControl("TabPanel6").FindControl("txtGen");
                int addl       = int.Parse(txt.Text);

                ProgramCodes.Generate(TotalCodes + 1, TotalCodes + addl, PK);

                odsData.DataBind();
                dv.DataBind();
                dv.ChangeMode(DetailsViewMode.Edit);

                var masterPage = (IControlRoomMaster)Master;
                masterPage.PageMessage = "Additional codes generated!";
            }
            if (e.CommandName.ToLower() == "exp")
            {
                int PK = int.Parse(lblPK.Text);

                var ds = ProgramCodes.GetExportList(PK);

                string excelFilename = Server.MapPath("~/ProgramRewardCodes.xlsx");
                CreateExcelFile.CreateExcelDocument(ds, excelFilename);

                Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=ProgramRewardCodes.xlsx");
                EnableViewState = false;
                Response.BinaryWrite(File.ReadAllBytes(excelFilename));
                File.Delete(excelFilename);
                Response.End();


                var masterPage = (IControlRoomMaster)Master;
                masterPage.PageMessage = "Codes Exported!";
            }
        }
Example #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var familyRelationship = new FamilyTools().ValidImpersonation(Request, Session);
                if (familyRelationship == null)
                {
                    Response.Redirect("~");
                }

                ViewState[SubmitAsPatronIdKey] = familyRelationship.PatronId;

                var patron  = Patron.FetchObject(familyRelationship.PatronId);
                var program = Programs.FetchObject(patron.ProgID);

                lblAccount.Text = DisplayHelper.FormatName(patron.FirstName,
                                                           patron.LastName,
                                                           patron.Username);

                if (program == null || !program.IsOpen)
                {
                    familyReadingLogControlPanel.Visible = false;
                    return;
                }

                ViewState[RequireBookDetailsKey] = program.RequireBookDetails;
                ViewState[PatronCanReviewKey]    = program.PatronReviewFlag;

                ViewState[ProgramGameIdKey] = program.PID.ToString();

                if (Request.Cookies[CookieKey.LogBookDetails] != null)
                {
                    enterBookDetails.Checked = true;
                }

                foreach (ActivityType activityTypeValue in Enum.GetValues(typeof(ActivityType)))
                {
                    int activityTypeId = (int)activityTypeValue;
                    var sessionTool    = new SessionTools(Session);

                    string lookupString = string.Format("{0}.{1}.{2}",
                                                        CacheKey.PointGameConversionStub,
                                                        patron.ProgID,
                                                        activityTypeId);
                    var pgc = sessionTool.GetCache(Cache, lookupString) as ProgramGamePointConversion;
                    if (pgc == null)
                    {
                        this.Log().Debug("Cache miss looking up {0}", lookupString);
                        pgc = ProgramGamePointConversion.FetchObjectByActivityId(patron.ProgID,
                                                                                 activityTypeId);
                        sessionTool.SetCache(Cache, lookupString, pgc);
                    }

                    if (pgc != null && pgc.PointCount > 0)
                    {
                        activityTypeSelector.Items.Add(new ListItem(activityTypeValue.ToString(),
                                                                    activityTypeId.ToString()));
                    }
                }

                if (activityTypeSelector.Items.Count == 1)
                {
                    var singleOption = activityTypeSelector.Items[0];

                    if (int.Parse(singleOption.Value) == (int)ActivityType.Books)
                    {
                        countSubmittedLabel.Visible     = false;
                        familyReadingActivityField.Text = "1";
                        familyReadingActivityField.Attributes.Remove("style");
                        familyReadingActivityField.Attributes.Add("style", "display: none;");
                        activityTypeSelector.Attributes.Remove("style");
                        activityTypeSelector.Attributes.Add("style", "display: none;");
                        activityTypeSingleLabel.Visible = false;
                        submitButton.Text = StringResources.getString("readinglog-read-a-book");
                    }
                    else
                    {
                        activityTypeSelector.Attributes.Remove("style");
                        activityTypeSelector.Attributes.Add("style", "display: none;");
                        activityTypeSingleLabel.Text    = singleOption.Text;
                        activityTypeSingleLabel.Visible = true;
                    }
                }
                else
                {
                    activityTypeSingleLabel.Visible = false;
                }
            }
        }