public AwardPoints(int PID) {
            patron = Patron.FetchObject(PID);
            pgm = Programs.FetchObject(patron.ProgID);
            EarnedBadges = new List<Badge>();

            StartingPoints = PatronPoints.GetTotalPatronPoints(patron.PID);
            EndingPoints = StartingPoints;
        }
Exemplo n.º 2
0
 public int GetGameCompletionBonusPoints(DataSet ds, Patron patron)
 {
     var ret = 0;
     for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
         var multiplier = GetGame(patron).BonusLevelPointMultiplier;
         var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
         ret = ret + levelPoints;
     }
     return ret;
 }
Exemplo n.º 3
0
        public ProgramGame GetGame(Patron patron)
        {
            if(ViewState["gm"] != null) {
                return ViewState["gm"] as ProgramGame;
            }

            var pg = Programs.FetchObject(patron.ProgID);
            var gm = ProgramGame.FetchObject(pg.ProgramGameID);
            ViewState["gm"] = gm;
            return gm;
        }
        public string GetMGIDs(Patron patron, Programs pgm, ProgramGame gm, int StartingPoints, int defMGID = 0, int whichMinigames = 1) {
            //Tally up the points  
            //var level = 0;
            //var points = 0;
            var bonus = false;
            string ret = defMGID == 0 ? "" : defMGID.ToString();
            var prefix1 = whichMinigames == 1 ? "1" : "2";
            var prefixBonus = bonus ? "Bonus" : "";

            if(pgm.ProgramGameID > 0) {
                // only if we have a game we can earn badges by reading ....
                var ds = ProgramGameLevel.GetAll(gm.PGID);

                var normalLevelTotalPoints = GetGameCompletionPoints(ds);
                //var bonusLevelTotalPoints = GetGameCompletionBonusPoints(ds, gm.BonusLevelPointMultiplier);

                bonus = (StartingPoints > normalLevelTotalPoints);

                // loop thru the levels to see where we are at ... before awarding the new points
                var rp = StartingPoints;   //remaining points
                if(bonus) {
                    prefixBonus = string.Empty;   // first do all non bonus levels
                    // if we are on the bonus, we have access to all of them
                    for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                        var MGIDfield = string.Format("Minigame{0}ID{1}", prefix1, prefixBonus);
                        if(Convert.ToInt32(ds.Tables[0].Rows[i][MGIDfield]) != 0) {
                            ret = string.Format("{0}{1}{2}", ret, (ret.Length > 0 ? "," : ""), Convert.ToInt32(ds.Tables[0].Rows[i][MGIDfield]));
                        }
                    }
                    rp = StartingPoints - normalLevelTotalPoints;
                }

                prefixBonus = bonus ? "Bonus" : "";
                // we have not tallied the bonus levels yet, or if not on bonus mode we have not tallied the regular levels yet ....
                for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                    var multiplier = (bonus ? gm.BonusLevelPointMultiplier : 1.00m);
                    var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
                    rp = rp - levelPoints;
                    if(rp < 0) {
                        return ret;
                        //break;
                    }
                    var MGIDfield = string.Format("Minigame{0}ID{1}", prefix1, prefixBonus);
                    if(Convert.ToInt32(ds.Tables[0].Rows[i][MGIDfield]) != 0) {
                        ret = string.Format("{0}{1}{2}", ret, (ret.Length > 0 ? "," : ""), Convert.ToInt32(ds.Tables[0].Rows[i][MGIDfield]));
                    }
                }
            }
            return ret;
        }
        public void LoadNextLevelInfo(Patron p, Programs pg, int tp) {
            int level, points;
            bool bonus;
            GetGameInfo(p, pg, tp, out level, out points, out bonus);

            lblNextLevel.Text =
                string.Format(
                    "I'm on <strong>{0}level: {1}</strong>.<br />I need <strong>{2} point{3}</strong> to level up.<br />",
                    bonus ? "bonus " : string.Empty,
                    level,
                    points,
                    points > 1 ? "s" : string.Empty);


        }
