Example #1
0
        /// <summary>
        /// singature签名的生成比较麻烦。
        /// 首先生成获取access_token
        /// (有效期7200秒,开发者必须在自己的服务全局缓存access_token)
        /// </summary>
        /// <returns></returns>
        public static string Getaccesstoken()
        {
            string         appid     = PayConfig.WxAppid();
            string         secret    = PayConfig.WxAppSecret();
            string         urljson   = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            string         strjson   = "";
            UTF8Encoding   encoding  = new UTF8Encoding();
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urljson);

            myRequest.Method      = "GET";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response;
            Stream          responseStream;
            StreamReader    reader;
            string          srcString;

            response       = myRequest.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader         = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString      = reader.ReadToEnd();
            reader.Close();
            if (srcString.Contains("access_token"))
            {
                //CommonJsonModel model = new CommonJsonModel(srcString);
                CommonJsonModel model = new CommonJsonModel(srcString);
                strjson = model.GetValue("access_token");
                SessionTools.SetSession("access_tokenzj", strjson);
            }
            return(strjson);
        }
        protected void GvRowCommand(object sender, GridViewCommandEventArgs e)
        {
            string editpage = "~/ControlRoom/Modules/Setup/EventAddEdit.aspx";
            string addpage  = "~/ControlRoom/Modules/Setup/EventAddWizard.aspx";

            if (e.CommandName.ToLower() == "addrecord")
            {
                Session["EID"] = string.Empty; Response.Redirect(addpage);
            }
            if (e.CommandName.ToLower() == "editrecord")
            {
                int key = Convert.ToInt32(e.CommandArgument);
                Session["EID"] = key; Response.Redirect(editpage);
            }
            if (e.CommandName.ToLower() == "deleterecord")
            {
                var key = Convert.ToInt32(e.CommandArgument);
                try
                {
                    var obj = new Event();
                    if (obj.IsValid(BusinessRulesValidationMode.DELETE))
                    {
                        obj.FetchObject(key).Delete();
                        var st = new SessionTools(Session);
                        st.RemoveCache(Cache, CacheKey.EventsActive);
                        st.RemoveCache(Cache, CacheKey.AllEvents);
                        LoadData();
                        var masterPage = (IControlRoomMaster)Master;
                        if (masterPage != null)
                        {
                            masterPage.PageMessage = SRPResources.DeleteOK;
                        }
                    }
                    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);
                        if (masterPage != null)
                        {
                            masterPage.PageError = message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                    {
                        masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                    }
                }
            }
        }
Example #3
0
        private void Event_MapMouseMove(object sender, MouseEventArgs e)
        {
            var mouseScreenCoordinates = OutlandAreaCommon.Tools.ToRelativeCoordinates(e.Location, _screenParameters.Center);

            var mouseMapCoordinates = OutlandAreaCommon.Tools.ToTacticalMapCoordinates(mouseScreenCoordinates, _screenParameters.CenterScreenOnMap);

            var celestialObjectInRange = SessionTools.GetObjectInRange(_gameSession, 15, new PointF(mouseMapCoordinates.X, mouseMapCoordinates.Y));

            MouseMoveCelestialObject = celestialObjectInRange?.DeepClone();
        }
 public void DeleteTemporaryEvent()
 {
     try
     {
         var e = Event.GetEvent(int.Parse(lblPK.Text));
         e.Delete();
         var st = new SessionTools(Session);
         st.RemoveCache(Cache, CacheKey.EventsActive);
         st.RemoveCache(Cache, CacheKey.AllEvents);
     }
     catch { }
 }
 public void DeleteTemporaryEvent()
 {
     try
     {
         var e = Event.GetEvent(int.Parse(lblPK.Text));
         e.Delete();
         var st = new SessionTools(Session);
         st.RemoveCache(Cache, CacheKey.EventsActive);
         st.RemoveCache(Cache, CacheKey.AllEvents);
     }
     catch { }
 }
Example #6
0
        private void MapMouseMove(object sender, MouseEventArgs e)
        {
            Logger.Debug(TraceMessage.Execute(this, $"MapMouseMove]"));

            mouseCoordinates = e.Location;

            var mouseCoordinatesInternal = OutlandAreaCommon.Tools.ToRelativeCoordinates(e.Location, _screenParameters.Center);

            var mouseMapCoordinates = OutlandAreaCommon.Tools.ToTacticalMapCoordinates(mouseCoordinatesInternal, _screenParameters.CenterScreenOnMap);

            var celestialObjectInRange = SessionTools.GetObjectInRange(_gameSession, 15, new PointF(mouseMapCoordinates.X, mouseMapCoordinates.Y));

            MouseMoveCelestialObject = celestialObjectInRange?.DeepClone();
        }
