/// <summary>
        /// Saves the value of a survey checkbox control. Should only be called when the control is visible.
        /// </summary>
        /// <param name="control"></param>
        public static void SaveValue(SurveyCheckBox control)
        {
            //Get value from postback
            bool postValue = (!String.IsNullOrEmpty(RequestVars.Post <string>(control.UniqueID, null)));

            control.Checked = postValue;
            SessionWrapper.Add(control.SessionKey, new SurveySessionControl <bool>(postValue));
            //if ( control.Checked ) {
            //    if ( !SessionWrapper.Get( control.SessionKey, new SurveySessionControl<bool>( false ) ).Value || postValue ) {
            //        //If it wasn't checked already or it's the same one as before, check it.
            //        SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( true ) );
            //        control.Checked = true;
            //    } else {
            //        //Uncheck other radio buttons that may have been flagged as checked if we know that we've already found a checked one.
            //        SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( false ) );
            //        control.Checked = false;
            //    }
            //} else {
            //    SessionWrapper.Add( control.SessionKey, new SurveySessionControl<bool>( false ) );
            //    control.Checked = false;
            //}
            //SurveyRadioButton rad = control as SurveyRadioButton;
            //if ( rad != null ) {

            //    return;
            //}
            //SaveValue<bool>( control );
        }
Esempio n. 2
0
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            string currentSort    = RequestVars.Get("s", "F");;           //Feedback status
            string currentSortDir = RequestVars.Get("d", "D");;           //Desc

            SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;

            sql.CommandTimeout = 120;
            SQLParamList sqlParams = Master.GetFilters()
                                     .Add("@Sort", currentSort)
                                     .Add("@SortDir", currentSortDir);

            if (CurrentPage == -1)
            {
                sqlParams.Add("@ShowAllRows", true);
            }
            else
            {
                sqlParams.Add("@Page", CurrentPage)
                .Add("@RowsPerPage", ROWS_PER_PAGE);
            }
            if (txtRecordIDSearch.Text.Length > 0)
            {
                sqlParams.Add("RecordID", txtRecordIDSearch.Text);
            }
            DataTable dt = sql.ExecStoredProcedureDataTable("[spFeedback_GetList]", sqlParams);

            if (!sql.HasError)
            {
                Data = dt;
            }
        }
Esempio n. 3
0
        public void LogInUser(string usernameOrEmail, string password, bool useEmailForLogin, int clientID, out int outputValue)
        {
            outputValue = -1;
            //Set up the sql request
            SQLDatabaseReporting sql       = new SQLDatabaseReporting();
            SQLParamList         sqlParams = new SQLParamList();

            sqlParams.Add(useEmailForLogin ? "@Email" : "@Username", usernameOrEmail);

            SqlParameter outParam;

            sqlParams.Add("@Password", password)
            .Add("@ClientID", clientID)
            .Add("@IP", RequestVars.GetRequestIPv4Address())
            .AddOutputParam("@OutputValue", 4, out outParam);

            //Try and get the user's info
            DataTable dt = sql.ExecStoredProcedureDataTable("spCOM_WebReportingLogon", sqlParams);

            if (!sql.HasError)
            {
                outputValue = Conversion.StringToInt(outParam.Value.ToString(), -1);
                if (outputValue == 0 && dt.Rows.Count > 0)
                {
                    //Success!
                    SetUserDataFromDr(dt.Rows[0]);
                    //SessionWrapper.Add<UserInfoModel>("AccountDetail", this);
                    return;
                }
            }
            UserID = -1;
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(GUID))
            {
                SQLDatabase  sql       = new SQLDatabase();    sql.CommandTimeout = 120;
                SQLParamList sqlParams = new SQLParamList();
                UserInfo     ui        = SessionWrapper.Get <UserInfo>("UserInfo");
                sqlParams.Add("@GUID", GUID)
                .Add("@UpdateLastViewedTime", !(ui != null || RequestVars.Get <string>("a", null) != null));
                DataSet ds = sql.ExecStoredProcedureDataSet("[spFeedback_GetGuestItem]", sqlParams);
                if (!sql.HasError)
                {
                    Data = ds;

                    GCCPropertyShortCode sc = (GCCPropertyShortCode)Conversion.StringToInt(ds.Tables[0].Rows[0]["PropertyID"].ToString(), 1);

                    Master.ForceSpecificProperty      = sc;
                    MessageTimeline.PropertyShortCode = sc;

                    MessageTimeline.Messages = ds.Tables[1];
                    int feedbackStatus = Conversion.StringToInt(ds.Tables[0].Rows[0]["FeedbackStatusID"].ToString());
                    MessageTimeline.HideReplyBox = ui != null || RequestVars.Get <string>("a", null) != null;

                    Title = PropertyTools.GetCasinoName((int)sc) + " Feedback";
                }
            }
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            string currentSort    = RequestVars.Get("s", "D");; //Date
            string currentSortDir = RequestVars.Get("d", "D");; //Desc

            SQLDatabase  sql       = new SQLDatabase();    sql.CommandTimeout = 120;
            SQLParamList sqlParams = Master.GetFilters()
                                     .Add("@Sort", currentSort)
                                     .Add("@SortDir", currentSortDir);

            if (CurrentPage == -1)
            {
                sqlParams.Add("@ShowAllRows", true);
            }
            else
            {
                sqlParams.Add("@Page", CurrentPage)
                .Add("@RowsPerPage", ROWS_PER_PAGE);
            }
            DataTable dt = sql.ExecStoredProcedureDataTable("spReports_Survey_List", sqlParams);

            if (!sql.HasError)
            {
                Data = dt;
            }
        }