Exemplo n.º 6
0
 public bool EstablishPatron(Patron patron)
 {
     try {
         Session[SessionKey.Patron] = patron;
         Session["ProgramID"] = patron.ProgID;
         Session["TenantID"] = patron.TenID;
         Session[SessionKey.IsMasterAccount] = patron.IsMasterAccount;
         if(patron.IsMasterAccount) {
             Session["MasterAcctPID"] = patron.PID;
         } else {
             Session["MasterAcctPID"] = 0;
         }
         return true;
     } catch(Exception ex) {
         this.Log().Error(() => "Unable to establish patron session", ex);
         return false;
     }
 }
        protected void loginClick(object sender, EventArgs e) {
            if(!(string.IsNullOrEmpty(loginUsername.Text.Trim()) || string.IsNullOrEmpty(loginPassword.Text.Trim()))) {
                var patron = new Patron();
                if(Patron.Login(loginUsername.Text.Trim(), loginPassword.Text)) {
                    var bp = Patron.GetObjectByUsername(loginUsername.Text.Trim());

                    var pgm = DAL.Programs.FetchObject(bp.ProgID);
                    if(pgm == null) {
                        var progID = Programs.GetDefaultProgramForAgeAndGrade(bp.Age, bp.SchoolGrade.SafeToInt());
                        bp.ProgID = progID;
                        bp.Update();
                    }
                    new SessionTools(Session).EstablishPatron(bp);

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

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


                    if(ViewState[SessionKey.RequestedPath] != null) {
                        string requestedPath = ViewState[SessionKey.RequestedPath].ToString();
                        Response.Redirect(requestedPath);
                    } else {
                        Response.Redirect("~");
                    }
                } else {
                    Session[SessionKey.PatronMessage] = "Invalid username or password.";
                    Session[SessionKey.PatronMessageLevel] = PatronMessageLevels.Danger;
                    Session[SessionKey.PatronMessageGlyphicon] = "remove";
                    Session[SessionKey.Patron] = null;
                }
            }

        }
        public void GetGameInfo(Patron patron, Programs pgm, int StartingPoints, out int level, out int points, out bool bonus)
        {
            //Tally up the points
            level = 0;
            points = 0;
            bonus = false;
            if(pgm.ProgramGameID > 0) {
                // only if we have a game we can earn badges by reading ....
                var gm = ProgramGame.FetchObject(pgm.ProgramGameID);
                var ds = ProgramGameLevel.GetAll(gm.PGID);

                var normalLevelTotalPoints = GetGameCompletionPoints(ds);
                var bonusLevelTotalPoints = GetGameCompletionBonusPoints(ds, gm.BonusLevelPointMultiplier);

                bonus = (StartingPoints > normalLevelTotalPoints);

                // loop thru the levels to see where we are at ... before awarding the new points
                var rp = StartingPoints;   //remaining points
                if(bonus) {
                    // if we are on the bonus, eliminate the "fully completed boards/levels) and then see what the remainder of the points is.
                    rp = rp - normalLevelTotalPoints;
                    level = ds.Tables[0].Rows.Count + 1;   // completed all the levels for the "normal"

                    level = level + (int)((int)rp / (int)bonusLevelTotalPoints) * (ds.Tables[0].Rows.Count + 1);

                    rp = rp % bonusLevelTotalPoints;

                }

                for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                    var multiplier = (bonus ? gm.BonusLevelPointMultiplier : 1.00m);
                    var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
                    rp = rp - levelPoints;
                    if(rp < 0) {
                        points = -rp;
                        break;
                    }
                    level++;
                }
            }
        }
Exemplo n.º 9
0
        public string GetGameboardPath(Patron patron, int programGameId) {
            var patronPoints = PatronPoints.GetTotalPatronPoints(patron.PID);
            var programGameLevelDs = ProgramGameLevel.GetAll(programGameId);

            int normalLevelTotalPoints = 0;
            for(var i = 0; i < programGameLevelDs.Tables[0].Rows.Count; i++) {
                normalLevelTotalPoints +=
                    Convert.ToInt32(programGameLevelDs.Tables[0].Rows[i]["PointNumber"]);
            }
            var onBonusLevel = (patronPoints > normalLevelTotalPoints);

            var gameboardPath = onBonusLevel
                ? string.Format(BaseBonusGameBoardPath, programGameId)
                : string.Format(BaseGameBoardPath, programGameId);

            if(!File.Exists(HttpContext.Current.Server.MapPath(gameboardPath))) {
                return null;
            }

            return gameboardPath;
        }