Example #7
0
        /// <summary>
        /// 最后生成signature:
        /// </summary>
        /// <param name="nonceStr"></param>
        /// <param name="timespanstr"></param>
        /// <returns></returns>
        public static string Getsignature(string nonceStr, string timespanstr)
        {
            if (SessionTools.GetSession("access_tokenzj") == null)
            {
                Getaccesstoken();
            }
            if (SessionTools.GetSession("ticketzj") == null)
            {
                Getjsapi_ticket();
            }
            //string url = HttpContext.Current.Request.Url.ToString();
            //string url = PayConfig.WebSiteDomain() + HttpContext.Current.Request.ApplicationPath;
            string url = PayConfig.WebSiteDomain() + HttpContext.Current.Request.RawUrl;
            string str = "jsapi_ticket=" + (string)SessionTools.GetSession("ticketzj") + "&noncestr=" + nonceStr +
                         "&timestamp=" + timespanstr + "&url=" + url;// +"&wxref=mp.weixin.qq.com";
            string singature = SHA1Util.getSha1(str);

            return(singature.ToLower());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var patron = Session[SessionKey.Patron] as DAL.Patron;
                if (patron == null)
                {
                    return;
                }

                var program = DAL.Programs.FetchObject(patron.ProgID);
                if (program == null
                    || !program.IsOpen
                    || !program.DisplayDailyImage
                    || DateTime.Now < program.LoggingStart
                    || DateTime.Now > program.LoggingEnd)
                {
                    return;
                }

                string imagePath = string.Format(DailyImagePath,
                    program.PID,
                    (DateTime.Now - program.LoggingStart).Days + 1);

                if (System.IO.File.Exists(Server.MapPath(imagePath)))
                {
                    DailyImageButton.HRef = Page.ResolveUrl(imagePath);
                    DailyImageButton.Visible = true;
                }
                else
                {
                    var sessionTools = new SessionTools(Session);
                    var cached = sessionTools.GetCache(Cache, "LoggedAboutDailyImage");
                    if (cached == null)
                    {
                        this.Log().Warn("Unable to show daily image - file doesn't exist: {0}",
                            Server.MapPath(imagePath));
                        sessionTools.SetCache(Cache, "LoggedAboutDailyImage", true);
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var patron = Session[SessionKey.Patron] as DAL.Patron;
                if (patron == null)
                {
                    return;
                }

                var program = DAL.Programs.FetchObject(patron.ProgID);
                if (program == null ||
                    !program.IsOpen ||
                    !program.DisplayDailyImage ||
                    DateTime.Now < program.LoggingStart ||
                    DateTime.Now > program.LoggingEnd)
                {
                    return;
                }

                string imagePath = string.Format(DailyImagePath,
                                                 program.PID,
                                                 (DateTime.Now - program.LoggingStart).Days + 1);

                if (System.IO.File.Exists(Server.MapPath(imagePath)))
                {
                    DailyImageButton.HRef    = Page.ResolveUrl(imagePath);
                    DailyImageButton.Visible = true;
                }
                else
                {
                    var sessionTools = new SessionTools(Session);
                    var cached       = sessionTools.GetCache(Cache, "LoggedAboutDailyImage");
                    if (cached == null)
                    {
                        this.Log().Warn("Unable to show daily image - file doesn't exist: {0}",
                                        Server.MapPath(imagePath));
                        sessionTools.SetCache(Cache, "LoggedAboutDailyImage", true);
                    }
                }
            }
        }
Example #10
0
        private void MapClick(object sender, MouseEventArgs e)
        {
            var mouseScreenCoordinates = OutlandAreaCommon.Tools.ToRelativeCoordinates(e.Location, _screenParameters.Center);

            var mouseMapCoordinates = OutlandAreaCommon.Tools.ToTacticalMapCoordinates(mouseScreenCoordinates, _screenParameters.CenterScreenOnMap);

            var celestialObjectInRange = SessionTools.GetObjectInRange(_gameSession, 15, new PointF(mouseMapCoordinates.X, mouseMapCoordinates.Y));

            //PointInSpace = new Point(0, 0);

            if (celestialObjectInRange != null)
            {
                Global.Game.SelectCelestialObject(celestialObjectInRange);
            }
            else
            {
                Global.Game.SelectPointInSpace(mouseMapCoordinates);
                //PointInSpace = mouseMapCoordinates;
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (!(string.IsNullOrEmpty(NPassword.Text.Trim())))
                {
                    var patron = (Patron)Session["Patron"];
                    if (!Patron.VerifyPassword(patron.Username, CPass.Text.Trim()))
                    {
                        new SessionTools(Session).AlertPatron("That's not your current password, please try entering your current password again.",
                                                              PatronMessageLevels.Danger, "remove");

                        CPass.Attributes.Add("Value", CPass.Text);
                        NPassword.Attributes.Add("Value", NPassword.Text);
                        NPasswordR.Attributes.Add("Value", NPasswordR.Text);
                        return;
                    }

                    if (NPassword.Text.Trim() != NPasswordR.Text.Trim())
                    {
                        new SessionTools(Session).AlertPatron("New password and new password validation do not match.",
                                                              PatronMessageLevels.Danger, "remove");
                        CPass.Attributes.Add("Value", CPass.Text);
                        NPassword.Attributes.Add("Value", NPassword.Text);
                        NPasswordR.Attributes.Add("Value", NPasswordR.Text);
                        return;
                    }
                    patron.NewPassword = NPassword.Text.Trim();
                    patron.Update();

                    var st = new SessionTools(Session);

                    st.EstablishPatron(patron);
                    //Session["Patron"] = patron;
                    //Session["ProgramID"] = patron.ProgID;

                    st.AlertPatron("Your password has been updated!", glyphicon: "check");
                    Response.Redirect("~/Account/");
                }
            }
        }
Example #12
0
        public int UnreadCrMail(HttpContext context)
        {
            if (context.Session == null)
            {
                return(0);
            }
            var tenant   = context.Session[GRA.SRP.ControlRoom.CRSessionKey.TenantID];
            int tenantId = tenant as int? ?? -1;

            if (tenantId == -1)
            {
                return(0);
            }

            var sessionTool = new SessionTools(context.Session);
            var cachedFeed  = sessionTool.GetCache(context.Cache,
                                                   GRA.SRP.ControlRoom.CRSessionKey.UnreadMail,
                                                   tenantId) as int?;

            if (cachedFeed != null)
            {
                return((int)cachedFeed);
            }
            else
            {
                var unread = SRP.DAL.Notifications.GetAllUnreadToPatron(0);
                if (unread != null && unread.Tables.Count > 0)
                {
                    int unreadMessages = unread.Tables[0].Rows.Count;
                    sessionTool.SetCache(context.Cache,
                                         GRA.SRP.ControlRoom.CRSessionKey.UnreadMail,
                                         unreadMessages,
                                         tenantId,
                                         60);
                    return(unreadMessages);
                }
                return(0);
            }
        }
Example #13
0
        public int UnreadCrMail(HttpContext context)
        {
            if (context.Session == null)
            {
                return 0;
            }
            var tenant = context.Session[GRA.SRP.ControlRoom.CRSessionKey.TenantID];
            int tenantId = tenant as int? ?? -1;
            if (tenantId == -1)
            {
                return 0;
            }

            var sessionTool = new SessionTools(context.Session);
            var cachedFeed = sessionTool.GetCache(context.Cache,
                GRA.SRP.ControlRoom.CRSessionKey.UnreadMail,
                tenantId) as int?;
            if (cachedFeed != null)
            {
                return (int)cachedFeed;
            }
            else
            {
                var unread = SRP.DAL.Notifications.GetAllUnreadToPatron(0);
                if (unread != null && unread.Tables.Count > 0)
                {
                    int unreadMessages = unread.Tables[0].Rows.Count;
                    sessionTool.SetCache(context.Cache,
                        GRA.SRP.ControlRoom.CRSessionKey.UnreadMail,
                        unreadMessages,
                        tenantId,
                        60);
                    return unreadMessages;
                }
                return 0;
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e) {
            if(Page.IsValid) {
                if(!(string.IsNullOrEmpty(NPassword.Text.Trim()))) {
                    var patron = (Patron)Session["Patron"];
                    if(!Patron.VerifyPassword(patron.Username, CPass.Text.Trim())) {
                        new SessionTools(Session).AlertPatron("That's not your current password, please try entering your current password again.",
                            PatronMessageLevels.Danger, "remove");

                        CPass.Attributes.Add("Value", CPass.Text);
                        NPassword.Attributes.Add("Value", NPassword.Text);
                        NPasswordR.Attributes.Add("Value", NPasswordR.Text);
                        return;
                    }

                    if(NPassword.Text.Trim() != NPasswordR.Text.Trim()) {
                        new SessionTools(Session).AlertPatron("New password and new password validation do not match.",
                            PatronMessageLevels.Danger, "remove");
                        CPass.Attributes.Add("Value", CPass.Text);
                        NPassword.Attributes.Add("Value", NPassword.Text);
                        NPasswordR.Attributes.Add("Value", NPasswordR.Text);
                        return;
                    }
                    patron.NewPassword = NPassword.Text.Trim();
                    patron.Update();

                    var st = new SessionTools(Session);

                    st.EstablishPatron(patron);
                    //Session["Patron"] = patron;
                    //Session["ProgramID"] = patron.ProgID;

                    st.AlertPatron("Your password has been updated!", glyphicon: "check");
                    Response.Redirect("~/Account/");
                }
            }
        }
Example #15
0
        /// <summary>
        /// 接着获取jsapi_ticket:
        /// 用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket
        /// (有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket)
        /// </summary>
        /// <returns></returns>
        public static string Getjsapi_ticket()
        {
            string         accesstoken = (string)SessionTools.GetSession("access_tokenzj");
            string         urljson     = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi";
            string         strjson     = "";
            UTF8Encoding   encoding    = new UTF8Encoding();
            HttpWebRequest myRequest   = (HttpWebRequest)WebRequest.Create(urljson);

            myRequest.Method      = "GET";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response       = myRequest.GetResponse() as HttpWebResponse;
            Stream          responseStream = response.GetResponseStream();
            StreamReader    reader         = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            string          srcString      = reader.ReadToEnd();

            reader.Close();
            if (srcString.Contains("ticket"))
            {
                CommonJsonModel model = new CommonJsonModel(srcString);
                strjson = model.GetValue("ticket");
                SessionTools.SetSession("ticketzj", strjson);
            }
            return(strjson);
        }
        public void ProcessRequest(HttpContext context)
        {
            var tenant   = context.Session["TenantID"];
            int tenantId = tenant as int? ?? -1;

            if (tenantId == -1)
            {
                tenantId = Core.Utilities.Tenant.GetMasterID();
            }

            var sessionTool = new SessionTools(context.Session);
            var cachedFeed  = sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) as JsonFeed;

            try
            {
                if (cachedFeed != null)
                {
                    context.Response.ContentType = "application/json";
                    context.Response.Write(JsonConvert.SerializeObject(cachedFeed));
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Log().Error("Error looking up feed data in cache: {0}", ex.Message);
            }

            var jsonResponse = new JsonFeed();
            var entries      = new List <JsonFeedEntry>();

            int after = 0;

            int.TryParse(context.Request.QueryString["after"], out after);

            try
            {
                var feed = new ActivityFeed().Latest(after, tenantId);
                foreach (DataRow dataRow in feed.Rows)
                {
                    var entry = new JsonFeedEntry
                    {
                        ID                 = (int)dataRow["PPID"],
                        PatronId           = (int)dataRow["PID"],
                        Username           = (string)dataRow["Username"],
                        AwardedAt          = ((DateTime)dataRow["AwardDate"]).ToString(),
                        AwardReasonId      = (int)dataRow["AwardReasonCd"],
                        BadgeId            = (int)dataRow["BadgeId"],
                        ChallengeId        = dataRow["BLID"] == DBNull.Value ? 0 : (int)dataRow["BLID"],
                        ChallengeProgramId = dataRow["BLProgID"] == DBNull.Value ? 0 : (int)dataRow["BLProgID"],
                        AvatarState        = dataRow["AvatarState"] == DBNull.Value ? string.Empty : (string)dataRow["AvatarState"]
                    };

                    if (entry.ID > jsonResponse.Latest)
                    {
                        jsonResponse.Latest = entry.ID;
                    }

                    switch (entry.AwardReasonId)
                    {
                    case 1:
                        // got badge
                        entry.AchievementName = (string)dataRow["BadgeName"];
                        break;

                    case 2:
                        // completed challenge
                        entry.AchievementName = (string)dataRow["ListName"];
                        break;

                    case 4:
                        entry.AchievementName = (string)dataRow["GameName"];
                        break;
                    }
                    entries.Add(entry);
                }

                jsonResponse.Entries = entries.ToArray();
                jsonResponse.Success = true;
            }
            catch (Exception ex)
            {
                this.Log().Error("Error loading feed: {0}", ex.Message);
                jsonResponse.Success = false;
            }

            if (jsonResponse.Success)
            {
                try
                {
                    DateTime cacheUntil = DateTime.UtcNow.AddSeconds(30);
                    if (sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) == null)
                    {
                        //this.Log().Debug("Caching feed data until {0}",
                        //                 cacheUntil.ToLocalTime().ToLongTimeString());
                        string tenantCacheKey = sessionTool.GetTenantCacheKey(CacheKey.Feed, tenantId);
                        context.Cache.Insert(tenantCacheKey,
                                             jsonResponse,
                                             null,
                                             cacheUntil,
                                             System.Web.Caching.Cache.NoSlidingExpiration,
                                             System.Web.Caching.CacheItemPriority.Default,
                                             null);
                    }
                }
                catch (Exception ex)
                {
                    this.Log().Error("Error caching feed response: {0}", ex.Message);
                }
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(jsonResponse));
        }
        protected void Save_Click(object sender, EventArgs e)
        {
            var st = new SessionTools(Session);
            var sessionPatron = (Patron)Session[SessionKey.Patron];
            if (Username.Text.Trim().Equals(sessionPatron.Username))
            {
                st.AlertPatron("You cannot add yourself as a family member to your own family.",
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return;
            }

            if (string.IsNullOrEmpty(Username.Text))
            {
                st.AlertPatron("In order to link an existing account to yours as a family member you must supply their username.",
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return;
            }

            if (string.IsNullOrEmpty(Password.Text))
            {
                st.AlertPatron("In order to link an existing account to yours as a family member you must supply their password.",
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return;
            }

            // validate password
            if (!Patron.VerifyPassword(Username.Text, Password.Text))
            {
                // log invalid attempts
                this.Log().Info("Invalid credentials provided by {0}/{1} to try to link a family member.",
                    sessionPatron.Username,
                    sessionPatron.PID);
                st.AlertPatron("The username and password you supplied are not valid.",
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return;
            }

            var familyMemberPatron = Patron.GetObjectByUsername(Username.Text);

            if(familyMemberPatron.MasterAcctPID == sessionPatron.PID)
            {
                this.Log().Info("Attempt by {0}/{1} to add family member {2}/{3} who is already linked.",
                    familyMemberPatron.Username,
                    familyMemberPatron.PID,
                    sessionPatron.Username,
                    sessionPatron.PID);
                st.AlertPatron(string.Format("{0} is already a member of your family!",
                        familyMemberPatron.Username),
                    PatronMessageLevels.Warning,
                    "exclamation-sign");
                return;

            }

            this.Log().Info("Correct credentials to make {0}/{1} a family member under {2}/{3}.",
                familyMemberPatron.Username,
                familyMemberPatron.PID,
                sessionPatron.Username,
                sessionPatron.PID);

            var currentPatron = Patron.GetObjectByUsername(sessionPatron.Username);
            if (!currentPatron.IsMasterAccount)
            {
                currentPatron.IsMasterAccount = true;
                this.Log().Info("Updating {0}/{1} to mark as head of family",
                    sessionPatron.Username,
                    sessionPatron.PID);
                currentPatron.Update();
                st.EstablishPatron(currentPatron);
            }

            var alreadyFamilyMembers = Patron.GetSubAccountList(familyMemberPatron.PID);
            int alreadyFamilyMemberCount = alreadyFamilyMembers.Tables[0].Rows.Count;

            if (alreadyFamilyMemberCount > 0)
            {
                this.Log().Info("{0}/{1} already had {2} family members, moving them all to {3}/{4}",
                    familyMemberPatron.Username,
                    familyMemberPatron.PID,
                    alreadyFamilyMemberCount,
                    sessionPatron.Username,
                    sessionPatron.PID);
                foreach (DataRow row in alreadyFamilyMembers.Tables[0].Rows)
                {
                    var alreadyFamilyPatron = Patron.GetObjectByUsername(row["Username"].ToString());
                    this.Log().Info("Marking {0}/{1} as a family member of {2}/{3} and saving...",
                        alreadyFamilyPatron.Username,
                        alreadyFamilyPatron.PID,
                        sessionPatron.Username,
                        sessionPatron.PID);
                    alreadyFamilyPatron.MasterAcctPID = currentPatron.PID;
                    alreadyFamilyPatron.IsMasterAccount = false;
                    alreadyFamilyPatron.Update();
                }
            }

            if (familyMemberPatron.IsMasterAccount)
            {
                this.Log().Info("{0}/{1} was already marked as a family head, marking as regular user",
                    familyMemberPatron.Username,
                    familyMemberPatron.PID);
                familyMemberPatron.IsMasterAccount = false;
            }

            familyMemberPatron.MasterAcctPID = sessionPatron.PID;

            this.Log().Info("Saving update to {0}/{1}...",
                familyMemberPatron.Username,
                familyMemberPatron.PID);
            familyMemberPatron.Update();

            if (alreadyFamilyMemberCount> 0)
            {
                st.AlertPatron(
                    string.Format("<strong>{0}</strong> and {1} other users are now members of your family!",
                        familyMemberPatron.Username,
                        alreadyFamilyMemberCount),
                    PatronMessageLevels.Success,
                    "thumbs-up");
            } else
            {
                st.AlertPatron(
                    string.Format("<strong>{0}</strong> is now a member of your family!",
                        familyMemberPatron.Username),
                    PatronMessageLevels.Success,
                    "thumbs-up");
            }
            Response.Redirect("~/Account/FamilyAccountList.aspx");
        }
        protected void DoFilter(EventSearchCriteria criteria)
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(criteria.StartDate))
            {
                sb.Append("Start Date: ");
                sb.Append("<strong>");
                sb.Append(criteria.StartDate);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrEmpty(criteria.EndDate))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("End date: ");
                sb.Append("<strong>");
                sb.Append(criteria.EndDate);
                sb.Append("</strong>");
            }
            if (criteria.SystemId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("System: ");
                sb.Append("<strong>");
                sb.Append(SystemId.Items.FindByValue(criteria.SystemId.ToString()).Text);
                sb.Append("</strong>");
            }
            if (criteria.BranchId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Branch/library: ");
                sb.Append("<strong>");
                sb.Append(criteria.BranchName);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrWhiteSpace(criteria.SearchText))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Search text: ");
                sb.Append("<strong>");
                sb.Append(criteria.SearchText);
                sb.Append("</strong>");
            }

            WhatsShowing.Text = WhatsShowingPrint.Text = sb.ToString();
            WhatsShowingPanel.Visible = Filtered = !string.IsNullOrEmpty(WhatsShowing.Text);

            if (string.IsNullOrEmpty(WhatsShowing.Text))
            {
                // no filter criteria, use cache if possible
                var st = new SessionTools(Session);
                var cachedEvents = st.GetCache(Cache, CacheKey.AllEvents) as System.Data.DataSet;
                if (cachedEvents != null)
                {
                    rptr.DataSource = cachedEvents;
                }
                else
                {
                    var allEvents = Event.GetUpcomingDisplay(
                        criteria.StartDate,
                        criteria.EndDate,
                        criteria.SystemId,
                        criteria.BranchId,
                        criteria.SearchText);
                    rptr.DataSource = allEvents;

                    string tenantCacheKey = st.GetTenantCacheKey(CacheKey.AllEvents);
                    Cache.Insert(tenantCacheKey,
                        allEvents,
                        null,
                        DateTime.UtcNow.AddHours(2),
                        System.Web.Caching.Cache.NoSlidingExpiration,
                        System.Web.Caching.CacheItemPriority.Default,
                        null);
                }
            }
            else
            {
                rptr.DataSource = Event.GetUpcomingDisplay(
                    criteria.StartDate,
                    criteria.EndDate,
                    criteria.SystemId,
                    criteria.BranchId,
                    criteria.SearchText);
            }
            rptr.DataBind();

            var wt = new WebTools();
            if (Filtered)
            {
                StartDate.CssClass = wt.CssEnsureClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass = wt.CssEnsureClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssEnsureClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass = wt.CssEnsureClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssEnsureClass(SearchText.CssClass, "gra-search-active");
            }
            else
            {
                StartDate.CssClass = wt.CssRemoveClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass = wt.CssRemoveClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass = wt.CssRemoveClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
            }
        }
 protected void GvRowCommand(object sender, GridViewCommandEventArgs e)
 {
     string editpage = "~/ControlRoom/Modules/Setup/EventAddEdit.aspx";
     string addpage = "~/ControlRoom/Modules/Setup/EventAddWizard.aspx";
     if (e.CommandName.ToLower() == "addrecord")
     {
         Session["EID"] = string.Empty; Response.Redirect(addpage);
     }
     if (e.CommandName.ToLower() == "editrecord")
     {
         int key = Convert.ToInt32(e.CommandArgument);
         Session["EID"] = key; Response.Redirect(editpage);
     }
     if (e.CommandName.ToLower() == "deleterecord")
     {
         var key = Convert.ToInt32(e.CommandArgument);
         try
         {
             var obj = new Event();
             if (obj.IsValid(BusinessRulesValidationMode.DELETE))
             {
                 obj.FetchObject(key).Delete();
                 var st = new SessionTools(Session);
                 st.RemoveCache(Cache, CacheKey.EventsActive);
                 st.RemoveCache(Cache, CacheKey.AllEvents);
                 LoadData();
                 var masterPage = (IControlRoomMaster)Master;
                 if (masterPage != null) masterPage.PageMessage = SRPResources.DeleteOK;
             }
             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);
                 if (masterPage != null) masterPage.PageError = message;
             }
         }
         catch (Exception ex)
         {
             var masterPage = (IControlRoomMaster)Master;
             if (masterPage != null)
                 masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
         }
     }
 }
        protected void Save_Click(object sender, EventArgs e)
        {
            var st            = new SessionTools(Session);
            var sessionPatron = (Patron)Session[SessionKey.Patron];

            if (Username.Text.Trim().Equals(sessionPatron.Username))
            {
                st.AlertPatron("You cannot add yourself as a family member to your own family.",
                               PatronMessageLevels.Warning,
                               "exclamation-sign");
                return;
            }

            if (string.IsNullOrEmpty(Username.Text))
            {
                st.AlertPatron("In order to link an existing account to yours as a family member you must supply their username.",
                               PatronMessageLevels.Warning,
                               "exclamation-sign");
                return;
            }

            if (string.IsNullOrEmpty(Password.Text))
            {
                st.AlertPatron("In order to link an existing account to yours as a family member you must supply their password.",
                               PatronMessageLevels.Warning,
                               "exclamation-sign");
                return;
            }

            // validate password
            if (!Patron.VerifyPassword(Username.Text, Password.Text))
            {
                // log invalid attempts
                this.Log().Error("Invalid credentials provided by {0}/{1} to try to link a family member.",
                                 sessionPatron.Username,
                                 sessionPatron.PID);
                st.AlertPatron("The username and password you supplied are not valid.",
                               PatronMessageLevels.Warning,
                               "exclamation-sign");
                return;
            }

            var familyMemberPatron = Patron.GetObjectByUsername(Username.Text);

            if (familyMemberPatron.MasterAcctPID == sessionPatron.PID)
            {
                this.Log().Error("Attempt by {0}/{1} to add family member {2}/{3} who is already linked.",
                                 familyMemberPatron.Username,
                                 familyMemberPatron.PID,
                                 sessionPatron.Username,
                                 sessionPatron.PID);
                st.AlertPatron(string.Format("{0} is already a member of your family!",
                                             familyMemberPatron.Username),
                               PatronMessageLevels.Warning,
                               "exclamation-sign");
                return;
            }

            this.Log().Info("Correct credentials to make {0}/{1} a family member under {2}/{3}.",
                            familyMemberPatron.Username,
                            familyMemberPatron.PID,
                            sessionPatron.Username,
                            sessionPatron.PID);

            var currentPatron = Patron.GetObjectByUsername(sessionPatron.Username);

            if (!currentPatron.IsMasterAccount)
            {
                currentPatron.IsMasterAccount = true;
                this.Log().Info("Updating {0}/{1} to mark as head of family",
                                sessionPatron.Username,
                                sessionPatron.PID);
                currentPatron.Update();
                st.EstablishPatron(currentPatron);
            }

            var alreadyFamilyMembers     = Patron.GetSubAccountList(familyMemberPatron.PID);
            int alreadyFamilyMemberCount = alreadyFamilyMembers.Tables[0].Rows.Count;

            if (alreadyFamilyMemberCount > 0)
            {
                this.Log().Info("{0}/{1} already had {2} family members, moving them all to {3}/{4}",
                                familyMemberPatron.Username,
                                familyMemberPatron.PID,
                                alreadyFamilyMemberCount,
                                sessionPatron.Username,
                                sessionPatron.PID);
                foreach (DataRow row in alreadyFamilyMembers.Tables[0].Rows)
                {
                    var alreadyFamilyPatron = Patron.GetObjectByUsername(row["Username"].ToString());
                    this.Log().Info("Marking {0}/{1} as a family member of {2}/{3} and saving...",
                                    alreadyFamilyPatron.Username,
                                    alreadyFamilyPatron.PID,
                                    sessionPatron.Username,
                                    sessionPatron.PID);
                    alreadyFamilyPatron.MasterAcctPID   = currentPatron.PID;
                    alreadyFamilyPatron.IsMasterAccount = false;
                    alreadyFamilyPatron.Update();
                }
            }

            if (familyMemberPatron.IsMasterAccount)
            {
                this.Log().Info("{0}/{1} was already marked as a family head, marking as regular user",
                                familyMemberPatron.Username,
                                familyMemberPatron.PID);
                familyMemberPatron.IsMasterAccount = false;
            }

            familyMemberPatron.MasterAcctPID = sessionPatron.PID;

            this.Log().Info("Saving update to {0}/{1}...",
                            familyMemberPatron.Username,
                            familyMemberPatron.PID);
            familyMemberPatron.Update();

            if (alreadyFamilyMemberCount > 0)
            {
                st.AlertPatron(
                    string.Format("<strong>{0}</strong> and {1} other users are now members of your family!",
                                  familyMemberPatron.Username,
                                  alreadyFamilyMemberCount),
                    PatronMessageLevels.Success,
                    "thumbs-up");
            }
            else
            {
                st.AlertPatron(
                    string.Format("<strong>{0}</strong> is now a member of your family!",
                                  familyMemberPatron.Username),
                    PatronMessageLevels.Success,
                    "thumbs-up");
            }
            Response.Redirect("~/Account/FamilyAccountList.aspx");
        }
        protected void DoFilter(EventSearchCriteria criteria)
        {
            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrEmpty(criteria.StartDate))
            {
                sb.Append("Start Date: ");
                sb.Append("<strong>");
                sb.Append(criteria.StartDate);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrEmpty(criteria.EndDate))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("End date: ");
                sb.Append("<strong>");
                sb.Append(criteria.EndDate);
                sb.Append("</strong>");
            }
            if (criteria.SystemId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("System: ");
                sb.Append("<strong>");
                sb.Append(SystemId.Items.FindByValue(criteria.SystemId.ToString()).Text);
                sb.Append("</strong>");
            }
            if (criteria.BranchId > 0)
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Branch/library: ");
                sb.Append("<strong>");
                sb.Append(criteria.BranchName);
                sb.Append("</strong>");
            }
            if (!string.IsNullOrWhiteSpace(criteria.SearchText))
            {
                if (sb.Length > 0)
                {
                    sb.Append(" / ");
                }
                sb.Append("Search text: ");
                sb.Append("<strong>");
                sb.Append(criteria.SearchText);
                sb.Append("</strong>");
            }

            WhatsShowing.Text         = WhatsShowingPrint.Text = sb.ToString();
            WhatsShowingPanel.Visible = Filtered = !string.IsNullOrEmpty(WhatsShowing.Text);

            if (string.IsNullOrEmpty(WhatsShowing.Text))
            {
                // no filter criteria, use cache if possible
                var st           = new SessionTools(Session);
                var cachedEvents = st.GetCache(Cache, CacheKey.AllEvents) as System.Data.DataSet;
                if (cachedEvents != null)
                {
                    rptr.DataSource = cachedEvents;
                }
                else
                {
                    var allEvents = Event.GetUpcomingDisplay(
                        criteria.StartDate,
                        criteria.EndDate,
                        criteria.SystemId,
                        criteria.BranchId,
                        criteria.SearchText);
                    rptr.DataSource = allEvents;

                    string tenantCacheKey = st.GetTenantCacheKey(CacheKey.AllEvents);
                    Cache.Insert(tenantCacheKey,
                                 allEvents,
                                 null,
                                 DateTime.UtcNow.AddHours(2),
                                 System.Web.Caching.Cache.NoSlidingExpiration,
                                 System.Web.Caching.CacheItemPriority.Default,
                                 null);
                }
            }
            else
            {
                rptr.DataSource = Event.GetUpcomingDisplay(
                    criteria.StartDate,
                    criteria.EndDate,
                    criteria.SystemId,
                    criteria.BranchId,
                    criteria.SearchText);
            }
            rptr.DataBind();

            var wt = new WebTools();

            if (Filtered)
            {
                StartDate.CssClass  = wt.CssEnsureClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass    = wt.CssEnsureClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass   = wt.CssEnsureClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass   = wt.CssEnsureClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssEnsureClass(SearchText.CssClass, "gra-search-active");
            }
            else
            {
                StartDate.CssClass  = wt.CssRemoveClass(StartDate.CssClass, "gra-search-active");
                EndDate.CssClass    = wt.CssRemoveClass(EndDate.CssClass, "gra-search-active");
                BranchId.CssClass   = wt.CssRemoveClass(BranchId.CssClass, "gra-search-active");
                SystemId.CssClass   = wt.CssRemoveClass(SystemId.CssClass, "gra-search-active");
                SearchText.CssClass = wt.CssRemoveClass(SearchText.CssClass, "gra-search-active");
            }
        }
        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Setup/EventList.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 Event();
                    //obj.GenNotificationFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("GenNotificationFlag")).Checked;

                    obj.EventTitle   = ((TextBox)((DetailsView)sender).FindControl("EventTitle")).Text;
                    obj.EventDate    = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("EventDate")).Text);
                    obj.EventTime    = ((TextBox)((DetailsView)sender).FindControl("EventTime")).Text;
                    obj.HTML         = ((HtmlTextArea)((DetailsView)sender).FindControl("HTML")).InnerHtml;
                    obj.SecretCode   = ((TextBox)((DetailsView)sender).FindControl("SecretCode")).Text;
                    obj.NumberPoints = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumberPoints")).Text);
                    obj.BadgeID      = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BadgeID")).SelectedValue);
                    obj.BranchID     = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BranchID")).SelectedValue);
                    obj.Custom1      = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom1")).Value;
                    obj.Custom2      = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom2")).Value;
                    obj.Custom3      = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom3")).Value;

                    obj.ShortDescription = ((TextBox)((DetailsView)sender).FindControl("ShortDescription")).Text;
                    obj.EndDate          = ((TextBox)((DetailsView)sender).FindControl("EndDate")).Text.SafeToDateTime();
                    obj.EndTime          = ((TextBox)((DetailsView)sender).FindControl("EndTime")).Text;

                    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();
                        new SessionTools(Session).RemoveCache(Cache, CacheKey.EventsActive);
                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text = obj.EID.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 Event();
                    int pk  = int.Parse(lblPK.Text);//int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text));
                    obj.Fetch(pk);

                    obj.EventTitle = ((TextBox)((DetailsView)sender).FindControl("EventTitle")).Text.Trim();
                    obj.EventDate  = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("EventDate")).Text);
                    //obj.EventTime = ((TextBox)((DetailsView)sender).FindControl("EventTime")).Text;
                    obj.HTML         = ((HtmlTextArea)((DetailsView)sender).FindControl("HTML")).InnerHtml.Trim();
                    obj.SecretCode   = ((TextBox)((DetailsView)sender).FindControl("SecretCode")).Text.Trim().ToLower();
                    obj.NumberPoints = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumberPoints")).Text);
                    obj.BadgeID      = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BadgeID")).SelectedValue);
                    obj.BranchID     = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BranchID")).SelectedValue);

                    obj.Custom1 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom1")).Value;
                    obj.Custom2 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom2")).Value;
                    obj.Custom3 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom3")).Value;
                    //obj.Custom2 = ((TextBox)((DetailsView)sender).FindControl("Custom2")).Text;
                    //obj.Custom3 = ((TextBox)((DetailsView)sender).FindControl("Custom3")).Text;


                    //obj.ShortDescription = ((TextBox)((DetailsView)sender).FindControl("ShortDescription")).Text;
                    //obj.EndDate = ((TextBox)((DetailsView)sender).FindControl("EndDate")).Text.SafeToDateTime();
                    //obj.EndTime = ((TextBox)((DetailsView)sender).FindControl("EndTime")).Text;

                    obj.ExternalLinkToEvent = ((TextBox)((DetailsView)sender).FindControl("ExternalLinkToEvent")).Text.Trim();
                    obj.HiddenFromPublic    = ((DropDownList)((DetailsView)sender).FindControl("HiddenFromPublic")).SelectedIndex > 0;

                    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 st = new SessionTools(Session);
                        st.RemoveCache(Cache, CacheKey.EventsActive);
                        st.RemoveCache(Cache, CacheKey.AllEvents);
                        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);
                }
            }
        }
        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);

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

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

                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;
                        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 #24