Esempio n. 6
0
        protected string GetPaginationURL(int pageNumber)
        {
            string currentSort = RequestVars.Get("s", "F");           //Feedback status
            string sortDir     = RequestVars.Get("d", "D");;          //Desc

            return(String.Format("/Admin/Feedback/List/{0}?s={1}&d={2}", pageNumber, currentSort, sortDir));
        }
Esempio n. 7
0
        protected string GetSort(string sortCol, string label)
        {
            string currentSort = RequestVars.Get("s", "F");           //Feedback status
            string sortDir     = RequestVars.Get("d", "D");;          //Desc

            sortDir = sortDir.Equals("A") && currentSort.Equals(sortCol) ? "D" : "A";

            return(String.Format("<a href=\"/Admin/Feedback/List/{0}?s={1}&d={2}\">{3}</a>", CurrentPage, sortCol, sortDir, label));
        }
Esempio n. 8
0
        /// <summary>
        ///     Checks if page has redirect url
        /// </summary>
        public void CheckRedirect()
        {
            LoginRedirect = "/Director.ashx";
            string redir = RequestVars.Get("rd", String.Empty);

            if (!String.IsNullOrEmpty(redir))
            {
                LoginRedirect += "?rd=" + Server.UrlPathEncode(redir);
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            string filename = RequestVars.Get("f", String.Empty);

            if (!String.IsNullOrWhiteSpace(filename))
            {
                Response.Clear();
                Response.ContentType = "message/rfc822";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.WriteFile(Path.Combine(PickupDirectory, filename));
                Response.End();
                return;
            }
        }
Esempio n. 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int loginUserID = RequestVars.Get <int>("luid", -1);

            if (loginUserID >= 0)
            {
                LoginResponse = TryLogUserIn(loginUserID);
                switch (LoginResponse)
                {
                case LoginErrorCode.Success:
                    Response.Redirect("/Director.ashx");
                    break;

                case LoginErrorCode.PasswordExpired:
                    Response.Redirect("/Director.ashx");                               //This will redirect to password change
                    break;

                default:
                    TopMessage.ErrorMessage = LoginResponse.ToString();
                    break;
                }
            }

            Title = "GCC Users";
            Master.HideAllFilters = true;
            SQLDatabase  sql       = new SQLDatabase();    sql.CommandTimeout = 120;
            SQLParamList sqlParams = new SQLParamList();

            if (CurrentPage == -1)
            {
                sqlParams.Add("@ShowAllRows", true);
            }
            else
            {
                sqlParams.Add("@Page", CurrentPage)
                .Add("@RowsPerPage", ROWS_PER_PAGE);
            }
            if (!String.IsNullOrEmpty(txtNameSearch.Text.Trim()))
            {
                sqlParams.Add("@TextSearch", txtNameSearch.Text.Trim());
            }
            DataTable dt = sql.ExecStoredProcedureDataTable("spAdmin_User_List", sqlParams);

            if (!sql.HasError)
            {
                Data = dt;
            }
        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            //Check for a reset and abandon the session and redirect to page 1.
            if (RequestVars.Get("r", 0) == 1)
            {
                Session.Abandon();
                Response.Redirect(GetURL(1, 1), true);
                return;
            }

            //spbProgress.MaxValue = 22;
            //spbProgress.CurrentValue = CurrentPage;
            //spbProgress.Visible = (CurrentPage != 1 //First page
            //                        && CurrentPage != 99 //Quit early page
            //                        && (CurrentPage != 97 || !String.IsNullOrWhiteSpace(mmLastPage.SuccessMessage))); //Only show 100% on final page
        }
Esempio n. 12
0
        /// <summary>
        ///     Checks for valid login credentials. Returns 0 if successful, 1 if the username or password is empty, 2 if there was a SQL error, 3 if the user is locked out or 4 if the username or password is invalid.
        /// </summary>
        private static LoginErrorCode TryLogUserIn()
        {
            string username = RequestVars.Post("inputUsername", String.Empty).Trim(),
                   password = RequestVars.Post("inputPassword", String.Empty).Trim();

            int outputVal;

            UserInfo ui = UserInformation.LogUserIn <UserInfo>(
                username,
                password,
                true, //email logins allowed
                Config.ClientID, out outputVal);

            LoginErrorCode loginCode = (LoginErrorCode)outputVal;

            return(loginCode);
        }
        protected void LoadData()
        {
            SQLDatabase  sql       = new SQLDatabase();    sql.CommandTimeout = 120;
            SQLParamList sqlParams = Master.GetFilters();

            sqlParams.Add("@IsCompetitor", RequestVars.Get <int>("competitor", 0));
            sqlParams.Add("@IsPositive", RequestVars.Get <int>("positive", 0));
            sqlParams.Add("@IsNegative", RequestVars.Get <int>("negative", 0));
            string keyword = RequestVars.Get <string>("keyword", "");

            if (keyword != "")
            {
                sqlParams.Add("@SpecificKeyword", keyword);
            }
            Data = sql.ExecStoredProcedureDataSet("spGetSocialMediaData", sqlParams);
            if (Data.Tables.Count > 0)
            {
                Master.RecordCount = Data.Tables[0].Rows.Count.ToString();
            }
        }