Exemplo n.º 10
0
        public static Patron GetUserByToken(string token, int hoursWindow = 24)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT [PID] FROM [PatronRecovery] WHERE [Token] = @token ");
            sql.Append("AND DateDiff(hh, [Generated], GETDATE()) <= @hourswindow");

            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("token", token));
            parameters.Add(new SqlParameter("hourswindow", hoursWindow));

            object pidObject = null;
            try {
                pidObject = SqlHelper.ExecuteScalar(conn,
                                                    CommandType.Text,
                                                    sql.ToString(),
                                                    parameters.ToArray());
            } catch(Exception ex) {
                "Patron".Log().Error(() => string.Format("Unable to retrieve patron from token {0}",
                                                         token),
                                     ex);
                return null;
            }

            int pid = 0;
            if(pidObject == null
               || !int.TryParse(pidObject.ToString(), out pid)) {
                "SRPUser".Log().Error("Unable parse to parse PID {0}, returned value: {0}",
                                      pidObject,
                                      pid);
                return null;
            }

            Patron p = new Patron();
            if(p.Fetch(pid)) {
                return p;
            } else {
                return null;
            }
        }
Exemplo n.º 11
0
 public string GetGameboardPath(Patron patron) {
     var program = Programs.FetchObject(patron.ProgID);
     return GetGameboardPath(patron, program.ProgramGameID);
 }
        public string GetGameInfo(Patron patron, Programs pgm, ProgramGame gm, int StartingPoints) {
            //Tally up the points  
            //var level = 0;
            //var points = 0;
            var bonus = false;
            string ret = string.Empty;

            if(pgm.ProgramGameID > 0) {
                // only if we have a game we can earn badges by reading ....
                var ds = ProgramGameLevel.GetAll(gm.PGID);

                var normalLevelTotalPoints = GetGameCompletionPoints(ds);
                var bonusLevelTotalPoints = GetGameCompletionBonusPoints(ds, gm.BonusLevelPointMultiplier);

                bonus = (StartingPoints > normalLevelTotalPoints);

                // loop thru the levels to see where we are at ... before awarding the new points
                var rp = StartingPoints;   //remaining points
                if(bonus) {
                    // if we are on the bonus, we have access to all of them
                    for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                        ret = string.Format("{0}{1}{2}", ret, (ret.Length > 0 ? "," : ""),
                                            Convert.ToInt32(ds.Tables[0].Rows[i]["PGLID"]));

                    }
                    return ret;
                }

                // we have not completed the bonus yet ....
                for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                    var multiplier = (bonus ? gm.BonusLevelPointMultiplier : 1.00m);
                    var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
                    rp = rp - levelPoints;
                    if(rp < 0) {
                        return ret;
                        //break;
                    }
                    ret = string.Format("{0}{1}{2}", ret, (ret.Length > 0 ? "," : ""),
                                            Convert.ToInt32(ds.Tables[0].Rows[i]["PGLID"]));
                }
            }
            return ret;
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            Programs pgm = null;
            this.CurrentPatron = Session[SessionKey.Patron] as Patron;

            if (this.CurrentPatron != null)
            {
                pgm = DAL.Programs.FetchObject(this.CurrentPatron.ProgID);
                if (pgm == null)
                {
                    pgm = Programs.FetchObject(
                        Programs.GetDefaultProgramForAgeAndGrade(this.CurrentPatron.Age,
                            this.CurrentPatron.SchoolGrade.SafeToInt()));
                }
            }

            if (pgm == null || !pgm.IsOpen)
            {
                this.ProgramOpen = false;
                btnSave.Visible = false;
            }
            else
            {
                this.ProgramOpen = true;
            }
        }