0
        private void MapClick(object sender, MouseEventArgs e)
        {
            var mouseScreenCoordinates = OutlandAreaCommon.Tools.ToRelativeCoordinates(e.Location, _screenParameters.Center);

            var mouseMapCoordinates = OutlandAreaCommon.Tools.ToTacticalMapCoordinates(mouseScreenCoordinates, _screenParameters.CenterScreenOnMap);

            var celestialObjectInRange = SessionTools.GetObjectInRange(_gameSession, 15, new PointF(mouseMapCoordinates.X, mouseMapCoordinates.Y));


            switch (_activeModule)
            {
            case CelestialObjectTypes.PointInMap:
                break;

            case CelestialObjectTypes.Missile:
                if (e.Button == MouseButtons.Right)
                {
                    _activeModule = CelestialObjectTypes.None;
                    return;
                }

                if (e.Button == MouseButtons.Left)
                {
                    _activeCelestialObject.PositionX = mouseMapCoordinates.X;
                    _activeCelestialObject.PositionY = mouseMapCoordinates.Y;

                    _activeModule = CelestialObjectTypes.None;

                    OnLaunchMissile?.Invoke(_activeCelestialObject);
                    return;
                }

                break;

            case CelestialObjectTypes.SpaceshipPlayer:
                break;

            case CelestialObjectTypes.SpaceshipNpcNeutral:
                break;

            case CelestialObjectTypes.SpaceshipNpcEnemy:
                break;

            case CelestialObjectTypes.SpaceshipNpcFriend:
                break;

            case CelestialObjectTypes.Asteroid:
                break;

            case CelestialObjectTypes.None:
                _connectorsShow = new List <ICelestialObject>();
                break;
            }



            Logger.Info(TraceMessage.Execute(this, $"MapClick"));

            //if (e.Button == MouseButtons.Right)
            //{
            //    AlignToCommand(null, e);
            //    return;
            //}


            if (celestialObjectInRange != null)
            {
                Global.Game.SelectCelestialObject(celestialObjectInRange);
            }
            else
            {
                // Movement by mouse click
                //Global.Game.SelectPointInSpace(mouseMapCoordinates);
            }

            //pointInSpace = mouseMapCoordinates;
        }
        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);

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

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

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

        }
        protected void btnContinue2_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            var eventObj = LoadEventObject();

            if (!eventObj.IsValid(BusinessRulesValidationMode.INSERT))
            {
                var    masterPage = (IControlRoomMaster)Master;
                string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                foreach (BusinessRulesValidationMessage m in eventObj.ErrorCodes)
                {
                    message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                }
                message = string.Format("{0}</ul>", message);
                masterPage.PageError = message;
            }
            else
            {
                if (rblBadge.SelectedIndex == 0)
                {
                    // No Badge Awarded

                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    Session["EID"] = eventObj.EID;
                    Response.Redirect("EventAddEdit.aspx?M=K");
                }
                if (rblBadge.SelectedIndex == 1)
                {
                    // Existing Badge Awarded
                    eventObj.BadgeID = int.Parse(BadgeID.SelectedValue);
                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    Session["EID"] = eventObj.EID;
                    Response.Redirect("EventAddEdit.aspx?M=K");
                }
                if (rblBadge.SelectedIndex == 2)
                {
                    // Start creation of new badge
                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    lblPK.Text = eventObj.EID.ToString();

                    pnlBadgeMore.Visible = true;
                    pnlReward.Visible    = false;

                    foreach (GridViewRow row in gvBranch.Rows)
                    {
                        Label idLabel = row.FindControl("CID") as Label;
                        if (idLabel != null && idLabel.Text == BranchId.SelectedValue)
                        {
                            var check = row.FindControl("isMember") as CheckBox;
                            if (check != null)
                            {
                                check.Checked = true;
                            }
                        }
                    }

                    btnContinue3_Click(sender, e);
                }
                new SessionTools(Session).RemoveCache(Cache, CacheKey.EventsActive);
            }
        }
        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Setup/EventList.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 Event();
                    //obj.GenNotificationFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("GenNotificationFlag")).Checked;

                    obj.EventTitle = ((TextBox)((DetailsView)sender).FindControl("EventTitle")).Text;
                    obj.EventDate = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("EventDate")).Text);
                    obj.EventTime = ((TextBox)((DetailsView)sender).FindControl("EventTime")).Text;
                    obj.HTML = ((HtmlTextArea)((DetailsView)sender).FindControl("HTML")).InnerHtml;
                    obj.SecretCode = ((TextBox)((DetailsView)sender).FindControl("SecretCode")).Text;
                    obj.NumberPoints =  FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumberPoints")).Text);
                    obj.BadgeID = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BadgeID")).SelectedValue);
                    obj.BranchID = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BranchID")).SelectedValue);
                    obj.Custom1 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom1")).Value;
                    obj.Custom2 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom2")).Value;
                    obj.Custom3 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom3")).Value;

                    obj.ShortDescription = ((TextBox)((DetailsView)sender).FindControl("ShortDescription")).Text;
                    obj.EndDate = ((TextBox)((DetailsView)sender).FindControl("EndDate")).Text.SafeToDateTime();
                    obj.EndTime = ((TextBox)((DetailsView)sender).FindControl("EndTime")).Text;
                    
                    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();
                        new SessionTools(Session).RemoveCache(Cache, CacheKey.EventsActive);
                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text = obj.EID.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 Event();
                    int pk = int.Parse(lblPK.Text);//int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text));
                    obj.Fetch(pk);

                    obj.EventTitle = ((TextBox)((DetailsView)sender).FindControl("EventTitle")).Text.Trim();
                    obj.EventDate = FormatHelper.SafeToDateTime(((TextBox)((DetailsView)sender).FindControl("EventDate")).Text);
                    //obj.EventTime = ((TextBox)((DetailsView)sender).FindControl("EventTime")).Text;
                    obj.HTML = ((HtmlTextArea)((DetailsView)sender).FindControl("HTML")).InnerHtml.Trim();
                    obj.SecretCode = ((TextBox)((DetailsView)sender).FindControl("SecretCode")).Text.Trim().ToLower();
                    obj.NumberPoints = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("NumberPoints")).Text);
                    obj.BadgeID = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BadgeID")).SelectedValue);
                    obj.BranchID = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("BranchID")).SelectedValue);

                    obj.Custom1 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom1")).Value;
                    obj.Custom2 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom2")).Value;
                    obj.Custom3 = ((EvtCustFldCtl)((DetailsView)sender).FindControl("Custom3")).Value;
                    //obj.Custom2 = ((TextBox)((DetailsView)sender).FindControl("Custom2")).Text;
                    //obj.Custom3 = ((TextBox)((DetailsView)sender).FindControl("Custom3")).Text;


                    //obj.ShortDescription = ((TextBox)((DetailsView)sender).FindControl("ShortDescription")).Text;
                    //obj.EndDate = ((TextBox)((DetailsView)sender).FindControl("EndDate")).Text.SafeToDateTime();
                    //obj.EndTime = ((TextBox)((DetailsView)sender).FindControl("EndTime")).Text;

                    obj.ExternalLinkToEvent = ((TextBox)((DetailsView)sender).FindControl("ExternalLinkToEvent")).Text.Trim();
                    obj.HiddenFromPublic = ((DropDownList)((DetailsView)sender).FindControl("HiddenFromPublic")).SelectedIndex > 0;

                    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 st = new SessionTools(Session);
                        st.RemoveCache(Cache, CacheKey.EventsActive);
                        st.RemoveCache(Cache, CacheKey.AllEvents);
                        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);
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            var tenant = context.Session["TenantID"];
            int tenantId = tenant as int? ?? -1;
            if (tenantId == -1)
            {
                tenantId = Core.Utilities.Tenant.GetMasterID();
            }

            var sessionTool = new SessionTools(context.Session);
            var cachedStatus = sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) as JsonStatus;

            try
            {
                if (cachedStatus != null)
                {
                    context.Response.ContentType = "application/json";
                    context.Response.Write(JsonConvert.SerializeObject(cachedStatus));
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Log().Error("Error looking up status data in cache: {0}", ex.Message);
            }

            var jsonResponse = new JsonStatus();
            try
            {
                TenantStatusReport result = null;
                result = new TenantStatus(tenantId).CurrentStatus();

                jsonResponse.PointsEarned = result.PointsEarned;
                jsonResponse.BadgesAwarded = result.BadgesAwarded;
                jsonResponse.ChallengesCompleted = result.ChallengesCompleted;
                jsonResponse.Since = "All Participants";
                jsonResponse.Success = true;
            }
            catch (Exception ex)
            {
                this.Log().Error("Status update error: {0}", ex.Message);
                jsonResponse.Success = false;
            }

            if (jsonResponse.Success)
            {
                try
                {
                    DateTime cacheUntil = DateTime.UtcNow.AddSeconds(30);
                    if (sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) == null)
                    {
                        //this.Log().Debug("Caching status data until {0}",
                        //                 cacheUntil.ToLocalTime().ToLongTimeString());
                        string tenantCacheKey = sessionTool.GetTenantCacheKey(CacheKey.Status, tenantId);
                        context.Cache.Insert(tenantCacheKey,
                                             jsonResponse,
                                             null,
                                             cacheUntil,
                                             System.Web.Caching.Cache.NoSlidingExpiration,
                                             System.Web.Caching.CacheItemPriority.Default,
                                             null);
                    }
                }
                catch (Exception ex)
                {
                    this.Log().Error("Error caching status response: {0}", ex.Message);
                }
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(jsonResponse));
        }
        public void ProcessRequest(HttpContext context)
        {
            var tenant = context.Session["TenantID"];
            int tenantId = tenant as int? ?? -1;
            if (tenantId == -1)
            {
                tenantId = Core.Utilities.Tenant.GetMasterID();
            }

            var sessionTool = new SessionTools(context.Session);
            var cachedFeed = sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) as JsonFeed;

            try
            {
                if (cachedFeed != null)
                {
                    context.Response.ContentType = "application/json";
                    context.Response.Write(JsonConvert.SerializeObject(cachedFeed));
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Log().Error("Error looking up feed data in cache: {0}", ex.Message);
            }

            var jsonResponse = new JsonFeed();
            var entries = new List<JsonFeedEntry>();

            int after = 0;
            int.TryParse(context.Request.QueryString["after"], out after);

            try
            {
                var feed = new ActivityFeed().Latest(after, tenantId);
                foreach (DataRow dataRow in feed.Rows)
                {
                    var entry = new JsonFeedEntry
                    {
                        ID = (int)dataRow["PPID"],
                        PatronId = (int)dataRow["PID"],
                        Username = (string)dataRow["Username"],
                        AwardedAt = ((DateTime)dataRow["AwardDate"]).ToString(),
                        AwardReasonId = (int)dataRow["AwardReasonCd"],
                        BadgeId = (int)dataRow["BadgeId"],
                        ChallengeId = dataRow["BLID"] == DBNull.Value ? 0 : (int)dataRow["BLID"],
                        ChallengeProgramId = dataRow["BLProgID"] == DBNull.Value ? 0 : (int)dataRow["BLProgID"],
                        AvatarState = dataRow["AvatarState"] == DBNull.Value ? string.Empty : (string)dataRow["AvatarState"]
                    };

                    if (entry.ID > jsonResponse.Latest)
                    {
                        jsonResponse.Latest = entry.ID;
                    }

                    switch (entry.AwardReasonId)
                    {
                        case 1:
                            // got badge
                            entry.AchievementName = (string)dataRow["BadgeName"];
                            break;
                        case 2:
                            // completed challenge
                            entry.AchievementName = (string)dataRow["ListName"];
                            break;
                        case 4:
                            entry.AchievementName = (string)dataRow["GameName"];
                            break;
                    }
                    entries.Add(entry);
                }

                jsonResponse.Entries = entries.ToArray();
                jsonResponse.Success = true;
            }
            catch (Exception ex)
            {
                this.Log().Error("Error loading feed: {0}", ex.Message);
                jsonResponse.Success = false;
            }

            if (jsonResponse.Success)
            {
                try
                {
                    DateTime cacheUntil = DateTime.UtcNow.AddSeconds(30);
                    if (sessionTool.GetCache(context.Cache, CacheKey.Feed, tenantId) == null)
                    {
                        //this.Log().Debug("Caching feed data until {0}",
                        //                 cacheUntil.ToLocalTime().ToLongTimeString());
                        string tenantCacheKey = sessionTool.GetTenantCacheKey(CacheKey.Feed, tenantId);
                        context.Cache.Insert(tenantCacheKey,
                                             jsonResponse,
                                             null,
                                             cacheUntil,
                                             System.Web.Caching.Cache.NoSlidingExpiration,
                                             System.Web.Caching.CacheItemPriority.Default,
                                             null);
                    }
                }
                catch (Exception ex)
                {
                    this.Log().Error("Error caching feed response: {0}", ex.Message);
                }
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(jsonResponse));
        }