Esempio n. 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckRedirect();

            SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;

            if (sql.HasError == true)
            {
                string a;
            }

            if (Request.RequestType == "GET")
            {
                //Check for logouts
                if (RequestVars.Get("lo", 0) == 1)
                {
                    Session.Abandon();
                    LoggedOutOnLoad = true;
                }
            }

            if (Request.RequestType == "POST")
            {
                LoginResponse = TryLogUserIn();
                switch (LoginResponse)
                {
                case LoginErrorCode.Success:
                    Response.Redirect(LoginRedirect);
                    break;

                case LoginErrorCode.PasswordExpired:
                    Response.Redirect("/Director.ashx");     //This will redirect to password change
                    break;

                default:
                    SetErrorSuccessMessage(LoginResponse);
                    break;
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            UserInfo ui = SessionWrapper.Get <UserInfo>("UserInfo", null);

            if (ui != null)
            {
                string redir       = RequestVars.Get("rd", String.Empty);
                string redirSuffix = String.Empty;
                if (!String.IsNullOrEmpty(redir))
                {
                    redirSuffix = "?rd=" + HttpContext.Current.Server.UrlEncode(redir);
                }

                if (ui.PasswordExpireDate <= DateTime.Now)
                {
                    //Password update required
                    context.Response.Redirect("/PasswordChange" + redirSuffix, true);
                }
                else
                {
                    //Carry on
                    if (!String.IsNullOrEmpty(redir))
                    {
                        context.Response.Redirect(redir);
                    }
                    else
                    {
                        context.Response.Redirect("/");
                    }
                }
            }
            else
            {
                //Not logged in
                context.Response.Redirect("/Login", true);
            }
        }
        protected UserInfo UserData;            //The current user's information.

        protected void Page_Load(object sender, EventArgs e)
        {
            form.Action = Request.Url.PathAndQuery;
            bool isGuidReset = false;

            //Load user variable
            if (RequestVars.Get <string>("id", null) != null)
            {
                UserData        = UserInformation.GetUser <UserInfo>(RequestVars.Get <string>("id", null));
                ShowOldPassword = false;
                isGuidReset     = true;
            }
            else
            {
                UserData = SessionWrapper.Get <UserInfo>("UserInfo");
            }
            //If no user was loaded, output error message
            if (UserData == null)
            {
                mmMessages.ErrorMessage = "We're sorry. We couldn't find the user associated with this account or the link is invalid. Please try again.";
                HideForm = true;
                return;
            }

            //Check if the GUID reset time has expired
            if (isGuidReset && !IsResetPasswordTimeValid(UserData.PasswordResetDate))
            {
                Response.Redirect("/ResetPassword?guidexpired=1");
                return;
            }

            if (Request.RequestType.Equals("POST"))
            {
                ResetPassword(isGuidReset);
            }
        }
        //
        private void ZeroPrivateVars()
        {
            // Set default values for private members here
            m_RequestVars = new RequestVars();

            m_HttpPolicy        = null;
            m_StatusCode        = (HttpStatusCode)0;
            m_StatusDescription = null;
            m_HttpVersion       = null;
            m_Headers           = null;
            m_SystemMeta        = null;
            m_DontUpdateHeaders = false;
            m_HeuristicExpiration = false;

            m_CacheVars   = new Vars();
            m_CacheVars.Initialize();

            m_ResponseVars= new Vars();
            m_ResponseVars.Initialize();
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            fltDateRange.User = User;
            Filters           = new IReportFilter[] {
                fltDateRange,
                fltRegion,
                fltProperty,
                fltSurveyType,
                fltBusinessUnit,
                fltSource,
                fltStatus,
                fltFeedbackAge,
                fltFeedbackTier,
                fltFBVenue,
                fltEncoreNumber,
                fltPlayerEmail,
                fltAgeRange,
                fltGender,
                fltLanguage,
                fltVisits,
                fltSegments,
                fltTenure,
                fltTier,
                fltTextSearch
            };

            if (IsPropertyUser)
            {
                fltProperty.OnClear = fltProperty_OnClear;
                fltProperty.SelectedIndexChanged += fltProperty_SelectedIndexChanged;
                fltProperty.SelectedValue         = ((int)User.Property).ToString();
            }


            //if (IsMultiPropertyUser)
            //{
            //    List<GCCProperty> myprop = new List<GCCProperty>();
            //    myprop.Add(GCCProperty.CasinoNewBrunswick);
            //    fltProperty.Items.Clear();
            //    fltProperty.DataSource = myprop;

            //    fltProperty.DataBind();

            //    ////fltProperty.OnClear = fltProperty_OnClear;
            //    //List<PropData> data = new List<PropData>();
            //    //data.Add(new PropData() { Value = 2, Text = "River Rock Casino Resort" });
            //    //data.Add(new PropData() { Value = 3, Text = "Hard Rock Casino Vancouver" });

            //    //fltProperty.DataSource = data;
            //    //fltProperty.DataMember = "Text";
            //    //fltProperty.DataBind();


            //    //fltProperty.SelectedIndexChanged += fltProperty_SelectedIndexChanged;
            //    //fltProperty.SelectedValue = ((int)User.Property).ToString();
            //}
            //Set filters from query string
            int sf = RequestVars.Get("sf", 0);

            if (sf == 1)
            {
                foreach (IReportFilter flt in Filters)
                {
                    string getVal = RequestVars.Get <string>(flt.SessionKey, null);
                    if (!String.IsNullOrWhiteSpace(getVal))
                    {
                        ReportFilterListBox rflb = flt as ReportFilterListBox;
                        if (rflb != null)
                        {
                            string[] vals = getVal.Split(',');
                            foreach (ListItem li in rflb.Items)
                            {
                                if (vals.Contains(li.Value))
                                {
                                    li.Selected = true;
                                }
                            }
                            flt.Save();
                            continue;
                        }
                        ReportFilterTextBox rftb = flt as ReportFilterTextBox;
                        if (rftb != null)
                        {
                            rftb.Text = getVal;
                            flt.Save();
                            continue;
                        }
                        DateRangeFilterControl drfc = flt as DateRangeFilterControl;
                        if (drfc != null)
                        {
                            string[] vals = getVal.Split(',');
                            if (vals.Length == 2)
                            {
                                drfc.SetValues(vals[0], vals[1]);
                                flt.Save();
                                continue;
                            }
                        }
                        ReportFilterDropDownList rfddl = flt as ReportFilterDropDownList;
                        if (rfddl != null)
                        {
                            rfddl.SelectedValue = getVal;
                            flt.Save();
                            continue;
                        }
                    }
                }
                //Remove the query string and refresh
                Response.Redirect(Request.Path);
            }

            string rm = RequestVars.Get("rm", String.Empty);

            if (!String.IsNullOrEmpty(rm))
            {
                foreach (IReportFilter flt in Filters)
                {
                    if (flt.ID.Equals(rm))
                    {
                        flt.Clear();
                        break;
                    }
                }
                Response.Redirect(Request.Path);
            }



            // Jan 2017 Date range was default from 2016-12-01 to Jan 2017 but data was too much to load so resetting it to Jan 01,2017 to current date
            //if (DateTime.Today.Month == 1)
            //{
            //    fltDateRange.DefaultBeginDate = DateTime.Now.AddDays(-DateTime.Now.AddMonths(-1).Day + 1).Date;
            //}
            //else
            //{

            // connection timeout set to = 120 in Feddbacklist Page load complete
            //fltDateRange.DefaultBeginDate = DateTime.Now.AddMonths(-1).AddDays(-DateTime.Now.AddMonths(-1).Day + 1).Date;
            // }



            fltDateRange.DefaultBeginDate = DateTime.Now.AddMonths(-1).AddDays(-DateTime.Now.AddMonths(-1).Day + 1).Date;



            // For Archived Portal setting up from Jan to Dec 2016
            //fltDateRange.DefaultBeginDate = new DateTime(2016, 01, 01, 00, 00, 01); ;

            fltDateRange.DefaultEndDate = DateTime.Now;
        }
 private void ZeroPrivateVars()
 {
     this.m_RequestVars = new RequestVars();
     this.m_HttpPolicy = null;
     this.m_StatusCode = (HttpStatusCode) 0;
     this.m_StatusDescription = null;
     this.m_HttpVersion = null;
     this.m_Headers = null;
     this.m_SystemMeta = null;
     this.m_DontUpdateHeaders = false;
     this.m_HeuristicExpiration = false;
     this.m_CacheVars = new Vars();
     this.m_CacheVars.Initialize();
     this.m_ResponseVars = new Vars();
     this.m_ResponseVars.Initialize();
 }
Esempio n. 20
0
        public void ProcessRequest(HttpContext context)
        {
            //Only run locally or in the network
            string ip = RequestVars.GetRequestIPv4Address();

            if (!ip.Equals("127.0.0.1") && !ip.StartsWith("172.16.") && !ip.StartsWith("192.168.0."))
            {
                ErrorHandler.WriteLog("GCC_Web_Portal.Jobs", "Job attempted to be run by invalid IP: " + ip, ErrorHandler.ErrorEventID.General);
                return;
            }
            //Get the job ID
            string jobID = RequestVars.Get("jobid", String.Empty);

            switch (jobID)
            {
            case "e07db58b-d3a6-4e01-a5ed-ff9875773b3c":

                #region Send weekly notification email

                DateTime startDate = DateTime.Now.Date.AddDays(-7);
                DateTime endDate   = DateTime.Now.Date.AddMilliseconds(-1);
                //DateTime startDate = new DateTime( 2015, 7, 1 ).Date;
                //DateTime endDate = new DateTime( 2015, 8, 1 ).Date.AddMilliseconds( -1 );
                SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;
                DataTable   dt  = sql.ExecStoredProcedureDataTable("spJobs_StatusEmail",
                                                                   new SQLParamList()
                                                                   .Add("@DateCreated_Begin", startDate)
                                                                   .Add("@DateCreated_End", endDate));
                StringBuilder sbCurrent = new StringBuilder();
                sbCurrent.AppendFormat(@"<h3 style='margin:20px 0'>GEI / GSEI Dashboard for {0} to {1}</h3><table style='border-collapse:collapse;border:1px solid #444;width:100%' cellspacing='0' cellpadding='0'>", startDate.ToString("MMM d, yyyy"), endDate.ToString("MMM d, yyyy"));
                sbCurrent.AppendFormat("<thead><tr><th{0}></th><th{0}># Surveys</th><th{0}>GEI</th><th{0}>NPS</th><th{0}>PRS</th><th{0}>GSEI</th><th{0}># Followup</th><th{0}>% Followup</th><th{0}># <24h</th><th{0}>#24-48h</th><th{0}># > 48h</th><th{0}>Avg. Response</th></tr></thead>",
                                       " style='padding:5px;border:1px solid #BBB'");
                StringBuilder sbComparison = new StringBuilder("<h3 style='margin:20px 0'>Change from Previous Week</h3><table style='border-collapse:collapse;border:1px solid #444;width:100%' cellspacing='0' cellpadding='0'>");
                sbComparison.AppendFormat("<thead><tr><th{0}></th><th{0}># Surveys</th><th{0}>GEI</th><th{0}>NPS</th><th{0}>PRS</th><th{0}>GSEI</th><th{0}># Followup</th><th{0}>% Followup</th><th{0}># <24h</th><th{0}>#24-48h</th><th{0}># > 48h</th><th{0}>Avg. Response</th></tr></thead>",
                                          " style='padding:5px;border:1px solid #BBB'");
                Dictionary <string, List <string> > redFlagDetails = new Dictionary <string, List <string> >();
                foreach (DataRow dr in dt.Rows)
                {
                    sbCurrent.AppendFormat("<tr><th style='padding:5px;text-align:left;border:1px solid #BBB;'>{0}</th><td{12}>{1:#,###}</td><td{12}>{2}</td><td{12}>{3}</td><td{12}>{4}</td><td{12}>{5}</td><td{12}>{6:#,###}</td><td{12}>{7:#,###}</td><td{12}>{8:#,###}</td><td{12}>{9:#,###}</td><td{12}>{10:#,###}</td><td{12}>{11}</td></tr>",
                                           dr["ShortCode"],
                                           dr["TotalRecords"],
                                           ReportingTools.FormatIndex(dr["GEI"].ToString()),
                                           ReportingTools.FormatPercent(dr["NPS"].ToString()),
                                           ReportingTools.FormatPercent(dr["PRS"].ToString()),
                                           ReportingTools.FormatPercent(dr["GSEI"].ToString()),
                                           dr["FeedbackCount"], //6
                                           ReportingTools.FormatPercent(dr["FeedbackCompletePercent"].ToString()),
                                           dr["FeedbackLessThan24Hrs"],
                                           dr["Feedback24HrsTo48Hrs"],
                                           dr["FeedbackGreaterThan48Hrs"],
                                           ReportingTools.MinutesToNiceTime(dr["AverageFeedbackResponse"].ToString()),
                                           " style='padding:5px;border:1px solid #BBB;text-align:center'"
                                           );
                    sbComparison.AppendFormat("<tr><th style='padding:5px;text-align:left;border:1px solid #BBB;'>{0}</th>{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}</tr>",
                                              dr["ShortCode"],
                                              GetChangeCell(dr, "TotalRecords_Diff", String.Format("{0:#,###}", dr["TotalRecords"]), redFlagDetails, null),
                                              GetChangeCell(dr, "GEI_Diff", ReportingTools.FormatIndex(dr["GEI_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r <= -10); }),
                                              GetChangeCell(dr, "NPS_Diff", ReportingTools.FormatPercent(dr["NPS_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r <= -0.1); }),
                                              GetChangeCell(dr, "PRS_Diff", ReportingTools.FormatPercent(dr["PRS_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r <= -0.1); }),
                                              GetChangeCell(dr, "GSEI_Diff", ReportingTools.FormatPercent(dr["GSEI_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r <= -0.1); }),
                                              GetChangeCell(dr, "FeedbackCount_Diff", String.Format("{0:#,###}", dr["FeedbackCount_Diff"]), redFlagDetails, null), //6
                                              GetChangeCell(dr, "FeedbackCompletePercent_Diff", ReportingTools.FormatPercent(dr["FeedbackCompletePercent_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r <= -0.1); }),
                                              GetChangeCell(dr, "FeedbackLessThan24Hrs_Diff", String.Format("{0:#,###}", dr["FeedbackLessThan24Hrs_Diff"]), redFlagDetails, null),
                                              GetChangeCell(dr, "Feedback24HrsTo48Hrs_Diff", String.Format("{0:#,###}", dr["Feedback24HrsTo48Hrs_Diff"]), redFlagDetails, null),
                                              GetChangeCell(dr, "FeedbackGreaterThan48Hrs_Diff", String.Format("{0:#,###}", dr["FeedbackGreaterThan48Hrs_Diff"]), redFlagDetails, null),
                                              GetChangeCell(dr, "AverageFeedbackResponse_Diff", ReportingTools.MinutesToNiceTime(dr["AverageFeedbackResponse_Diff"].ToString()), redFlagDetails, r => { return(r != -1000 && r >= 120); })
                                              );
                }
                sbCurrent.Append("</table><br /><br /><br />");
                sbComparison.Append("</table>");

                StringBuilder sbRedFlags = new StringBuilder();
                foreach (var kvp in redFlagDetails)
                {
                    if (sbRedFlags.Length == 0)
                    {
                        sbRedFlags.Append("<h3 style='margin:20px 0'>Red Flag Summary</h3><ul>");
                    }
                    if (kvp.Key.Length <= 4)
                    {
                        //Score
                        sbRedFlags.AppendFormat("<li><b>{0} score</b> has decreased by at least 10% for the following site(s): ", kvp.Key);
                    }
                    else if (kvp.Key.Equals("FeedbackCompletePercent"))
                    {
                        //Completion percentage
                        sbRedFlags.Append("<li><b>Feedback Completion</b> has decreased by at least 10% for the following site(s): ");
                    }
                    else if (kvp.Key.Equals("AverageFeedbackResponse"))
                    {
                        //Feedback response
                        sbRedFlags.Append("<li><b>Average Feedback Response</b> has increased by at least 2 hours for the following site(s): ");
                    }
                    foreach (string shortCode in kvp.Value)
                    {
                        sbRedFlags.AppendFormat("{0}, ", shortCode);
                    }
                    sbRedFlags.Remove(sbRedFlags.Length - 2, 2)
                    .Append("</li>");
                }
                if (sbRedFlags.Length > 0)
                {
                    sbRedFlags.Append("</ul><br />");
                    sbCurrent.Insert(0, sbRedFlags.ToString());
                }

                MailMessage msg = null;
                try
                {
                    var replacementModel = new
                    {
                        DataTables = sbCurrent.ToString() + sbComparison.ToString()
                    };
                    string path = context.Server.MapPath("~/Content/notifications/");
                    msg = EmailManager.CreateEmailFromTemplate(
                        Path.Combine(path, "WeeklyNotification.htm"),
                        replacementModel);
                    msg.IsBodyHtml   = true;
                    msg.BodyEncoding = System.Text.Encoding.UTF8;
                    msg.From         = new MailAddress("*****@*****.**");
                    msg.Subject      = "GCGC Weekly Status Notification - Week Ending " + endDate.ToString("MMM d, yyyy");
                    bool hasAddress = false;

                    dt = sql.QueryDataTable(@"
SELECT [SendType], u.[FirstName], u.[LastName],  u.[Email]
FROM [tblNotificationUsers] ne
	INNER JOIN [tblNotificationPropertySurveyReason] psr
		ON ne.[PropertySurveyReasonID] = psr.[PropertySurveyReasonID]
	INNER JOIN [tblCOM_Users] u
		ON ne.UserID = u.UserID
WHERE psr.PropertyID = @PropertyID
    AND psr.SurveyTypeID = @SurveyID
    AND psr.ReasonID = @ReasonID
;",
                                            new SQLParamList()
                                            .Add("@PropertyID", (int)GCCPropertyShortCode.GCC)
                                            .Add("@SurveyID", (int)SurveyType.GEI)
                                            .Add("@ReasonID", (int)NotificationReason.WeeklyStatusNotification)
                                            );
                    if (!sql.HasError && dt.Rows.Count > 0)
                    {
                        StringBuilder addrs = new StringBuilder();
                        foreach (DataRow dr in dt.Rows)
                        {
                            switch (dr["SendType"].ToString())
                            {
                            case "1":
                                msg.To.Add(dr["Email"].ToString());
                                addrs.Append(dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n");
                                hasAddress = true;
                                break;

                            case "2":
                                msg.CC.Add(dr["Email"].ToString());
                                //Colin requested that CC addresses not show on the call Aug 10,2015
                                //addrs.Append( dr["FirstName"].ToString() + " " + dr["LastName"].ToString() + " <" + dr["Email"].ToString() + ">" + "\n" );
                                hasAddress = true;
                                break;

                            case "3":
                                msg.Bcc.Add(dr["Email"].ToString());
                                hasAddress = true;
                                break;
                            }
                        }
                        //using ( StreamReader sr = new StreamReader( msg.AlternateViews[0].ContentStream ) ) {
                        //    msg.AlternateViews[0] = AlternateView.CreateAlternateViewFromString( sr.ReadToEnd().Replace( "{Recipients}", context.Server.HtmlEncode( addrs.ToString() ).Replace( "\n", "<br />" ) ), null, MediaTypeNames.Text.Html );
                        //}
                    }

                    if (hasAddress)
                    {
                        msg.Send();
                    }
                }
                catch (Exception ex)
                {
                    ErrorHandler.WriteLog("GCC_Web_Portal.Jobs", "Error running job.", ErrorHandler.ErrorEventID.General, ex);
                }
                finally
                {
                    if (msg != null)
                    {
                        msg.Dispose();
                        msg = null;
                    }
                }
                return;

                #endregion Send weekly notification email

            case "506aebb3-dfa2-4b34-94bc-51e81f5f31d3":

                #region Send Feedback Reminder Email

                sql = new SQLDatabase();
                dt  = sql.ExecStoredProcedureDataTable("[spJobs_48HrReminder]");
                foreach (DataRow dr in dt.Rows)
                {
                    GCCPropertyShortCode sc;
                    SurveyType           st;
                    NotificationReason   nr;
                    DateTime             created = Conversion.XMLDateToDateTime(dr["DateCreated"].ToString());
                    string feedbackUID           = dr["UID"].ToString();
                    if (Enum.TryParse(dr["PropertyID"].ToString(), out sc) &&
                        Enum.TryParse(dr["SurveyTypeID"].ToString(), out st) &&
                        Enum.TryParse(dr["ReasonID"].ToString(), out nr))
                    {
                        switch (st)
                        {
                        case SurveyType.GEI:
                            string gagLocation = dr["GEIGAGLocation"].ToString();
                            if (gagLocation.Length > 0)
                            {
                                gagLocation = " - " + gagLocation;
                            }
                            string fbLink = GCCPortalUrl + "Admin/Feedback/" + feedbackUID;
                            SurveyTools.SendNotifications(HttpContext.Current.Server, sc, st, nr, string.Empty,
                                                          new
                            {
                                Date               = created.ToString("yyyy-MM-dd"),
                                CasinoName         = PropertyTools.GetCasinoName((int)sc) + gagLocation,
                                Problems           = (dr["Q27"].Equals(1) ? "Yes" : "No"),
                                Response           = (dr["Q40"].Equals(1) ? "Yes" : "No"),
                                ProblemDescription = dr["Q27B"].ToString(),
                                StaffComment       = dr["Q11"].ToString(),
                                GeneralComments    = dr["Q34"].ToString(),
                                MemorableEmployee  = dr["Q35"].ToString(),
                                FeedbackLinkTXT    = (String.IsNullOrWhiteSpace(feedbackUID) ? String.Empty : "\n\nRespond to this feedback:\n" + fbLink + "\n"),
                                FeedbackLinkHTML   = (String.IsNullOrWhiteSpace(feedbackUID) ? String.Empty : @"<br /><br />
	<p><b>Respond to this feedback:</b></p>
	<p>"     + fbLink + "</p>"),
                                SurveyLink = GCCPortalUrl + "Display/GEI/" + dr["RecordID"].ToString()
                            },
                                                          String.Empty,
                                                          "Overdue: ");
                            break;

                        case SurveyType.Hotel:
                            SurveyTools.SendNotifications(HttpContext.Current.Server, sc, st, nr, string.Empty,
                                                          new
                            {
                                CasinoName       = PropertyTools.GetCasinoName((int)sc),
                                FeedbackNoteHTML = "<p><b>This guest has requested a response.</b> You can view and respond to the feedback request by clicking on (or copying and pasting) the following link:</p>\n<p>" + GCCPortalUrl + "Admin/Feedback/" + feedbackUID + "</p>",
                                FeedbackNoteTXT  = "The guest requested feedback. You can view and respond to the feedback request by clicking on (or copying and pasting) the following link:\n" + GCCPortalUrl + "Admin/Feedback/" + feedbackUID + "\n\n",
                                SurveyLink       = GCCPortalUrl + "Display/Hotel/" + dr["RecordID"].ToString()
                            },
                                                          String.Empty,
                                                          "Overdue: ");
                            break;

                        case SurveyType.Feedback:
                            gagLocation = dr["FBKGAGLocation"].ToString();
                            if (gagLocation.Length > 0)
                            {
                                gagLocation = " - " + gagLocation;
                            }
                            SurveyTools.SendNotifications(HttpContext.Current.Server, sc, st, nr, string.Empty,
                                                          new
                            {
                                Date             = created.ToString("yyyy-MM-dd"),
                                CasinoName       = PropertyTools.GetCasinoName((int)sc) + gagLocation,
                                FeedbackNoteHTML = "<p><b>This guest has requested a response.</b> You can view and respond to the feedback request by clicking on (or copying and pasting) the following link:</p>\n<p>" + GCCPortalUrl + "Admin/Feedback/" + feedbackUID + "</p>",
                                FeedbackNoteTXT  = "The guest requested feedback. You can view and respond to the feedback request by clicking on (or copying and pasting) the following link:\n" + GCCPortalUrl + "Admin/Feedback/" + feedbackUID + "\n\n",
                                SurveyLink       = GCCPortalUrl + "Display/Feedback/" + dr["RecordID"].ToString()
                            },
                                                          String.Empty,
                                                          "Overdue: ");
                            break;

                        case SurveyType.Donation:
                            SurveyTools.SendNotifications(HttpContext.Current.Server, sc, st, nr, string.Empty,
                                                          new
                            {
                                Date         = created.ToString("yyyy-MM-dd"),
                                CasinoName   = PropertyTools.GetCasinoName((int)sc),
                                FeedbackLink = GCCPortalUrl + "Admin/Feedback/" + feedbackUID,
                                Link         = GCCPortalUrl + "Display/Donation/" + dr["RecordID"].ToString()
                            },
                                                          String.Empty,
                                                          "Overdue: ");
                            break;
                        }
                    }
                }
                return;

                #endregion Send Feedback Reminder Email
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("Invalid Job ID.");
        }
        /// <summary>
        ///     Perform password reset
        /// </summary>
        /// <param name="isGuidReset">is this a password retrieval?</param>
        public void ResetPassword(bool isGuidReset)
        {
            string         pass       = Request.Form["pwd"];     //Old password
            string         newpass1   = Request.Form["newpwd1"]; //New passwords
            string         newpass2   = Request.Form["newpwd2"];
            LoginErrorCode loginError = LoginErrorCode.UnknownError;
            UserInfo       user       = UserData;

            //If this isn't a GUID-based reset (we already checked those)
            if (!isGuidReset)
            {
                int outputValue;
                user       = UserInformation.LogUserIn <UserInfo>(user.Email, pass, true, Config.ClientID, out outputValue);
                loginError = (LoginErrorCode)outputValue;
                if (loginError != LoginErrorCode.Success)
                {
                    user = SessionWrapper.Get <UserInfo>("UserInfo", null);
                    switch (loginError)
                    {
                    case LoginErrorCode.NoUserOrEmailSpecified:
                        mmMessages.ErrorMessage = "Please enter your old password.";
                        return;

                    case LoginErrorCode.LoginFailed:
                        mmMessages.ErrorMessage = "Invalid password.";
                        return;

                    case LoginErrorCode.UserLockedOut:
                        mmMessages.ErrorMessage = "This account has been locked out. Please try again in 30 minutes.";
                        return;

                    case LoginErrorCode.UserOrEmailNotExists:
                        mmMessages.ErrorMessage = "This user doesn't appear to exist. If you think this is an error, please contact the administrator.";
                        return;
                    }
                }
            }
            if (user == null)
            {
                //Error message!
                mmMessages.ErrorMessage = "We're sorry. We couldn't find the user associated with this account. Please try again.";
                return;
            }
            UserData = user;
            //Validate new password
            if (newpass1 != newpass2)
            {
                mmMessages.ErrorMessage = "These new passwords don't match.";
                return;
            }
            //try to update password and return error message if invalid
            string error;

            if (!UserData.UpdatePassword(newpass1, out error))
            {
                mmMessages.ErrorMessage = error;
                return;
            }

            int rows = UserData.ClearLoginAttempts();

#if DEBUG
            Debug.WriteLine("{0} Login Attempts deleted");
#endif

            //Get user with new password to make sure that everything is OK
            int outputValue2;
            UserData = UserInformation.LogUserIn <UserInfo>(UserData.Email, newpass1, true, Config.ClientID, out outputValue2);

            if (UserData == null)
            {
                if (user != null)
                {
                    UserData = user;
                }
                else
                {
                    UserData = SessionWrapper.Get <UserInfo>("UserInfo", null);
                }

                mmMessages.ErrorMessage = "There was a database level error while attempting to save this user. Please contact the administrator if this error persists.";
                return;
            }

            SessionWrapper.Add("UserInfo", UserData);

            string redir = RequestVars.Get("rd", String.Empty);
            if (!String.IsNullOrEmpty(redir))
            {
                redir = "?rd=" + HttpContext.Current.Server.UrlEncode(redir);
            }
            Response.Redirect("/Director.ashx" + redir);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.HideAllFilters = true;
            if (RequestVars.Get("a", 0) == 1)
            {
                Response.Clear();
                switch (RequestVars.Get("t", 0))
                {
                case 1:                         //Remove
                    int propSurvReaID = RequestVars.Post("p", -1);
                    int userID        = RequestVars.Post("u", -1);
                    int sendType      = RequestVars.Post("s", -1);
                    if (propSurvReaID != -1 && userID != -1 && sendType != -1)
                    {
                        SQLDatabase sql  = new SQLDatabase();    sql.CommandTimeout = 120;
                        int         rows = sql.NonQuery(
                            @"DELETE FROM [tblNotificationUsers] WHERE [PropertySurveyReasonID] = @PropertySurveyReasonID AND [UserID] = @UserID AND [SendType] = @SendType",
                            new SQLParamList().Add("@PropertySurveyReasonID", propSurvReaID)
                            .Add("@UserID", userID)
                            .Add("@SendType", sendType)
                            );
                        if (!sql.HasError)
                        {
                            if (rows != 0)
                            {
                                Response.Write(new JSONBuilder().AddInt("s", 0));
                            }
                            else
                            {
                                Response.Write(new JSONBuilder().AddInt("s", 4).AddString("msg", "No matching records found. Refresh the page to see the most up to date information."));
                            }
                        }
                        else
                        {
                            Response.Write(new JSONBuilder().AddInt("s", 3).AddString("msg", "There was a problem contacting the database. Please try again. (ENM105)"));
                        }
                    }
                    else
                    {
                        Response.Write(new JSONBuilder().AddInt("s", 2).AddString("msg", "Invalid values specified."));
                    }
                    break;

                case 2:                         //Get user list
                    propSurvReaID = RequestVars.Get("p", -1);
                    if (propSurvReaID != -1)
                    {
                        SQLDatabase sql = new SQLDatabase();    sql.CommandTimeout = 120;
                        DataTable   dt  = sql.QueryDataTable(@"
SELECT [UserID],[FirstName],[LastName]
FROM [tblCOM_Users]
WHERE [UserID] NOT IN (SELECT [UserID] FROM [tblNotificationUsers] WHERE [PropertySurveyReasonID] = @PSRID )
	AND [Active] = 1
ORDER BY [FirstName], [LastName]",
                                                             new SqlParameter("@PSRID", propSurvReaID));

                        if (!sql.HasError)
                        {
                            JSONBuilder jb = new JSONBuilder().AddInt("s", 0);
                            jb.AddArray("ubh");
                            foreach (DataRow dr in dt.Rows)
                            {
                                jb.AddObject()
                                .AddInt("i", (int)dr["UserID"])
                                .AddString("n", dr["FirstName"].ToString() + " " + dr["LastName"].ToString())
                                .CloseObject();
                            }
                            jb.CloseArray();
                            Response.Write(jb);
                        }
                        else
                        {
                            Response.Write(new JSONBuilder().AddInt("s", 3).AddString("msg", "There was a problem contacting the database. Please try again. (ENM106)"));
                        }
                    }
                    else
                    {
                        Response.Write(new JSONBuilder().AddInt("s", 2).AddString("msg", "Invalid values specified."));
                    }
                    break;

                default:
                    Response.Write(new JSONBuilder().AddInt("s", 1).AddString("msg", "Invalid type specified."));
                    break;
                }
                Response.End();
                return;
            }

            if (!IsPostBack)
            {
                //Hide reason by default. Can only be shown if Property and Survey are changed.
                ddlReason.Visible = false;
            }
            else
            {
                lblReasonError.Text = String.Empty;
            }
        }