Exemplo n.º 14
0
        public static bool AwardBadgeToPatron(int badgeToAward, Patron patron, ref List<Badge> earnedBadges)
        {
            var now = DateTime.Now;

            // check if badge was already earned...
            var pbds = PatronBadges.GetAll(patron.PID);
            var a = pbds.Tables[0].AsEnumerable().Where(r => r.Field<int>("BadgeID") == badgeToAward);

            var newTable = new DataTable();
            try { newTable = a.CopyToDataTable(); } catch { }

            // badge not found, award it!
            if(newTable.Rows.Count == 0) {
                var pb = new PatronBadges { BadgeID = badgeToAward, DateEarned = now, PID = patron.PID };
                pb.Insert();

                var earnedBadge = Badge.GetBadge(badgeToAward);
                if(earnedBadge != null) {
                    earnedBadges.Add(earnedBadge);

                    //if badge generates notification, then generate the notification
                    if(earnedBadge.GenNotificationFlag) {
                        var not = new Notifications {
                            PID_To = patron.PID,
                            PID_From = 0,  //0 == System Notification
                            Subject = earnedBadge.NotificationSubject,
                            Body = earnedBadge.NotificationBody,
                            isQuestion = false,
                            AddedDate = now,
                            LastModDate = now,
                            AddedUser = patron.Username,
                            LastModUser = "******"
                        };
                        not.Insert();
                    }

                    //if badge generates prize, then generate the prize
                    if(earnedBadge.IncludesPhysicalPrizeFlag) {
                        var ppp = new DAL.PatronPrizes {
                            PID = patron.PID,
                            PrizeSource = 1,
                            BadgeID = badgeToAward,
                            PrizeName = earnedBadge.PhysicalPrizeName,
                            RedeemedFlag = false,
                            AddedUser = patron.Username,
                            LastModUser = "******",
                            AddedDate = now,
                            LastModDate = now
                        };

                        ppp.Insert();
                    }

                    // if badge generates award code, then generate the code
                    if(earnedBadge.AssignProgramPrizeCode) {
                        var rewardCode= string.Empty;
                        // get the Code value
                        // save the code value for the patron
                        rewardCode = ProgramCodes.AssignCodeForPatron(patron.ProgID, patron.ProgID);

                        // generate the notification
                        var not = new Notifications {
                            PID_To = patron.PID,
                            PID_From = 0,  //0 == System Notification
                            Subject = earnedBadge.PCNotificationSubject,
                            Body = earnedBadge.PCNotificationBody.Replace("{ProgramRewardCode}", rewardCode),
                            isQuestion = false,
                            AddedDate = now,
                            LastModDate = now,
                            AddedUser = patron.Username,
                            LastModUser = "******"
                        };
                        not.Insert();
                    }
                }

                return true;
            } else {
                return false;
            }
        }
Exemplo n.º 15
0
        public Badge TallyPoints(Patron patron, Programs pgm, int StartingPoints, int EndingPoints, ref List<Badge> EarnedBadges)
        {
            Badge b = null;
            //Tally up the points and figure out if we need to award a badge.
            if(pgm.ProgramGameID > 0) {
                // only if we have a game we can earn badges by reading ....
                var gm = ProgramGame.FetchObject(pgm.ProgramGameID);
                var ds = ProgramGameLevel.GetAll(gm.PGID);

                var normalLevelTotalPoints = GetGameCompletionPoints(ds);
                var bonusLevelTotalPoints = GetGameCompletionBonusPoints(ds, gm.BonusLevelPointMultiplier);

                var bonus = (StartingPoints > normalLevelTotalPoints);
                var bonusPostfix = (bonus ? "Bonus" : "");
                int BeforeLevel = 0, AfterLevel = 0;

                // loop thru the levels to see where we are at ... before awarding the new points
                var rp = StartingPoints;   //remaining points
                if(bonus) {
                    // if we are on the bonus, eliminate the "fully completed boards/levels) and then see what the remainder of the points is.
                    rp = rp - normalLevelTotalPoints;
                    rp = rp % bonusLevelTotalPoints;
                }

                for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                    var multiplier = (bonus ? gm.BonusLevelPointMultiplier : 1.00m);
                    var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
                    rp = rp - levelPoints;
                    if(rp < 0) {
                        BeforeLevel = i;
                        break;
                    }
                }

                // loop thru the levels to see where we are at ... AFTER awarding the new points
                rp = EndingPoints;   //remaining points
                if(bonus) {
                    // if we are on the bonus, eliminate the "fully completed boards/levels) and then see what the remainder of the points is.
                    rp = rp - normalLevelTotalPoints;
                    rp = rp % bonusLevelTotalPoints;
                }
                for(var i = 0; i < ds.Tables[0].Rows.Count; i++) {
                    var multiplier = (bonus ? gm.BonusLevelPointMultiplier : 1.00m);
                    var levelPoints = Convert.ToInt32(Convert.ToInt32(ds.Tables[0].Rows[i]["PointNumber"]) * multiplier);
                    rp = rp - levelPoints;
                    AfterLevel = i;
                    if(rp < 0) {
                        break;
                    } else {
                        if(!((i + 1) < ds.Tables[0].Rows.Count)) {
                            AfterLevel = (i + 1);
                        }
                    }
                }

                if(BeforeLevel != AfterLevel) {
                    // completed the "beforeLevel" and moved up to the "AfterLevel" , so check if we need to award a badge
                    for(var i = BeforeLevel; i < AfterLevel; i++) {
                        var badgeToAward = Convert.ToInt32(ds.Tables[0].Rows[i]["AwardBadgeID" + bonusPostfix]);
                        if(badgeToAward > 0) {
                            b = Badge.GetBadge(badgeToAward);
                            EarnedBadges.Add(b);
                        }
                    }
                }
            }
            return b;
        }