Example #30
0
        public void ProcessRequest(HttpContext context)
        {
            var tenant   = context.Session["TenantID"];
            int tenantId = tenant as int? ?? -1;

            if (tenantId == -1)
            {
                tenantId = Core.Utilities.Tenant.GetMasterID();
            }

            var sessionTool  = new SessionTools(context.Session);
            var cachedStatus = sessionTool.GetCache(context.Cache, CacheKey.Status, tenantId) as JsonStatus;

            try
            {
                if (cachedStatus != null)
                {
                    context.Response.ContentType = "application/json";
                    context.Response.Write(JsonConvert.SerializeObject(cachedStatus));
                    return;
                }
            }
            catch (Exception ex)
            {
                this.Log().Error("Error looking up status data in cache: {0}", ex.Message);
            }

            var jsonResponse = new JsonStatus();

            try
            {
                var result = new TenantStatus(tenantId).CurrentStatus();
                jsonResponse.RegisteredPatrons    = result.RegisteredPatrons;
                jsonResponse.PointsEarned         = result.PointsEarned;
                jsonResponse.PointsEarnedReading  = result.PointsEarnedReading;
                jsonResponse.ChallengesCompleted  = result.ChallengesCompleted;
                jsonResponse.SecretCodesRedeemed  = result.SecretCodesRedeemed;
                jsonResponse.AdventuresCompleted  = result.AdventuresCompleted;
                jsonResponse.BadgesAwarded        = result.BadgesAwarded;
                jsonResponse.RedeemedProgramCodes = result.RedeemedProgramCodes;
                jsonResponse.Since   = "All Participants";
                jsonResponse.Success = true;
            }
            catch (Exception ex)
            {
                this.Log().Error("Status update error: {0}", ex.Message);
                jsonResponse.Success = false;
            }

            if (jsonResponse.Success)
            {
                try
                {
                    DateTime cacheUntil = DateTime.UtcNow.AddSeconds(30);
                    if (sessionTool.GetCache(context.Cache, CacheKey.Status, tenantId) == null)
                    {
                        //this.Log().Debug("Caching status data until {0}",
                        //                 cacheUntil.ToLocalTime().ToLongTimeString());
                        string tenantCacheKey = sessionTool.GetTenantCacheKey(CacheKey.Status, tenantId);
                        context.Cache.Insert(tenantCacheKey,
                                             jsonResponse,
                                             null,
                                             cacheUntil,
                                             System.Web.Caching.Cache.NoSlidingExpiration,
                                             System.Web.Caching.CacheItemPriority.Default,
                                             null);
                    }
                }
                catch (Exception ex)
                {
                    this.Log().Error("Error caching status response: {0}", ex.Message);
                }
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(jsonResponse));
        }
        protected void btnContinue2_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            var eventObj = LoadEventObject();

            if (!eventObj.IsValid(BusinessRulesValidationMode.INSERT))
            {
                var masterPage = (IControlRoomMaster)Master;
                string message = String.Format(SRPResources.ApplicationError1, "<ul>");
                foreach (BusinessRulesValidationMessage m in eventObj.ErrorCodes)
                {
                    message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                }
                message = string.Format("{0}</ul>", message);
                masterPage.PageError = message;
            }
            else
            {
                if (rblBadge.SelectedIndex == 0)
                {
                    // No Badge Awarded

                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    Session["EID"] = eventObj.EID;
                    Response.Redirect("EventAddEdit.aspx?M=K");
                }
                if (rblBadge.SelectedIndex == 1)
                {
                    // Existing Badge Awarded
                    eventObj.BadgeID = int.Parse(BadgeID.SelectedValue);
                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    Session["EID"] = eventObj.EID;
                    Response.Redirect("EventAddEdit.aspx?M=K");
                }
                if (rblBadge.SelectedIndex == 2)
                {
                    // Start creation of new badge
                    eventObj.Insert();
                    var st = new SessionTools(Session);
                    st.RemoveCache(Cache, CacheKey.EventsActive);
                    st.RemoveCache(Cache, CacheKey.AllEvents);
                    lblPK.Text = eventObj.EID.ToString();

                    pnlBadgeMore.Visible = true;
                    pnlReward.Visible = false;

                    foreach (GridViewRow row in gvBranch.Rows)
                    {
                        Label idLabel = row.FindControl("CID") as Label;
                        if (idLabel != null && idLabel.Text == BranchId.SelectedValue)
                        {
                            var check = row.FindControl("isMember") as CheckBox;
                            if (check != null)
                            {
                                check.Checked = true;
                            }
                        }
                    }

                    btnContinue3_Click(sender, e);
                }
                new SessionTools(Session).RemoveCache(Cache, CacheKey.EventsActive);
            }

        }