public void SubmitSecretQuestion(object sender, EventArgs e)
    {
        string centGetUserAttributes = Session["UserAttributes"].ToString();
        var jssGetUserAttributes = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes);

        string strUuid = centGetUserAttribrutes_Dict["Result"]["Uuid"];

        string strSetQuestionJSON = @"{""ID"":""" + strUuid + @""",""securityquestion"":""" + SecretQuestion.Text + @""",""questionanwser"":""" + SecretAnswer.Text + @"""}";

        Centrify_API_Interface centSetQuestion = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetSecurityQuestionURL, strSetQuestionJSON);
        var jssSetQuestion = new JavaScriptSerializer();
        Dictionary<string, dynamic> centSetQuestion_Dict = jssSetQuestion.Deserialize<Dictionary<string, dynamic>>(centSetQuestion.returnedResponse);

        if (centSetQuestion_Dict["success"].ToString() != "True")
        {
            FailureText.Text = centSetQuestion_Dict["success"].ToString();
            ErrorMessage.Visible = true;
        }
        else
        {
            SecretQuestion_Div.Visible = false;
            AccountOverview.Visible = true;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        //if (!Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        {
            NotLoggedIn.Visible = false;

            if (!IsPostBack)
            {
                string strGetRolesJSON = @"{""Script"":""select * from Role"",""Args"":{""PageNumber"":1,""PageSize"":10000,""Limit"":10000,""SortBy"":"""",""direction"":""False"",""Caching"":-1}}";
                Centrify_API_Interface centGetRoles = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentQueryURL, strGetRolesJSON);
                var jssGetRoles = new JavaScriptSerializer();
                Dictionary<string, dynamic> centGetRoles_Dict = jssGetRoles.Deserialize<Dictionary<string, dynamic>>(centGetRoles.returnedResponse);

                SortedList<string, string> RolesList = new SortedList<string, string>();

                ArrayList centGetRoles_Roles = centGetRoles_Dict["Result"]["Results"];
                foreach (Dictionary<string, object> dRoles in centGetRoles_Roles)
                {
                    dynamic dRole = dRoles["Row"];
                    if (dRole["Name"] != null)
                    {
                        RolesList.Add(dRole["Name"], dRole["ID"]);
                    }
                    else
                    {
                        RolesList.Add(dRole["ID"], dRole["ID"]);
                    }
                }

                Roles_Dropdown.DataTextField = "Key";
                Roles_Dropdown.DataValueField = "Value";
                Roles_Dropdown.DataSource = RolesList;
                Roles_Dropdown.DataBind();
            }
        }
        else
        {
            Manage.Visible = false;           
        }

        ResultMessage.Visible = false;

        SetPassword.Visible = false;
        SetPassword_Label.Visible = false;
        Account_Enabled.Visible = false;
        Account_Enabled_Label.Visible = false;
        Account_Locked.Visible = false;
        Account_Locked_Label.Visible = false;
        ModifyUser_Button.Visible = false;


    }
    protected void CreateUser(object sender, EventArgs e)
    {
        string strCreateUserJSON = "{Name:'" + UserName.Text + "', Mail:'" + UserName.Text + "', Password:'******'}";
        Centrify_API_Interface centCreateUser = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentCreateUserURL, strCreateUserJSON);
        var jssAdvanceAuthPoll = new JavaScriptSerializer();
        Dictionary<string, dynamic> centCreateUser_Dict = jssAdvanceAuthPoll.Deserialize<Dictionary<string, dynamic>>(centCreateUser.returnedResponse);

        if (centCreateUser_Dict["Message"].ToString() != null)
        {
            ResultMessage.Text = centCreateUser_Dict["Message"].ToString();
        }
        else
        {
            ResultMessage.Text = "Create User Successful.";
        }

        ResultMessage.Visible = true;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["OTP"].ToString() != "")
            {
                string loginJSON = @"{""force"":""True""}";
                Centrify_API_Interface cent = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentGetAppsURL, loginJSON);

                string strApps = cent.returnedResponse;

                var jss = new JavaScriptSerializer();
                Dictionary<string, dynamic> sData = jss.Deserialize<Dictionary<string, dynamic>>(strApps);

                var dApps = sData["Result"]["Apps"];

                int iCount = 0;

                foreach (var app in dApps)
                {
                    string strDisplayName = app["DisplayName"];
                    string strAppKey = app["AppKey"];
                    string strIcon = app["Icon"];

                    AddUrls(strAppKey, strDisplayName, strIcon, iCount);

                    iCount++;

                }

                NotLoggedIn.Visible = false;
            }
            else
            {
                Apps.Visible = false;
            }
        }
        catch (Exception)
        {
            Apps.Visible = false;            
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        //if (!Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        {
            NotLoggedIn.Visible = false;

            if (!IsPostBack)
            {
                string strGetUserAttributesJSON = "{ID:null}";
                Centrify_API_Interface centGetUserAttributes = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentGetUserAttributesURL, strGetUserAttributesJSON);
                var jssGetUserAttributes = new JavaScriptSerializer();
                Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes.returnedResponse);

                Session["UserAttributes"] = centGetUserAttributes.returnedResponse;

                UserName.Text = centGetUserAttribrutes_Dict["Result"]["Name"];
                LoginName.Text = centGetUserAttribrutes_Dict["Result"]["DisplayName"];
                Alias.Text = centGetUserAttribrutes_Dict["Result"]["Alias"];
                Email.Text = centGetUserAttribrutes_Dict["Result"]["Mail"];
                DisplayName.Text = centGetUserAttribrutes_Dict["Result"]["DisplayName"];
                Mobile.Text = centGetUserAttribrutes_Dict["Result"]["MobileNumber"];
                OfficePhone.Text = centGetUserAttribrutes_Dict["Result"]["OfficeNumber"];
                HomePhone.Text = centGetUserAttribrutes_Dict["Result"]["HomeNumber"];

                UserName.Enabled = false;
                LoginName.Enabled = false;
                Alias.Enabled = false;

                ResetPassword_Div.Visible = false;
                SecretQuestion_Div.Visible = false;
            }
        }
        else
        {
            AccountOverview.Visible = false;
            ResetPassword_Div.Visible = false;
            SecretQuestion_Div.Visible = false;
        }      
    }
    protected void FindUser(object sender, EventArgs e)
    {
        string strFindUserJSON = @"{""Script"":""select * from dsusers where SystemName = '" + FindUser_UserName.Text + @"';"",""Args"":{""PageNumber"":1,""PageSize"":10000,""Limit"":10000,""SortBy"":"""",""direction"":""False"",""Caching"":-1}}";
        Centrify_API_Interface centFindUser = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentQueryURL, strFindUserJSON);
        var jssFindUser = new JavaScriptSerializer();
        Dictionary<string, dynamic> centFindUser_Dict = jssFindUser.Deserialize<Dictionary<string, dynamic>>(centFindUser.returnedResponse);

        if (centFindUser_Dict["success"].ToString() == "True")
        {
            ResultMessage.Text = "User Found";

            ArrayList centFindUser_Results = centFindUser_Dict["Result"]["Results"];
            dynamic centFindUser_Results_Column = centFindUser_Results[0];
            Dictionary<string, dynamic> centFindUser_Results_Row = centFindUser_Results_Column["Row"];

            bool bEnabled = centFindUser_Results_Row["Enabled"];
            bool bLocked = centFindUser_Results_Row["Locked"];
            Session["UserId"] = centFindUser_Results_Row["InternalName"];

            SetPassword.Visible = true;
            SetPassword_Label.Visible = true;

            if (bEnabled)
            {
                Account_Enabled.Checked = true;
            }

            Account_Enabled.Visible = true;
            Account_Enabled_Label.Visible = true;

            if (bLocked)
            {
                Account_Locked.Checked = true;
            }

            Account_Locked.Visible = true;
            Account_Locked_Label.Visible = true;
            ModifyUser_Button.Visible = true;
            ModifyUser_Button.Enabled = true; // Broken

            Find_User_Button.Visible = false;
            FindUser_UserName.Visible = false;
            FindUser_UserName_Label.Visible = false;

        }
        else
        {
            ResultMessage.Text = "Failed to find user: " + centFindUser.returnedResponse;
        }

        ResultMessage.Visible = true;
    }
    protected void AddUserToRole(object sender, EventArgs e)
    {       
        string strGetRoleMemebersJSON = "";
        Centrify_API_Interface centGetRoleMemebers = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentGetRoleMemebersURL + "?name=" + Roles_Dropdown.SelectedValue.ToString(), strGetRoleMemebersJSON);
        var jssGetRoleMemebers = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetRoleMemebers_Dict = jssGetRoleMemebers.Deserialize<Dictionary<string, dynamic>>(centGetRoleMemebers.returnedResponse);

        if (centGetRoleMemebers_Dict["success"].ToString() == "True")
        {
            ResultMessage.Text = "Role Memebers Found.";
        }
        else
        {
            ResultMessage.Text = "Failed to Get Role Memebers: " + centGetRoleMemebers.returnedResponse;
        }

        ArrayList centGetRoleMemebers_Results = centGetRoleMemebers_Dict["Result"]["Results"];

        string strUpdateRoleJSONUsers_Prefix = @"{""Users"":[""";
        string strUpdateRoleJSONGroups_Prefix = @"""Groups"":[],";
        string strUpdateRoleJSONRoles_Prefix = @"""Roles"":[],";

        foreach (Dictionary<string, dynamic> dMemebers in centGetRoleMemebers_Results)
        {
            dynamic dMemeber = dMemebers["Row"];
            strUpdateRoleJSONUsers_Prefix = strUpdateRoleJSONUsers_Prefix + dMemeber["Guid"] + @""", """;           
        }

        string strFindUserJSON = @"{""Script"":""select * from dsusers where SystemName = '" + UserToAdd.Text + @"';"",""Args"":{""PageNumber"":1,""PageSize"":10000,""Limit"":10000,""SortBy"":"""",""direction"":""False"",""Caching"":-1}}";

        Centrify_API_Interface centFindUser = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentQueryURL, strFindUserJSON);
        var jssFindUser = new JavaScriptSerializer();
        Dictionary<string, dynamic> centFindUser_Dict = jssFindUser.Deserialize<Dictionary<string, dynamic>>(centFindUser.returnedResponse);

        if (centFindUser_Dict["success"].ToString() == "True")
        {
            ResultMessage.Text = "User GUID Found.";
        }
        else
        {
            ResultMessage.Text = "Failed to Find User: "******"Result"]["Results"];
        dynamic centFindUser_Results_Column = centFindUser_Results[0];
        Dictionary<string, dynamic> centFindUser_Results_Row = centFindUser_Results_Column["Row"];

        string strUserUuid = centFindUser_Results_Row["InternalName"];
        
        strUpdateRoleJSONUsers_Prefix = strUpdateRoleJSONUsers_Prefix + strUserUuid + @"""],";

        string strUpdateRoleJSON = strUpdateRoleJSONUsers_Prefix + strUpdateRoleJSONGroups_Prefix + strUpdateRoleJSONRoles_Prefix + @"""Name"":""" + Roles_Dropdown.SelectedValue.ToString() + @"""}";

        Centrify_API_Interface centUpdateRole = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentUpdateRoleURL, strUpdateRoleJSON);
        var jssUpdateRole = new JavaScriptSerializer();
        Dictionary<string, dynamic> centUpdateRole_Dict = jssGetRoleMemebers.Deserialize<Dictionary<string, dynamic>>(centUpdateRole.returnedResponse);

        if (centFindUser_Dict["success"].ToString() == "True")
        {
            ResultMessage.Text = "User Successfully Added to Role.";
        }
        else
        {
            ResultMessage.Text = "Failed to Add User to Role: " + centUpdateRole.returnedResponse;
        }
    }
    protected void CreateRole(object sender, EventArgs e)
    {
        string strStoreRoleJSON = @"{""Name"":""" + CreateRole_Name.Text + @"""}";
        Centrify_API_Interface centStoreRole = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentStoreRoleURL, strStoreRoleJSON);
        var jssStoreRole = new JavaScriptSerializer();
        Dictionary<string, dynamic> centSetPass_Dict = jssStoreRole.Deserialize<Dictionary<string, dynamic>>(centStoreRole.returnedResponse);

        if (centSetPass_Dict["success"].ToString() == "True")
        {
            ResultMessage.Text = "Role Created.";
        }
        else
        {
            ResultMessage.Text = "Failed to Set Password: " + centStoreRole.returnedResponse;
        }
    }
    protected void ModifyUser(object sender, EventArgs e)
    {
        string strState = null;

        if (Account_Locked.Checked)
        {
            strState = "Locked";
        }
        else
        {
            strState = "None";
        }

        string strModifyUserJSON = @"{""ID"":""" + Session["UserId"].ToString() + @""", ""enableState"":" + Account_Enabled.Checked.ToString().ToLower() + @",""state"":""" + strState + @"""}";
        Centrify_API_Interface centSetUser = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetUserURL, strModifyUserJSON);
        var jss = new JavaScriptSerializer();
        Dictionary<string, dynamic> centSetUser_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centSetUser.returnedResponse);

        if (centSetUser_Dict["success"].ToString() == "True" && centSetUser_Dict["success"].ToString() == "True")
        {
            if (SetPassword.Text != null)
            {
                string strSetPassJSON = @"{""ID"":""" + Session["UserId"].ToString() + @""",""ConfrimPassword"":""" + SetPassword.Text + @""",""newPassword"":""" + SetPassword.Text + @"""}";
                Centrify_API_Interface centSetPass = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetPassURL, strSetPassJSON);
                var jssSetPass = new JavaScriptSerializer();
                Dictionary<string, dynamic> centSetPass_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centSetPass.returnedResponse);
                if (centSetPass_Dict["success"].ToString() == "True")
                {
                    ResultMessage.Text = "User Updated.";
                }
                else
                {
                    ResultMessage.Text = "Failed to Set Password: "******"Failed to Modify user: " + centSetUser.returnedResponse;
        }

        ResultMessage.Visible = true;

        //Reset
        Find_User_Button.Visible = true;
        FindUser_UserName.Visible = true;
        FindUser_UserName_Label.Visible = true;

        UserName.Text = null;
        Password.Text = null;
        Account_Enabled.Checked = false;
        Account_Locked.Checked = false;
    }
    public void SubmitPassword(object sender, EventArgs e)
    {
        string centGetUserAttributes = Session["UserAttributes"].ToString();
        var jssGetUserAttributes = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes);

        string strUuid = centGetUserAttribrutes_Dict["Result"]["Uuid"];

        string strSetPassJSON = @"{""ID"":""" + strUuid + @""",""ConfrimPassword"":""" + NewPassword.Text + @""",""newPassword"":""" + ConfirmPassword.Text + @"""}";

        Centrify_API_Interface centSetPass = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetPassURL, strSetPassJSON);
        var jssSetPass = new JavaScriptSerializer();
        Dictionary<string, dynamic> centChangeUser_Dict = jssSetPass.Deserialize<Dictionary<string, dynamic>>(centSetPass.returnedResponse);

        if (centChangeUser_Dict["success"].ToString() != "True")
        {
            FailureText.Text = centChangeUser_Dict["success"].ToString();
            ErrorMessage.Visible = true;
        }   
        else
        {
            ResetPassword_Div.Visible = false;
            AccountOverview.Visible = true;
        }
    }
    public void Save(object sender, EventArgs e)
    {
        string centGetUserAttributes = Session["UserAttributes"].ToString();
        var jssGetUserAttributes = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes);

        string strUuid = centGetUserAttribrutes_Dict["Result"]["Uuid"];

        string strChangeUserJSON = @"{""ID"":""" + strUuid + @""",""Mail"":""" + Email.Text + @"""}";
        Centrify_API_Interface centChangeUser = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentChangeUserURL, strChangeUserJSON);
        var jssChangeUser = new JavaScriptSerializer();
        Dictionary<string, dynamic> centChangeUser_Dict = jssChangeUser.Deserialize<Dictionary<string, dynamic>>(centChangeUser.returnedResponse);

        if (centChangeUser_Dict["success"].ToString() != "True")
        {
            FailureText.Text = centChangeUser_Dict["success"].ToString();
            ErrorMessage.Visible = true;
        }        
    }
        //Processes all AdvanceAuth calls
        public string ProcessAdvanceAuth(string strJSON)
        {
            Centrify_API_Interface centAdvanceAuth = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentAdvanceAuthURL, strJSON);
            var jssAdvanceAuthPoll = new JavaScriptSerializer();
            Dictionary<string, dynamic> centAdvanceAuth_Dict = jssAdvanceAuthPoll.Deserialize<Dictionary<string, dynamic>>(centAdvanceAuth.returnedResponse);

            if (centAdvanceAuth_Dict["success"].ToString() == "True")
            {
                if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "OobPending")
                {
                    return "Poll";
                }
                else if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "LoginSuccess")
                {
                    if (centAdvanceAuth.returnedCookie != null)
                    {
                        Session["podFQDN"] = centAdvanceAuth_Dict["Result"]["PodFqdn"].ToString();                        
                        Session["OTP"] = centAdvanceAuth_Dict["Result"]["Auth"].ToString();
                        Session["ASPXAUTH"] = centAdvanceAuth.returnedCookie.Value;
                        HttpContext.Current.Response.Cookies.Add(centAdvanceAuth.returnedCookie);
                        HttpContext.Current.Response.Headers.Add("Authorization", "Bearer " + Session["ASPXAUTH"].ToString());                     

                        String TransferPage = "<script>window.open('../" + Context.Request.QueryString["ReturnUrl"] + "','_self');</script>";
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "temp", TransferPage, false);                       
                    }
                    else
                    {
                        FailureText.Text = "Error: Please contact your system administrator. Error Reason: Valid cookie was not returned.";
                        ErrorMessage.Visible = true;
                    }

                    return "LoginSuccess";

                }
                else if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "StartNextChallenge")
                {
                    if (Session["ResetMechId"] != null)
                    {
                        NewPassValidator.Enabled = true;
                        ConfirmNewPassValidator.Enabled = true;
                        NewPass_Label.Visible = true;
                        NewPass.Visible = true;
                        ConfirmNewPass_Label.Visible = true;
                        ConfirmNewPass.Visible = true;
                        ForgotPass_Submit_button.Visible = true;
                    }
                    else
                    {
                        if (AuthMethod_Second.Items.Count != 0)
                        {
                            AuthMethod.Items.Clear();
                            Session["UPMechId"] = "";

                            AuthMethod_Label.Visible = false;
                            AuthMethod.Visible = false;
                            AuthMethod_Label_Second.Visible = true;
                            AuthMethod_Second.Visible = true;
                            Login.Visible = true;
                        }
                        else
                        {
                            FailureText.Text = "Error: Please contact your system administrator. Error Reason: Unknown Start Next Cahllenge.";
                            ErrorMessage.Visible = true;
                        }
                    }

                    return "StartNextChallenge";
                }
                else if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "NewPackage")
                {
                    Session["StartAuth"] = centAdvanceAuth.returnedResponse;
                    AuthMethod.Items.Clear();
                    SetDropDowns(centAdvanceAuth_Dict, null);
                }
            }
            else
            {
                FailureText.Text = centAdvanceAuth_Dict["Message"].ToString();
                ErrorMessage.Visible = true;
            }

            return "NewPackage";
        }
        protected void LogOut_Click(object sender, EventArgs e)
        {
            //Log Out from Centrify
            Centrify_API_Interface centLogOut = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentLogOutURL, "");
            var jss = new JavaScriptSerializer();
            Dictionary<string, dynamic> centLogOut_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centLogOut.returnedResponse);

            if (centLogOut_Dict["success"].ToString() == "True")
            {
                //Clear Local Cookies
                Session["OTP"] = "";
                Session.Abandon();

                Context.Response.Redirect(Context.Request.RawUrl);
            }
            else
            {
                FailureText_LogOut.Text = "Error. Please contact your system administrator. Error reason: " + centLogOut_Dict["Message"].ToString();
                ErrorMessage_LogOut.Visible = true;
            }


        }
        //Called by Forgot Pass button
        protected void ForgotPass(object sender, EventArgs e)
        {
            //Clear dropdown items
            AuthMethod.Items.Clear();
            AuthMethod_Second.Items.Clear();

            //Get Mechs for Pass Reset
            string strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""Action"":""ForgotPassword""}";

            Centrify_API_Interface centAdvanceAuth = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentAdvanceAuthURL, strAdvanceAuthJSON);

            //Reset Start Auth
            Session["StartAuth"] = centAdvanceAuth.returnedResponse;
            string strMFAMechs = centAdvanceAuth.returnedResponse;

            var jss = new JavaScriptSerializer();
            Dictionary<string, dynamic> centStartAuth_Dict = jss.Deserialize<Dictionary<string, dynamic>>(strMFAMechs);


            if (centStartAuth_Dict["success"].ToString() == "True")
            {
                //Populate dropdown
                SetDropDowns(centStartAuth_Dict, ForgotPass_button);
            }
            else
            {
                FailureText.Text = "Error: Please contact your system administrator.";
                ErrorMessage.Visible = true;
            }
        }
        //Called by Login Button
        protected void AdvanceAuth(object sender, EventArgs e)
        {
            string strStartAuth_Response = null;

            //Parse Selected MFA
            if (Session["StartAuth"] != null)
            {
                strStartAuth_Response = Session["StartAuth"].ToString();

                var jssStartAuth = new JavaScriptSerializer();
                Dictionary<string, dynamic> centStartAuth_Dict = jssStartAuth.Deserialize<Dictionary<string, dynamic>>(strStartAuth_Response);
                ArrayList centStartAuth_Challenges = centStartAuth_Dict["Result"]["Challenges"];

                string strUPMechId = null;

                string strSelectedName = null;
                string strSelectedMechId = null;
                string strSelectedAnswerType = null;
                string strSecretQuestion = null;


                if (AuthMethod.Items.Count != 0)
                {
                    if(AuthMethod_Second.Items.Count == 0)
                    {
                        //One MFA Only
                        strSelectedMechId = AuthMethod.SelectedValue.ToString();
                    }
                    else
                    {
                        //2 MFA
                        strSelectedMechId = AuthMethod.SelectedValue.ToString();
                    }
                }
                else
                {
                    if (AuthMethod_Second.Items.Count == 0)
                    {
                        //Password Only
                        strUPMechId = Session["UPMechId"].ToString();
                    }
                    else
                    {
                        //Password + MFA
                        if (Session["UPMechId"].ToString() != "")
                        {
                            strUPMechId = Session["UPMechId"].ToString();
                        }

                        //Second MFA Only
                        strSelectedMechId = AuthMethod_Second.SelectedValue.ToString();
                    }
                }

                foreach (Dictionary<string, dynamic> centStartAuth_Mechs in centStartAuth_Challenges)
                {
                    foreach (ArrayList mechs in centStartAuth_Mechs.Values)
                    {
                        foreach (Dictionary<string, object> mech in mechs)
                        {
                            if (strSelectedMechId != null)
                            {
                                if (mech["MechanismId"].ToString() == strSelectedMechId)
                                {
                                    strSelectedName = mech["Name"].ToString();
                                    strSelectedAnswerType = mech["AnswerType"].ToString();

                                    if (mech["Name"].ToString() == "SQ")
                                    {
                                        strSecretQuestion = mech["Question"].ToString();
                                    }
                                }                                
                            }                          
                        }
                    }
                }

                string strAdvanceAuthJSON = null;

                //Create JSON for AdvanceAuth by checking what MFA Mechs are available and selected
                if (strUPMechId != null)
                {
                    //Password + MFA
                    if (strSelectedMechId != null)
                    {
                        if (strSelectedAnswerType == "Text")
                        {
                            strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""MultipleOperations"":[{""MechanismId"":""" + strUPMechId + @""",""Answer"":""" + @Password.Text + @""",""Action"":""Answer""},{""MechanismId"":""" + strSelectedMechId + @""",""Answer"":""" + SecretQuestion.Text + @""",""Action"":""Answer""}]}";
                        }
                        else
                        {
                            strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""MultipleOperations"":[{""MechanismId"":""" + strUPMechId + @""",""Answer"":""" + @Password.Text + @""",""Action"":""Answer""},{""MechanismId"":""" + strSelectedMechId + @""",""Action"":""StartOOB""}]}";
                        }
                    }                    
                    //Password Only - No MFA
                    else
                    {
                        strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""MechanismId"":""" + strUPMechId + @""",""Answer"":""" + @Password.Text + @""",""Action"":""Answer""}";
                    }
                }
                //One MFA Only
                else if (strUPMechId == null && strSelectedMechId != null)
                {                   
                    if (strSelectedName != "UP")
                    {
                        strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""MechanismId"":""" + strSelectedMechId + @""",""Action"":""StartOOB""}";
                    }
                    //Password Selected from MFA Dropdown
                    else
                    {
                        strAdvanceAuthJSON = @"{""TenantId"":""" + Session["TenantId"].ToString() + @""",""SessionId"":""" + Session["SessionId"].ToString() + @""",""PersistentLogin"":" + RememberMe.Checked.ToString().ToLower() + @",""MechanismId"":""" + strSelectedMechId + @""",""Answer"":""" + @Password.Text + @""",""Action"":""Answer""}";
                    }
                }
               
                if (strAdvanceAuthJSON == null)
                {
                    FailureText.Text = "Error: Please contact your system administrator. Error Reason: JSON payload was not set.";
                    ErrorMessage.Visible = true;
                }

                else if (strAdvanceAuthJSON != null)
                {
                    //Start Oob - Send MFA
                    Centrify_API_Interface centAdvanceAuth = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentAdvanceAuthURL, strAdvanceAuthJSON);
                    var jssAdvanceAuth = new JavaScriptSerializer();
                    Dictionary<string, dynamic> centAdvanceAuth_Dict = jssAdvanceAuth.Deserialize<Dictionary<string, dynamic>>(centAdvanceAuth.returnedResponse);
                    
                    if (centAdvanceAuth_Dict["success"].ToString() == "True")
                    {                        
                        if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "LoginSuccess")
                        {
                            if (centAdvanceAuth.returnedCookie != null)
                            {
                                Session["podFQDN"] = centAdvanceAuth_Dict["Result"]["PodFqdn"].ToString();
                                Session["OTP"] = centAdvanceAuth_Dict["Result"]["Auth"].ToString();
                                Session["ASPXAUTH"] = centAdvanceAuth.returnedCookie.Value;
                                HttpContext.Current.Response.Cookies.Add(centAdvanceAuth.returnedCookie);
                                HttpContext.Current.Response.Headers.Add("Authorization", "Bearer " + Session["ASPXAUTH"].ToString());

                                String TransferPage = "<script>window.open('../" + Request.QueryString["ReturnUrl"] + "','_self');</script>";
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "temp", TransferPage, false);
                            }
                            else
                            {
                                FailureText.Text = "Error: Please contact your system administrator. Error Reason: Valid cookie was not returned.";
                                ErrorMessage.Visible = true;
                            }
                        }
                        //Precess MFA Types
                        else if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "OobPending")
                        {
                            if (strSelectedAnswerType != null)
                            {
                                //Text Based MFA
                                if (strSelectedAnswerType == "StartTextOob")
                                {
                                    MFAAnswer_Label.Visible = true;
                                    MFAAnswer.Visible = true;
                                    MFAAnswer_Submit.Visible = true;
                                    MFAAnswer_Validator.Enabled = true;
                                    Next.Visible = false;

                                    if (strSecretQuestion != null)
                                    {
                                        MFAMessage.Text = "Please Enter The Answer to the Question: " + strSecretQuestion;
                                    }
                                    else
                                    {
                                        MFAMessage.Text = "Please Enter The Answer to the Selected MFA Method.";
                                    }

                                    MFAMessage.Visible = true;

                                    if (strSelectedName == "OTP")
                                    {
                                        //StartPoll();
                                        Timer1.Enabled = true;
                                    }

                                    if (strSelectedName == "SMS")
                                    {
                                        //StartPoll();
                                        Timer1.Enabled = true;
                                    }
                                }

                                //Polling MFA
                                else if (strSelectedAnswerType == "StartOob")
                                {
                                    StartPoll();
                                }
                                else
                                {
                                    FailureText.Text = "Error: Please contact your system administrator. Error Reason: Unknown Mech Answer Type.";
                                    ErrorMessage.Visible = true;
                                }
                            }
                            else
                            {
                                FailureText.Text = "Error: Please contact your system administrator. Error Reason: Mech Answer Type is null.";
                                ErrorMessage.Visible = true;
                            }
                        }
                        else if (centAdvanceAuth_Dict["Result"]["Summary"].ToString() == "NewPackage")
                        {
                            Session["StartAuth"] = centAdvanceAuth.returnedResponse;
                            AuthMethod.Items.Clear();
                            SetDropDowns(centAdvanceAuth_Dict, null);
                        }
                        else
                        {
                            FailureText.Text = "Error: Please contact your system administrator. Error Reason: Unknown Mech Result Summary.";
                            ErrorMessage.Visible = true;
                        }
                    }
                    else
                    {
                        FailureText.Text = centAdvanceAuth_Dict["Message"].ToString();
                        ErrorMessage.Visible = true;
                    }
                }
            }
            else
            {
                FailureText.Text = "Error: Please contact your system administrator. Error Reason: StartAuth was not set.";
                ErrorMessage.Visible = true;
            }
        }
        //Called by Next Button
        protected void Next_Login(object sender, EventArgs e)
        {
            Session["NewPodURL"] = ConfigurationManager.AppSettings["CentPodURL"].ToString();

            AuthMethod.Items.Clear();
            AuthMethod_Second.Items.Clear();

            pwdValidator.Enabled = true;

            //Populate MFA Dropdown
            string strStartAuthJSON = @"{""User"":""" + UserName.Text + @""", ""Version"":""1.0""}";
            Centrify_API_Interface centStartAuth = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentStartAuthURL, strStartAuthJSON);
            var jss = new JavaScriptSerializer();
            Dictionary<string, dynamic> centStartAuth_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centStartAuth.returnedResponse);

            if (centStartAuth_Dict["success"].ToString() == "True")
            {
                //Detect if a redirect to pod was returned
                if (centStartAuth_Dict["Result"].ContainsKey("PodFqdn"))
                {
                    Session["NewPodURL"] = "https://" + centStartAuth_Dict["Result"]["PodFqdn"];
                    string test = Session["NewPodURL"].ToString() + CentStartAuthURL;
                    Centrify_API_Interface centStartAuth_redirect = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentStartAuthURL, strStartAuthJSON);

                    //Store Redirected Result in session
                    Session["StartAuth"] = centStartAuth_redirect.returnedResponse;
                    centStartAuth_Dict = jss.Deserialize<Dictionary<string, dynamic>>(centStartAuth_redirect.returnedResponse);
                }
                else
                {
                    //Store First Result in session
                    Session["StartAuth"] = centStartAuth.returnedResponse;
                }

                //Store Centrify session information in site session
                Session["TenantId"] = centStartAuth_Dict["Result"]["TenantId"];
                Session["SessionId"] = centStartAuth_Dict["Result"]["SessionId"];

                ArrayList centStartAuth_Challenges = centStartAuth_Dict["Result"]["Challenges"];

                SetDropDowns(centStartAuth_Dict, Next);

                if (AuthMethod.Visible && AuthMethod.SelectedItem.Text == "Password")
                {
                    Password.Visible = true;
                    Password_Label.Visible = true;
                }
                else if (AuthMethod_Second.Visible && AuthMethod_Second.SelectedItem.Text == "Password")
                {
                    Password.Visible = true;
                    Password_Label.Visible = true;
                }
            }
            else
            {
                FailureText.Text = centStartAuth_Dict["Message"].ToString();
                ErrorMessage.Visible = true;
            }
        }