Exemplo n.º 16
0
        public static bool AwardBadgeToPatronViaMatchingAwards(Patron patron, ref List<Badge> earnedBadges)
        {
            var retcode = false;
            var ds = Award.GetMatchingAwards(patron.PID);
            if(ds.Tables[0].Rows.Count > 0) {
                foreach(DataRow row in ds.Tables[0].Rows) {
                    var bid = Convert.ToInt32(row["BadgeID"]);
                    var ret = AwardBadgeToPatron(bid, patron, ref earnedBadges);

                    retcode = ret || retcode;
                }
            }

            return retcode;
        }
        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.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)) {
                    p.Insert();

                    var prog = Programs.FetchObject(p.ProgID);
                    var list = new List<Badge>();
                    if(prog.RegistrationBadgeID != 0) {
                        AwardPoints.AwardBadgeToPatron(prog.RegistrationBadgeID, p, ref list);
                    }
                    try {
                        this.Log().Debug("Running AwardBadgeToPatronViaMatchingAwards on patron ", p.PID);
                    } catch(Exception) { }

                    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;
        }
Exemplo n.º 18
0
        public bool Fetch(int PID)
        {
            // declare reader

            SqlDataReader dr;

            SqlParameter[] arrParams = new SqlParameter[1];

            arrParams[0] = new SqlParameter("@PID", PID);

            dr = SqlHelper.ExecuteReader(conn, CommandType.StoredProcedure, "app_Patron_GetByID", arrParams);

            if(dr.Read()) {

                // declare return value

                Patron result = new Patron();

                DateTime _datetime;

                int _int;

                //decimal _decimal;

                if(int.TryParse(dr["PID"].ToString(), out _int))
                    this.PID = _int;
                this.IsMasterAccount = bool.Parse(dr["IsMasterAccount"].ToString());
                if(int.TryParse(dr["MasterAcctPID"].ToString(), out _int))
                    this.MasterAcctPID = _int;
                this.Username = dr["Username"].ToString();
                if(DateTime.TryParse(dr["DOB"].ToString(), out _datetime))
                    this.DOB = _datetime;
                if(int.TryParse(dr["Age"].ToString(), out _int))
                    this.Age = _int;
                this.SchoolGrade = dr["SchoolGrade"].ToString();
                if(int.TryParse(dr["ProgID"].ToString(), out _int))
                    this.ProgID = _int;
                this.FirstName = dr["FirstName"].ToString();
                this.MiddleName = dr["MiddleName"].ToString();
                this.LastName = dr["LastName"].ToString();
                this.Gender = dr["Gender"].ToString();
                this.EmailAddress = dr["EmailAddress"].ToString();
                this.PhoneNumber = dr["PhoneNumber"].ToString();
                this.StreetAddress1 = dr["StreetAddress1"].ToString();
                this.StreetAddress2 = dr["StreetAddress2"].ToString();
                this.City = dr["City"].ToString();
                this.State = dr["State"].ToString();
                this.ZipCode = dr["ZipCode"].ToString();
                this.Country = dr["Country"].ToString();
                this.County = dr["County"].ToString();
                this.ParentGuardianFirstName = dr["ParentGuardianFirstName"].ToString();
                this.ParentGuardianLastName = dr["ParentGuardianLastName"].ToString();
                this.ParentGuardianMiddleName = dr["ParentGuardianMiddleName"].ToString();
                if(int.TryParse(dr["PrimaryLibrary"].ToString(), out _int))
                    this.PrimaryLibrary = _int;
                this.LibraryCard = dr["LibraryCard"].ToString();
                this.SchoolName = dr["SchoolName"].ToString();
                this.District = dr["District"].ToString();
                this.Teacher = dr["Teacher"].ToString();
                this.GroupTeamName = dr["GroupTeamName"].ToString();
                if(int.TryParse(dr["SchoolType"].ToString(), out _int))
                    this.SchoolType = _int;
                if(int.TryParse(dr["LiteracyLevel1"].ToString(), out _int))
                    this.LiteracyLevel1 = _int;
                if(int.TryParse(dr["LiteracyLevel2"].ToString(), out _int))
                    this.LiteracyLevel2 = _int;
                this.ParentPermFlag = bool.Parse(dr["ParentPermFlag"].ToString());
                this.Over18Flag = bool.Parse(dr["Over18Flag"].ToString());
                this.ShareFlag = bool.Parse(dr["ShareFlag"].ToString());
                this.TermsOfUseflag = bool.Parse(dr["TermsOfUseflag"].ToString());
                this.Custom1 = dr["Custom1"].ToString();
                this.Custom2 = dr["Custom2"].ToString();
                this.Custom3 = dr["Custom3"].ToString();
                this.Custom4 = dr["Custom4"].ToString();
                this.Custom5 = dr["Custom5"].ToString();
                if(int.TryParse(dr["AvatarID"].ToString(), out _int))
                    this.AvatarID = _int;
                if(int.TryParse(dr["SDistrict"].ToString(), out _int))
                    this.SDistrict = _int;

                if(int.TryParse(dr["TenID"].ToString(), out _int))
                    this.TenID = _int;
                if(int.TryParse(dr["FldInt1"].ToString(), out _int))
                    this.FldInt1 = _int;
                if(int.TryParse(dr["FldInt2"].ToString(), out _int))
                    this.FldInt2 = _int;
                if(int.TryParse(dr["FldInt3"].ToString(), out _int))
                    this.FldInt3 = _int;
                this.FldBit1 = bool.Parse(dr["FldBit1"].ToString());
                this.FldBit2 = bool.Parse(dr["FldBit2"].ToString());
                this.FldBit3 = bool.Parse(dr["FldBit3"].ToString());
                this.FldText1 = dr["FldText1"].ToString();
                this.FldText2 = dr["FldText2"].ToString();
                this.FldText3 = dr["FldText3"].ToString();

                if(int.TryParse(dr["Score1"].ToString(), out _int))
                    this.Score1 = _int;
                if(int.TryParse(dr["Score2"].ToString(), out _int))
                    this.Score2 = _int;
                var _decimal = (decimal)0.0;
                if(decimal.TryParse(dr["Score1Pct"].ToString(), out _decimal))
                    this.Score1Pct = _decimal;
                if(decimal.TryParse(dr["Score2Pct"].ToString(), out _decimal))
                    this.Score2Pct = _decimal;
                if(DateTime.TryParse(dr["Score1Date"].ToString(), out _datetime))
                    this.Score1Date = _datetime;
                if(DateTime.TryParse(dr["Score2Date"].ToString(), out _datetime))
                    this.Score2Date = _datetime;

                dr.Close();

                return true;

            }

            dr.Close();

            return false;
        }
