public IHttpActionResult Post([FromBody] UserLogin_Web user)
        {
            IOrganizationService service = (IOrganizationService)
                                           client.OrganizationWebProxyClient != null ? (IOrganizationService)client.OrganizationWebProxyClient : (IOrganizationService)client.OrganizationServiceProxy;

            QueryExpression query = new QueryExpression();

            query.EntityName = "revfinal_mortgage";
            query.ColumnSet  = new ColumnSet(new string[] { "revfinal_contact" });
            query.Criteria.AddCondition("revfinal_mortgagenumber", ConditionOperator.Equal, user.MortgageNumber);
            Entity mortgage = service.RetrieveMultiple(query).Entities.FirstOrDefault();

            UserLogin login = new UserLogin
            {
                UserName = user.UserName,
                Password = user.Password,
                GUID     = mortgage.GetAttributeValue <EntityReference>("revfinal_contact").Id.ToString()
            };

            try
            {
                UserLoginDB db = new UserLoginDB();

                db.UserLogins.Add(login);
                db.SaveChanges();
                return(Ok("Success"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
    protected void GrdUserLogin_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            DropDownList ddlParent = (DropDownList)GrdUserLogin.FooterRow.FindControl("ddlNewParent");
            TextBox      txtTitle  = (TextBox)GrdUserLogin.FooterRow.FindControl("txtNewTitle");

            //UserLogin2DB.Insert(txtTitle.Text, Convert.ToInt32(ddlParent.SelectedValue));

            FillGrid();
        }

        if (e.CommandName.Equals("_LogOff"))
        {
            int user_login_id = Convert.ToInt32(e.CommandArgument);

            try
            {
                UserLoginDB.UpdateLoggedOffByUserLoginID(user_login_id);
            }
            catch (ForeignKeyConstraintException fkcEx)
            {
                if (Utilities.IsDev())
                {
                    SetErrorMessage("Can not delete because other records depend on this : " + fkcEx.Message);
                }
                else
                {
                    SetErrorMessage("Can not delete because other records depend on this");
                }
            }

            FillGrid();
        }
    }
Пример #3
0
    protected void UpdateLogout(bool hideHeader)
    {
        bool isLoggedIn    = Session["IsLoggedIn"] != null && Convert.ToBoolean(Session["IsLoggedIn"]);
        bool isStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
        bool isMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);
        bool isAdmin       = Session["IsAdmin"] != null && Convert.ToBoolean(Session["IsAdmin"]);
        bool isPrincipal   = Session["IsPrincipal"] != null && Convert.ToBoolean(Session["IsPrincipal"]);

        bool isAdminView = isStakeholder || isMasterAdmin || isAdmin;


        if (!isLoggedIn)
        {
            Logout(hideHeader);
            return;
        }

        // if another session logged in - logout here
        if (!(new List <int> {
            -5, -7, -8
        }).Contains((int)Session["StaffID"]))
        {
            UserLogin userlogin = (Session["PatientID"] == null) ?
                                  UserLoginDB.GetByUserID(Convert.ToInt32(Session["StaffID"]), -1) :
                                  UserLoginDB.GetByUserID(-1, Convert.ToInt32(Session["StaffID"]));

            if (userlogin == null || userlogin.SessionID != HttpContext.Current.Session.SessionID.ToString())
            {
                Logout(hideHeader);
                return;
            }

            if (Session["SiteID"] == null &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LoginV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LogoutV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectSiteV2.aspx"))
            {
                Response.Redirect("~/Account/SelectSiteV2.aspx?from_url=" + Request.RawUrl);
            }


            if (!isAdminView && Session["OrgID"] == null &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/Login.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/Logout.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectOrg.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectSite.aspx"))
            {
                Response.Redirect("~/Account/SelectOrgV2.aspx?from_url=" + Request.RawUrl);
            }

            if (!(new List <int> {
                -5, -7, -8
            }).Contains((int)Session["StaffID"]))
            {
                UserLoginDB.UpdateLastAccessTime(userlogin.UserloginID, DateTime.Now, Request.RawUrl.Contains("/Account/Logout.aspx") ? "" : Request.RawUrl);
            }
        }
    }
Пример #4
0
    protected void LogoutAll()
    {
        try {
            if (Session != null && Session["StaffID"] != null && Session["DB"] != null)
            {
                UserLoginDB.UpdateLoggedOffByStaffID(Convert.ToInt32(Session["StaffID"]));
            }
        } catch (Exception) {}

        Utilities.UnsetSessionVariables();
        Utilities.LogoutV2(Session, Response, Request, false);
    }
Пример #5
0
    protected void UpdateLogout(bool hideHeader)
    {
        UserView userView = UserView.GetInstance();

        if (!userView.IsLoggedIn)
        {
            Logout(hideHeader);
            return;
        }

        // if another session logged in - logout here
        if (Session["StaffID"] == null || !(new List <int> {
            -5, -7, -8
        }).Contains((int)Session["StaffID"]))
        {
            UserLogin userlogin = null;
            if (HttpContext.Current.Session != null && HttpContext.Current.Session["DB"] != null)
            {
                userlogin = !userView.IsPatient ?
                            UserLoginDB.GetByUserID(Convert.ToInt32(Session["StaffID"]), -1) :
                            UserLoginDB.GetByUserID(-1, Convert.ToInt32(Session["PatientID"]));
            }

            if (userlogin == null || userlogin.SessionID != HttpContext.Current.Session.SessionID.ToString())
            {
                Logout(hideHeader);
                return;
            }

            if (Session["SiteID"] == null &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LoginV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LogoutV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectSiteV2.aspx"))
            {
                Response.Redirect("~/Account/SelectSiteV2.aspx?from_url=" + Request.RawUrl);
            }


            if (!userView.IsAdminView && Session["OrgID"] == null &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LoginV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/LogoutV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectOrgV2.aspx") &&
                !HttpContext.Current.Request.Url.LocalPath.Contains("/Account/SelectSiteV2.aspx"))
            {
                Response.Redirect("~/Account/SelectOrgV2.aspx?from_url=" + Request.RawUrl);
            }

            UserLoginDB.UpdateLastAccessTime(userlogin.UserloginID, DateTime.Now, Request.RawUrl.Contains("/Account/Logout.aspx") ? "" : Request.RawUrl);
        }
    }
    protected void btnToggleSiteRestriction_Click(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "TurnOff" || e.CommandName == "TurnOn")
        {
            int  siteID         = Convert.ToInt32(e.CommandArgument);
            int  staffID        = GetFormID();
            bool setRestriction = e.CommandName == "TurnOff";

            StaffSiteRestrictionDB.Update(staffID, siteID, setRestriction);

            // log them out so to make this have an immeidate effect
            if (setRestriction)
            {
                UserLoginDB.UpdateSetAllSessionsLoggedOut(staffID, -1);
            }

            UpdateSiteRestrictions();
        }
    }
Пример #7
0
        private void UserLogin(object sender, Exchange e)
        {
            MySqlDataReader reader;

            try
            {
                var email    = e.Request[0];
                var password = e.Request[1];

                UserLoginDB.Parameters[0].Value = email;
                UserLoginDB.Parameters[1].Value = password;

                Connection.Open();

                using (reader = UserLoginDB.ExecuteReader( ))
                {
                    reader.Read();

                    var token = reader[0].ToString();

                    XElement reply;

                    if (token == "")
                    {
                        reply = new XElement(ReplyFailure);

                        reply.Element("content").Add(new XElement("tryagain"));
                    }
                    else
                    {
                        reply = new XElement(ReplySuccess);

                        reply.Element("content").Add(new XElement("userloggedin"
                                                                  , new XElement("token", new XText(token))));
                    }

                    e.Reply = reply.ToString();
                }
            }
            catch   { Invalid(sender, e); }
            finally { Connection.Close(); }
        }
    protected void Select(int siteID)
    {
        Site site = SiteDB.GetByID(siteID);

        Session["SiteID"]         = site.SiteID;
        Session["SiteName"]       = site.Name;
        Session["SiteIsClinic"]   = site.SiteType.ID == 1;
        Session["SiteIsAgedCare"] = site.SiteType.ID == 2;
        Session["SiteIsGP"]       = site.SiteType.ID == 3;
        Session["SiteTypeID"]     = site.SiteType.ID;
        Session["SiteTypeDescr"]  = site.SiteType.Descr;


        if (Session["PatientID"] == null)
        {
            UserLoginDB.UpdateSite(Convert.ToInt32(Session["StaffID"]), -1, siteID);
        }
        else
        {
            UserLoginDB.UpdateSite(-1, Convert.ToInt32(Session["PatientID"]), siteID);
        }


        if (!Convert.ToBoolean(Session["IsAdmin"]) && Session["OrgID"] == null)  // need to choose org
        {
            Response.Redirect("~/Account/SelectOrgV2.aspx" + (Request.QueryString["from_url"] == null ? "" : "?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url="))), false);
            return;
        }
        else
        {
            if (Request.QueryString["from_url"] != null)
            {
                Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                return;
            }
            else
            {
                Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                return;
            }
        }
    }
Пример #9
0
        public IHttpActionResult Get(string id)
        {
            UserLoginDB db = new UserLoginDB();

            try
            {
                var data = (from a in db.UserLogins where a.UserName.Equals(id) select a).FirstOrDefault();

                if (data != null)
                {
                    return(BadRequest("Contact Exist!"));
                }
                else
                {
                    return(Ok("Success"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
    protected void GrdUserLogin_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblId = (Label)GrdUserLogin.Rows[e.RowIndex].FindControl("lblId");

        try
        {
            UserLoginDB.Delete(Convert.ToInt32(lblId.Text));
        }
        catch (ForeignKeyConstraintException fkcEx)
        {
            if (Utilities.IsDev())
            {
                SetErrorMessage("Can not delete because other records depend on this : " + fkcEx.Message);
            }
            else
            {
                SetErrorMessage("Can not delete because other records depend on this");
            }
        }

        FillGrid();
    }
Пример #11
0
        public IHttpActionResult Post([FromBody] UserLogin login)
        {
            UserLoginDB db = new UserLoginDB();

            UserLogin userLogin = (from a in db.UserLogins where a.UserName.Equals(login.UserName) select a).FirstOrDefault();


            if (userLogin != null)
            {
                if (userLogin.Password.Equals(login.Password))
                {
                    return(Ok(userLogin.GUID));
                }
                else
                {
                    return(BadRequest("Invalid Username or Password"));
                }
            }
            else
            {
                return(BadRequest("Invalid Username or Password"));
            }
        }
Пример #12
0
    protected void DisplayInfo()
    {
        string curDbName = Session["DB"].ToString();

        ddlDBs.Items.Clear();
        ddlDBs.Items.Add(new ListItem("All Clients", "0"));

        ddlDBs2.Items.Clear();
        ddlDBs2.Items.Add(new ListItem("All Clients", "0"));

        ArrayList dbNames = new ArrayList();
        Hashtable dbHash  = new Hashtable();

        try
        {
            bool isSupportStaff3 = Session != null && Session["StaffID"] != null && Convert.ToInt32(Session["StaffID"]) == -4;

            List <Tuple <string, string> > list = new List <Tuple <string, string> >();


            System.Data.DataTable tbl = DBBase.ExecuteQuery("EXEC sp_databases;", "master").Tables[0];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                string databaseName = tbl.Rows[i][0].ToString();

                if (!Regex.IsMatch(databaseName, @"Mediclinic_\d{4}"))
                {
                    continue;
                }
                //if (databaseName == "Mediclinic_0001")
                //    continue;


                SystemVariables sysVariables = SystemVariableDB.GetAll(databaseName);

                dbNames.Add(sysVariables["Site"].Value);
                dbHash[sysVariables["Site"].Value] = databaseName;


                System.Text.StringBuilder output = new System.Text.StringBuilder();

                Session["DB"] = databaseName;
                Session["SystemVariables"] = SystemVariableDB.GetAll();

                string callCenterPrefix = ((SystemVariables)Session["SystemVariables"])["CallCenterPrefix"].Value;

                int loginsPastWeek_Total = UserLoginDB.GetCount(7);
                int loginsPastWeek_Staff = UserLoginDB.GetStaffCount(7);


                if (((SystemVariables)Session["SystemVariables"])["UseMediclinicCallCenter"].Value == "1")
                {
                    Organisation[] orgs = OrganisationDB.GetAll(false, true, false, false, true, true);


                    Site[] sites          = SiteDB.GetAll();
                    int    clinicSiteID   = -1;
                    int    agedCareSiteID = -1;
                    for (int j = 0; j < sites.Length; j++)
                    {
                        if (sites[j].SiteType.ID == 1)
                        {
                            clinicSiteID = sites[j].SiteID;
                        }
                        if (sites[j].SiteType.ID == 2)
                        {
                            agedCareSiteID = sites[j].SiteID;
                        }
                    }


                    string showHideID1   = "heading_" + databaseName;
                    string showHideLink1 = @"<a href=""javascript:void(0)"" onclick=""hide_show_all('" + showHideID1 + @"');return false;"">Show/Hide Clinics/Facs</a>";

                    string siteTitleLink = @"<span style=""display:inline-block;vertical-align:middle;max-width:300px;min-width:300px;overflow:hidden;text-overflow:ellipsis;""><a style=""white-space:nowrap;"" class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    //string siteTitleLink      = @"<span style=""display:inline-block;min-width:250px;""><a class=""call_centre_header"" title=""" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @""" href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @""" onclick=""http_post('" + databaseName + @"','0','0',-1);return false;"">" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + @"</a></span>";
                    string callCentrePrefixText = @"<span style=""display:inline-block;min-width:160px;"">[Call Center Prefix: " + callCenterPrefix + "]</span>";

                    output.AppendLine("<tr>");
                    //output.AppendLine("    <td><u>" + ((SystemVariables)Session["SystemVariables"])["Site"].Value + "</u> &nbsp;&nbsp; [Call Center Prefix: " + callCenterPrefix + "] &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("    <td>" + showHideLink1 + " &nbsp;&nbsp; " + (isSupportStaff3 ? @"<span style=""display:inline-block;min-width:55px;"">" + (loginsPastWeek_Staff == 0 && loginsPastWeek_Total == 0 ? "" : "[" + loginsPastWeek_Staff + "," + loginsPastWeek_Total + "]") + "</span>" + " &nbsp;&nbsp; " : "") + siteTitleLink + " &nbsp;&nbsp; " + callCentrePrefixText + " &nbsp;&nbsp; [" + Session["DB"] + "]</td>");
                    output.AppendLine("</tr>");

                    if (orgs.Length > 0)
                    {
                        for (int j = 0; j < orgs.Length; j++)
                        {
                            string showHideID  = databaseName + "_" + orgs[j].OrganisationID;
                            string contactInfo = GetContactInfo(orgs[j].EntityID, 60, showHideID);

                            string titleLink    = @"<a href=""" + HttpContext.Current.Request.Url.AbsolutePath + "?db=" + databaseName + @"&org=" + orgs[j].OrganisationID + @""" onclick=""http_post('" + databaseName + "','" + orgs[j].OrganisationID + @"','" + (orgs[j].IsClinic ? clinicSiteID : agedCareSiteID) + @"',-1);return false;"">" + orgs[j].Name + " " + (orgs[j].IsClinic ? @"(Clinic)" : "(Aged Care)") + @"</a>";
                            string showHideLink = @"<a href=""javascript:void(0)"" onclick=""hide_show('" + showHideID + @"');return false;"">Show/Hide Details</a>";


                            output.AppendLine(@"<tr id=""" + showHideID1 + j.ToString() + @""" style=""margin:0 0;display:none;"">");
                            output.AppendLine(@"    <td style=""margin:0 0;"">");
                            output.AppendLine(@"            <table><tr style=""vertical-align:top;""><td style=""width:500px;""><ul style=""margin:0 0;""><li>" + titleLink + @"</li></ul></td><td style=""min-width:10px;""></td><td>" + (contactInfo.Length > 0 ? showHideLink : "") + "</td></tr></table>");

                            if (contactInfo.Length > 0)
                            {
                                output.AppendLine(contactInfo);
                            }

                            output.AppendLine(@"    </td>");
                            output.AppendLine(@"</tr>");
                        }
                    }
                }

                list.Add(new Tuple <string, string>(((SystemVariables)Session["SystemVariables"])["Site"].Value, output.ToString()));

                Session.Remove("DB");
                Session.Remove("SystemVariables");
            }


            dbNames.Sort();
            foreach (string siteName in dbNames)
            {
                ddlDBs.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
                ddlDBs2.Items.Add(new ListItem("[" + dbHash[siteName] + "] " + siteName, dbHash[siteName].ToString()));
            }


            list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, string> item in list)
            {
                finalOutput.Append(item.Item2);
            }

            lblInfo1.Text = "<table>" + finalOutput.ToString() + "</table>";
        }
        finally
        {
            Session["DB"] = curDbName;
            Session["SystemVariables"] = SystemVariableDB.GetAll();
        }
    }
Пример #13
0
    private void LogIn(string login, string pwd)
    {
        try
        {
            Session.Remove("DB");
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
            {
                Session["DB"] = ConfigurationManager.AppSettings["Database"];
            }
            else // Get DB from Mediclinic_Main
            {
                UserDatabaseMapper user = UserDatabaseMapperDB.GetByLogin(login);
                if (user == null)
                {
                    this.FailureText.Text = "<div class=\"alert alert-danger\" runat=\"server\"><strong>Login Failed.</strong> Please ensure that your username and password are correct and try again.</div>";
                    return;
                }

                Session["DB"] = user.DBName;
            }



            Staff   staff              = StaffDB.GetByLogin(login);
            Patient patient            = PatientDB.GetByLogin(login);
            bool    allowPatientLogins = Convert.ToInt32(SystemVariableDB.GetByDescr("AllowPatientLogins").Value) == 1;
            bool    validStaff         = staff != null && staff.Pwd == pwd && !staff.IsFired;
            bool    validPatient       = allowPatientLogins && patient != null && patient.Pwd == pwd && !patient.IsDeleted;

            if (validStaff)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(staff.StaffID, -1, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, staff.StaffID, -1);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(staff.StaffID, -1);
                    UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, -1, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                Session["IsLoggedIn"]    = true;
                Session["IsStakeholder"] = staff.IsStakeholder;
                Session["IsMasterAdmin"] = staff.IsMasterAdmin;
                Session["IsAdmin"]       = staff.IsAdmin;
                Session["IsPrincipal"]   = staff.IsPrincipal;
                Session["IsProvider"]    = staff.IsProvider;
                Session["IsExternal"]    = staff.IsExternal;
                Session["StaffID"]       = staff.StaffID;
                Session["StaffFullnameWithoutMiddlename"] = staff.Person.FullnameWithoutMiddlename;
                Session["StaffFirstname"] = staff.Person.Firstname;
                Session["NumDaysToDisplayOnBookingScreen"] = staff.NumDaysToDisplayOnBookingScreen;
                Session["HideBookingNotes"] = staff.HideBookingNotes;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = staff.ShowHeaderOnBookingScreen;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                UserView userView = UserView.GetInstance();

                Site[] allowedSites = StaffSiteRestrictionDB.GetSitesNotRestricted(staff.StaffID, -1, false);


                //
                // until aged care is running, remove aged care from display
                //

                /*
                 * System.Collections.ArrayList list = new System.Collections.ArrayList();
                 * for (int i = 0; i < allowedSites.Length; i++)
                 *  if (allowedSites[i].SiteType.ID == 1 || Utilities.IsDev())
                 *      list.Add(allowedSites[i]);
                 * allowedSites = (Site[])list.ToArray(typeof(Site));
                 */

                Site[] allSites = SiteDB.GetAll();
                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]          = allSites[0].SiteID;
                    Session["SiteName"]        = allSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }



                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]          = allowedSites[0].SiteID;
                    Session["SiteName"]        = allowedSites[0].Name;
                    Session["IsMultipleSites"] = false;
                    Session["SiteIsClinic"]    = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"]  = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]        = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]      = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]   = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(staff.StaffID, -1, allowedSites[0].SiteID);

                    if (!userView.IsAdminView)        // need to choose org
                    {
                        if (Session["OrgID"] == null) // providers need to select an org, need to choose one
                        {
                            Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                            return;
                        }
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Session["IsMultipleSites"] = true;
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }



                /*
                 *
                 * if (!staff.IsAdmin)
                 * {
                 *  // provs only login to clinic site
                 *  Site site = SiteDB.GetByID(2);
                 *  Session["SiteID"]   = site.SiteID;
                 *  Session["SiteName"] = site.Name;
                 *
                 *  if (Session["OrgID"] == null)  // providers et to login to select an org, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectOrgV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 * else
                 * {
                 *  if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                 *  {
                 *      if (Request.QueryString["from_url"] != null)
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx?" + Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=")), false);
                 *          return;
                 *      }
                 *      else
                 *      {
                 *          Response.Redirect("~/Account/SelectSiteV2.aspx", false);
                 *          return;
                 *      }
                 *  }
                 * }
                 *
                 */

                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }
            else if (validPatient)
            {
                UserLogin curLogin = UserLoginDB.GetCurLoggedIn(-1, patient.PatientID, HttpContext.Current.Session.SessionID, -1);
                if (curLogin != null)
                {
                    UserLoginDB.UpdateLastAccessTime(curLogin.UserloginID, DateTime.Now, Request.RawUrl);
                    UserLoginDB.UpdateSetOtherSessionsOfThisUserLoggedOut(curLogin.UserloginID, -1, patient.PatientID);
                }
                else
                {
                    UserLoginDB.UpdateSetAllSessionsLoggedOut(-1, patient.PatientID);
                    UserLoginDB.Insert(-1, (patient == null) ? -1 : patient.PatientID, login, -1, validPatient, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                }


                this.FailureText.Text = "";

                Session["IsLoggedIn"]    = true;
                Session["IsStakeholder"] = false;
                Session["IsMasterAdmin"] = false;
                Session["IsAdmin"]       = false;
                Session["IsPrincipal"]   = false;
                Session["IsProvider"]    = false;
                Session["IsExternal"]    = false;
                Session["PatientID"]     = patient.PatientID;
                Session["StaffFullnameWithoutMiddlename"] = patient.Person.FullnameWithoutMiddlename;
                Session["StaffFirstname"] = patient.Person.Firstname;
                Session["NumDaysToDisplayOnBookingScreen"]   = 3;
                Session["ShowOtherProvidersOnBookingScreen"] = false;
                Session["ShowHeaderOnBookingScreen"]         = true;
                Session["SystemVariables"] = SystemVariableDB.GetAll();
                Session["OfferingColors"]  = OfferingDB.GetColorCodes();
                System.Web.Security.FormsAuthentication.SetAuthCookie("--", true);  // needed to use forms authentication


                Site[] allSites     = SiteDB.GetAll();
                Site[] allowedSites = SiteDB.GetAll();


                //
                // remove aged care from display
                //
                System.Collections.ArrayList list = new System.Collections.ArrayList();
                for (int i = 0; i < allSites.Length; i++)
                {
                    if (allSites[i].SiteType.ID == 1)
                    {
                        list.Add(allSites[i]);
                    }
                }
                allowedSites = (Site[])list.ToArray(typeof(Site));

                if (allowedSites.Length == 0 && allSites.Length == 1)
                {
                    Session["SiteID"]         = allSites[0].SiteID;
                    Session["SiteName"]       = allSites[0].Name;
                    Session["SiteIsClinic"]   = allSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allSites[0].SiteType.Descr;


                    UserLoginDB.UpdateSite(-1, patient.PatientID, allSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers, ext staff, patient logins need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }


                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }

                if (allowedSites.Length == 1)
                {
                    Session["SiteID"]         = allowedSites[0].SiteID;
                    Session["SiteName"]       = allowedSites[0].Name;
                    Session["SiteIsClinic"]   = allowedSites[0].SiteType.ID == 1;
                    Session["SiteIsAgedCare"] = allowedSites[0].SiteType.ID == 2;
                    Session["SiteIsGP"]       = allowedSites[0].SiteType.ID == 3;
                    Session["SiteTypeID"]     = allowedSites[0].SiteType.ID;
                    Session["SiteTypeDescr"]  = allowedSites[0].SiteType.Descr;

                    UserLoginDB.UpdateSite(-1, patient.PatientID, allowedSites[0].SiteID);

                    if (Session["OrgID"] == null)  // providers need to select an org, need to choose one
                    {
                        if (Request.QueryString["from_url"] != null)
                        {
                            string from_url = Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9));
                            if (from_url.Contains("BookingsV2.aspx?") && from_url.Contains("orgs="))
                            {
                                Uri    theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + from_url);
                                string orgs       = HttpUtility.ParseQueryString(theRealURL.Query).Get("orgs");
                                if (Regex.IsMatch(orgs, @"^\d+$"))
                                {
                                    Organisation org = OrganisationDB.GetByID(Convert.ToInt32(orgs));
                                    if (org != null)
                                    {
                                        Session["OrgID"]   = org.OrganisationID.ToString();
                                        Session["OrgName"] = org.Name;
                                        Response.Redirect(from_url, false);
                                        return;
                                    }
                                }
                            }
                        }

                        Response.Redirect("~/Account/SelectOrgV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }
                else // if more than one site, go to choose. if no sites this page will say to contact admin
                {
                    if (Session["SiteID"] == null)  // admins if yet to login to a site, need to choose one
                    {
                        Response.Redirect("~/Account/SelectSiteV2.aspx" + GetUrlCarryOverParams(), false);
                        return;
                    }
                }


                if (Request.QueryString["from_url"] != null)
                {
                    Response.Redirect(Server.UrlDecode(Request.RawUrl.Substring(Request.RawUrl.IndexOf("from_url=") + 9)), false);
                    return;
                }
                else
                {
                    Response.Redirect(Convert.ToInt32(Session["StaffID"]) >= 0 ? "~/Default.aspx" : "~/StaffLoginsV2.aspx", false);
                    return;
                }
            }

            else
            {
                //UserLoginDB.Insert((staff == null) ? -1 : staff.StaffID, login, -1, validStaff, HttpContext.Current.Session.SessionID, Request.UserHostAddress);
                this.FailureText.Text = "Login Failed.";
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            if (Utilities.IsDev())
            {
                FailureText.Text = ex.ToString();
            }
            else
            {
                throw;
            }
        }
    }
    protected void FillGrid()
    {
        if (GetFormIncStaffLogins() && GetFormIncPatientLogins())
        {
            ddlDisplayUserType.SelectedValue = "All";
        }
        else if (!GetFormIncStaffLogins() && GetFormIncPatientLogins())
        {
            ddlDisplayUserType.SelectedValue = "Patients Only";
        }
        else if (GetFormIncStaffLogins() && !GetFormIncPatientLogins())
        {
            ddlDisplayUserType.SelectedValue = "Staff Only";
        }


        DateTime fromDate = IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text) : DateTime.Now.Date.AddDays(-7);
        DateTime toDate   = IsValidDate(txtEndDate.Text) ? GetDate(txtEndDate.Text).AddDays(1) : DateTime.Now.Date.AddDays(1);

        UserView userView = UserView.GetInstance();

        int       numCurrentlyLoggedIn  = 0;
        Hashtable distinctLoggedInToday = new Hashtable();
        DataTable dt = UserLoginDB.GetDataTable(userView.IsStakeholder, fromDate, toDate, GetFormIncStaffLogins(), GetFormIncPatientLogins(), IsValidFormStaffID() ? GetFormStaffID() : -1);

        dt.Columns.Add("user_to_display", typeof(string));
        dt.Columns.Add("user_type", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            UserLogin userLogin = UserLoginDB.LoadAll(dt.Rows[i]);

            if (userLogin.Staff == null && userLogin.Patient == null)
            {
                dt.Rows[i]["user_to_display"] = userLogin.Username;
                dt.Rows[i]["user_type"]       = "";
            }
            else if (userLogin.Staff != null)
            {
                dt.Rows[i]["user_to_display"] = userLogin.Staff.Person.FullnameWithoutMiddlename;
                dt.Rows[i]["user_type"]       = "Staff";
            }
            else if (userLogin.Patient != null)
            {
                dt.Rows[i]["user_to_display"] = userLogin.Patient.Person.FullnameWithoutMiddlename;
                dt.Rows[i]["user_type"]       = "Patient";
            }



            if (userLogin.Staff != null && userLogin.Staff.StaffID > 0 && !userLogin.IsLoggedOff)
            {
                numCurrentlyLoggedIn++;
            }
            if (userLogin.Staff != null && userLogin.Staff.StaffID > 0 && userLogin.LastAccessTime >= DateTime.Today)
            {
                distinctLoggedInToday[userLogin.Staff.StaffID] = 1;
            }
        }

        Session["userlogin_data"] = dt;

        lblNumCurrentlyLoggedIn.Text = "(current: " + numCurrentlyLoggedIn + ")  " + "<font color=\"#A0A0A0\">(distinct today: " + distinctLoggedInToday.Keys.Count + ") </font>";


        if (!userView.IsStakeholder)
        {
            img_log_user_off_icon.Visible = false;
            foreach (DataControlField col in GrdUserLogin.Columns)
            {
                if (col.HeaderText.ToLower().Trim() == "log off")
                {
                    col.Visible = false;
                }
            }
        }


        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["userlogin_sortexpression"] != null && Session["userlogin_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort           = Session["userlogin_sortexpression"].ToString();
                GrdUserLogin.DataSource = dataView;
            }
            else
            {
                GrdUserLogin.DataSource = dt;
            }


            try
            {
                GrdUserLogin.DataBind();
                GrdUserLogin.PagerSettings.FirstPageText = "1";
                GrdUserLogin.PagerSettings.LastPageText  = GrdUserLogin.PageCount.ToString();
                GrdUserLogin.DataBind();

                FillCountries();
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdUserLogin.DataSource = dt;
            GrdUserLogin.DataBind();

            int TotalColumns = GrdUserLogin.Rows[0].Cells.Count;
            GrdUserLogin.Rows[0].Cells.Clear();
            GrdUserLogin.Rows[0].Cells.Add(new TableCell());
            GrdUserLogin.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdUserLogin.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                Utilities.SetNoCache(Response);
            }
            HideErrorMessage();

            if (!IsPostBack)
            {
                PagePermissions.EnforcePermissions_RequireAll(Session, Response, false, false, true, false, false, true);
                Session.Remove("userlogin_sortexpression");
                Session.Remove("userlogin_data");


                // only allow support staff3 to do this
                string s  = Session["StaffID"].ToString();
                string s2 = Request.QueryString["del"];
                if (Session["StaffID"].ToString() == "-4" && Request.QueryString["del"] != null && Regex.IsMatch(Request.QueryString["del"], @"^\-?\d+$"))
                {
                    UserLoginDB.DeleteByStaffID(Convert.ToInt32(Request.QueryString["del"]));
                    Response.Redirect(UrlParamModifier.Remove(Request.RawUrl, "del"));  // redirect so that my 'last page accessed' should not show this
                }


                txtStartDate.Text = IsValidFormStartDate() ? GetFormStartDate(false).ToString("dd-MM-yyyy") : DateTime.Now.AddMonths(-1).ToString("dd-MM-yyyy");
                txtEndDate.Text   = IsValidFormEndDate() ? GetFormEndDate(false).ToString("dd-MM-yyyy") : DateTime.Now.ToString("dd-MM-yyyy");

                FillGrid();

                txtStartDate_Picker.OnClientClick = "displayDatePicker('txtStartDate', this, 'dmy', '-'); return false;";
                txtEndDate_Picker.OnClientClick   = "displayDatePicker('txtEndDate', this, 'dmy', '-'); return false;";
            }

            this.GrdUserLogin.EnableViewState = true;
        }
        catch (CustomMessageException ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage(ex.Message);
            }
            else
            {
                HideTableAndSetErrorMessage(ex.Message);
            }
        }
        catch (Exception ex)
        {
            if (IsPostBack)
            {
                SetErrorMessage("", ex.ToString());
            }
            else
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
    }
 public async Task RemoveLoginAsync(string userId, UserLoginDB login)
 {
     var userLoginInfo = new UserLoginInfo(login.LoginProvider, login.ProviderKey);
     await _manager.RemoveLoginAsync(userId, userLoginInfo).ConfigureAwait(false);
 }