Exemplo n.º 19
0
        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)
                        {
                            pgc = temp;
                        }
                    }

                    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 bool RegisterPatron() {
            var patron = new Patron();
            patron.ProgID = Programs.GetDefaultProgramForAgeAndGrade(0, 0);
            patron.Username = Username.Text;
            patron.NewPassword = Password.Text;
            // hardcoding over 18 because there's no facility to ask here
            patron.Over18Flag = true;
            patron.FirstName = FirstName.Text.Trim();
            patron.LastName = LastName.Text.Trim();
            patron.EmailAddress = EmailAddress.Text.Trim();
            patron.LibraryCard = LibraryCard.Text.Replace(" ", "");
            int primaryLibrary = 0;
            if(int.TryParse(PrimaryLibrary.SelectedValue, out primaryLibrary)) {
                patron.PrimaryLibrary = primaryLibrary;
            }
            if(!string.IsNullOrEmpty(MasterPID.Text)) {
                int masterPid = 0;
                if(int.TryParse(MasterPID.Text, out masterPid)) {
                    var masterPatron = Patron.FetchObject(masterPid);
                    if(!masterPatron.IsMasterAccount) {
                        masterPatron.IsMasterAccount = true;
                        masterPatron.Update();
                        new SessionTools(Session).EstablishPatron(masterPatron);
                    }
                    patron.MasterAcctPID = masterPid;
                    patron.ParentGuardianFirstName = masterPatron.FirstName;
                    patron.ParentGuardianLastName = masterPatron.LastName;
                }
            }
            try {
                if(patron.IsValid(BusinessRulesValidationMode.INSERT)) {
                    patron.Insert();
                    this.Log().Info("New participant: {0} {1} ({2})",
                                    patron.FirstName,
                                    patron.LastName,
                                    patron.LibraryCard);
                } else {
                    StringBuilder message = new StringBuilder("<strong>");
                    message.AppendFormat(SRPResources.ApplicationError1, "<ul>");
                    foreach(BusinessRulesValidationMessage m in patron.ErrorCodes) {
                        this.Log().Warn("Business rule error creating patron: {0}", m.ErrorMessage);
                        message.AppendFormat("<li>{0}</li>", m.ErrorMessage);
                    }
                    message.Append("</ul></strong>");
                    new SessionTools(Session).AlertPatron(
                        message.ToString(),
                        PatronMessageLevels.Warning,
                        "exclamation-sign");
                    return false;
                }

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

                if(string.IsNullOrEmpty(MasterPID.Text)) {
                    EarnedBadges.Text = string.Join("|", earnedBadgesList.Select(b => b.BID).Distinct());
                    MasterPID.Text = patron.PID.ToString();
                    new SessionTools(Session).EstablishPatron(patron);
                } else {
                    new SessionTools(Session).AlertPatron(
                        string.Format("Account created for: <strong>{0}</strong>",
                            DisplayHelper.FormatName(
                                patron.FirstName,
                                patron.LastName,
                                patron.Username)),
                        glyphicon: "thumbs-up");
                }
            } catch(Exception ex) {
                this.Log().Error(string.Format("A problem occurred during registration: {0}",
                                               ex.Message));
                new SessionTools(Session).AlertPatron(
                    string.Format("<strong>{0}</strong>", ex.Message),
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return false;
            }
            return true;
        }
        protected void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var masterPage = (IControlRoomMaster)((BaseControlRoomPage)Page).Master;
            if (e.CommandName.ToLower() == "back")
            {
                Response.Redirect("Default.aspx");
            }
            if (e.CommandName.ToLower() == "refresh")
            {
                LoadControl();
                if (masterPage != null) masterPage.PageMessage = SRPResources.RefreshOK;
                return;
            }

            lblError.Text = string.Empty;
            Page.Validate();
            if (Page.IsValid)
            {
                if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback")
                {
                    var p = new Patron();
                    if (!IsAdd())
                    {
                        p = Patron.FetchObject(int.Parse(SA.Text));
                    }

                    DateTime _d;

                    p.Username = ((TextBox)(e.Item).FindControl("Username")).Text;
                    var password = ((TextBox)(e.Item).FindControl("Password")).Text;
                    if (!password.StartsWith(PasswordFiller) && !password.EndsWith(PasswordFiller))
                    {
                        p.NewPassword = password;
                    }

                    var DOB = e.Item.FindControl("DOB") as TextBox;
                    if (DOB != null && 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.MasterAcctPID = int.Parse(MasterPatronID);

                    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;

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

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

                    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 = ((TextBox)(e.Item).FindControl("LiteracyLevel1")).Text.SafeToInt();
                    p.LiteracyLevel2 = ((TextBox)(e.Item).FindControl("LiteracyLevel2")).Text.SafeToInt();
                    try
                    {
                        p.ParentPermFlag = ((CheckBox)(e.Item).FindControl("ParentPermFlag")).Checked;
                        p.Over18Flag = ((CheckBox)(e.Item).FindControl("Over18Flag")).Checked;
                        p.ShareFlag = ((CheckBox)(e.Item).FindControl("ShareFlag")).Checked;
                        p.TermsOfUseflag = ((CheckBox)(e.Item).FindControl("TermsOfUseflag")).Checked;
                    }
                    catch { }



                    var cr = CustomRegistrationFields.FetchObject();
                    p.Custom1 = cr.DDValues1 == "" ? ((TextBox)(e.Item).FindControl("Custom1")).Text : ((DropDownList)(e.Item).FindControl("Custom1DD")).SelectedValue;
                    p.Custom2 = cr.DDValues2 == "" ? ((TextBox)(e.Item).FindControl("Custom2")).Text : ((DropDownList)(e.Item).FindControl("Custom2DD")).SelectedValue;
                    p.Custom3 = cr.DDValues3 == "" ? ((TextBox)(e.Item).FindControl("Custom3")).Text : ((DropDownList)(e.Item).FindControl("Custom3DD")).SelectedValue;
                    p.Custom4 = cr.DDValues4 == "" ? ((TextBox)(e.Item).FindControl("Custom4")).Text : ((DropDownList)(e.Item).FindControl("Custom4DD")).SelectedValue;
                    p.Custom5 = cr.DDValues5 == "" ? ((TextBox)(e.Item).FindControl("Custom5")).Text : ((DropDownList)(e.Item).FindControl("Custom5DD")).SelectedValue;

                    p.ProgID = FormatHelper.SafeToInt(((DropDownList)e.Item.FindControl("ProgID")).SelectedValue);
                    p.IsMasterAccount = ((CheckBox)(e.Item).FindControl("IsMasterAccount")).Checked;
                    // do the save

                    p.SuppressFromFeed = ((CheckBox)(e.Item).FindControl("SuppressFromFeed")).Checked;

                    if (IsAdd())
                    {
                        if (p.IsValid(BusinessRulesValidationMode.INSERT))
                        {
                            p.Insert();
                            PatronID = p.PID.ToString();
                            SA.Text = PatronID;
                            Session["CURR_PATRON_MODE"] = "EDIT";
                            LoadControl();

                            masterPage.PageMessage = SRPResources.AddedOK;

                            if (e.CommandName.ToLower() == "saveandback")
                            {
                                Response.Redirect("Default.aspx");
                            }
                        }
                        else
                        {
                            string message = String.Format(SRPResources.ApplicationError1, "<ul>");
                            foreach (BusinessRulesValidationMessage m in p.ErrorCodes)
                            {
                                message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                            }
                            message = string.Format("{0}</ul>", message);
                            masterPage.PageError = message;
                        }

                        var parent = Patron.FetchObject(p.MasterAcctPID);
                        if (parent != null && !parent.IsMasterAccount)
                        {
                            parent.IsMasterAccount = true;
                            parent.Update();
                            Session["CURR_PATRON"] = parent;
                            PatronsRibbon.GetByAppContext((BaseControlRoomPage)Page);
                        }
                    }
                    else
                    {
                        if (p.IsValid(BusinessRulesValidationMode.UPDATE))
                        {
                            p.Update();
                            masterPage.PageMessage = SRPResources.SaveOK;

                            if (e.CommandName.ToLower() == "saveandback")
                            {
                                Response.Redirect("Default.aspx");
                            }
                            else
                            {
                                LoadControl();
                            }
                        }
                        else
                        {
                            string message = String.Format(SRPResources.ApplicationError1, "<ul>");
                            foreach (BusinessRulesValidationMessage m in p.ErrorCodes)
                            {
                                message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                            }
                            message = string.Format("{0}</ul>", message);
                            masterPage.PageError = message;
                        }

                    }

                }
            }
        }
        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;
        }