protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!ddlEndDateValidateAllOrNoneSet.IsValid ||
            !ddlStartDateValidateAllOrNoneSet.IsValid)
        {
            return;
        }

        txtPwd.Attributes["value"] = txtPwd.Text;  // pwd fields is unset on send back to server, so re-set it

        if (GetUrlParamType() == UrlParamType.View)
        {
            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "edit"));
        }
        else if (GetUrlParamType() == UrlParamType.Edit)
        {
            Staff staff = StaffDB.GetByID(Convert.ToInt32(this.lblId.Text));

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text, staff.StaffID))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (staff.Pwd != txtPwd.Text && txtPwd.Text.Length < 6)
            {
                SetErrorMessage(staff.Pwd.Length >= 6 ? "Password must be at least 6 characters" : "New passwords must be at least 6 characters");
                return;
            }

            bool loggedInUserIsStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
            bool loggedInUserIsMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);


            PersonDB.Update(staff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), staff.Person.Nickname, ddlGender.SelectedValue, staff.Person.Dob, DateTime.Now);
            StaffDB.Update(staff.StaffID, staff.Person.PersonID, txtLogin.Text, txtPwd.Text, staff.StaffPosition.StaffPositionID, staff.Field.ID, staff.CostCentre.CostCentreID,
                           staff.IsContractor, staff.Tfn, staff.ProviderNumber,
                           ddlStatus.SelectedValue == "Inactive", staff.IsCommission, staff.CommissionPercent,
                           staff.IsStakeholder, staff.IsMasterAdmin, staff.IsAdmin, staff.IsPrincipal, staff.IsProvider, staff.IsExternal,
                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, staff.EnableDailyReminderSMS, staff.EnableDailyReminderEmail, staff.HideBookingNotes);

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text)
            {
                UserDatabaseMapper curDBMapper = UserDatabaseMapperDB.GetByLogin(staff.Login, Session["DB"].ToString());
                UserDatabaseMapperDB.Update(curDBMapper.ID, txtLogin.Text, Session["DB"].ToString());
            }

            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view"));
        }
        else if (GetUrlParamType() == UrlParamType.Add)
        {
            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            int  person_id    = -1;
            int  staff_id     = -1;
            bool staff_added  = false;
            int  mainDbUserID = -1;

            try
            {
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, DateTime.MinValue);
                staff_id  = StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, 0, 59,
                                           false, "", "",
                                           ddlStatus.SelectedValue == "Inactive", false, 0,
                                           false, false, false, false, false, true,
                                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, false, false, false);
                staff_added = true;

                string url = Request.RawUrl;
                url = UrlParamModifier.AddEdit(url, "type", "view");
                url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                Response.Redirect(url);
            }
            catch (Exception)
            {
                if (staff_added)
                {
                    string url = Request.RawUrl;
                    url = UrlParamModifier.AddEdit(url, "type", "view");
                    url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                    Response.Redirect(url);
                    return;
                }

                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }

                throw;
            }
        }
        else
        {
            HideTableAndSetErrorMessage();
        }
    }
예제 #2
0
    protected void GrdStaff_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            CustomValidator txtValidateDOB = (CustomValidator)GrdStaff.FooterRow.FindControl("txtValidateNewDOB");
            if (!txtValidateDOB.IsValid)
            {
                return;
            }

            DropDownList ddlTitle      = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewTitle");
            TextBox      txtFirstname  = (TextBox)GrdStaff.FooterRow.FindControl("txtNewFirstname");
            TextBox      txtMiddlename = (TextBox)GrdStaff.FooterRow.FindControl("txtNewMiddlename");
            TextBox      txtSurname    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewSurname");
            DropDownList ddlGender     = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewGender");
            TextBox      txtDOB        = (TextBox)GrdStaff.FooterRow.FindControl("txtNewDOB");

            TextBox txtLogin = (TextBox)GrdStaff.FooterRow.FindControl("txtNewLogin");
            TextBox txtPwd   = (TextBox)GrdStaff.FooterRow.FindControl("txtNewPwd");


            //DropDownList ddlStaffPosition     = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewStaffPosition");
            DropDownList ddlField             = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewField");
            CheckBox     chkContractor        = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewContractor");
            TextBox      txtTFN               = (TextBox)GrdStaff.FooterRow.FindControl("txtNewTFN");
            DropDownList ddlStatus            = (DropDownList)GrdStaff.FooterRow.FindControl("ddlStatus");
            DropDownList ddlCostCentre        = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewCostCentre");
            TextBox      txtProviderNumber    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewProviderNumber");
            CheckBox     chkIsCommission      = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsCommission");
            TextBox      txtCommissionPercent = (TextBox)GrdStaff.FooterRow.FindControl("txtNewCommissionPercent");

            CheckBox chkIsStakeholder = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsStakeholder");
            CheckBox chkIsAdmin       = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsAdmin");
            CheckBox chkIsMasterAdmin = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsMasterAdmin");
            CheckBox chkIsPrincipal   = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsPrincipal");
            CheckBox chkIsProvider    = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewIsProvider");
            CheckBox chkSMSBKs        = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewSMSBKs");
            CheckBox chkEmailBKs      = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewEmailBKs");
            CheckBox chkHideBKNotes   = (CheckBox)GrdStaff.FooterRow.FindControl("chkNewHideBKNotes");



            if (chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to add them. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }


            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            DateTime dob = GetDate(txtDOB.Text.Trim());

            int person_id    = -1;
            int mainDbUserID = -1;

            try
            {
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                if (chkIsMasterAdmin.Checked)
                {
                    chkIsAdmin.Checked = true;
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, dob);
                StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), Convert.ToInt32(ddlCostCentre.SelectedValue),
                               chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                               ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                               chkIsStakeholder.Checked, chkIsMasterAdmin.Checked, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, false,
                               DateTime.Today, DateTime.MinValue, "", chkSMSBKs.Checked, chkEmailBKs.Checked, chkHideBKNotes.Checked);

                FillGrid();
            }
            catch (Exception)
            {
                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }
            }
        }
    }
    protected void GrdStaff_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            CustomValidator txtValidateDOB = (CustomValidator)GrdStaff.FooterRow.FindControl("txtValidateNewDOB");
            if (!txtValidateDOB.IsValid)
            {
                return;
            }

            DropDownList ddlTitle      = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewTitle");
            TextBox      txtFirstname  = (TextBox)GrdStaff.FooterRow.FindControl("txtNewFirstname");
            TextBox      txtMiddlename = (TextBox)GrdStaff.FooterRow.FindControl("txtNewMiddlename");
            TextBox      txtSurname    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewSurname");
            DropDownList ddlGender     = (DropDownList)GrdStaff.FooterRow.FindControl("ddlNewGender");

            TextBox      txtLogin  = (TextBox)GrdStaff.FooterRow.FindControl("txtNewLogin");
            TextBox      txtPwd    = (TextBox)GrdStaff.FooterRow.FindControl("txtNewPwd");
            DropDownList ddlStatus = (DropDownList)GrdStaff.FooterRow.FindControl("ddlStatus");


            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            DateTime dob = DateTime.MinValue;

            int person_id    = -1;
            int mainDbUserID = -1;

            try
            {
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, dob);
                StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, 0, 59,
                               false, "", "",
                               ddlStatus.SelectedValue == "Inactive", false, 0,
                               false, false, false, false, false, true,
                               DateTime.Today, DateTime.MinValue, "", false, false);

                FillGrid();
            }
            catch (Exception)
            {
                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }
            }
        }
    }
예제 #4
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!ddlEndDateValidateAllOrNoneSet.IsValid ||
            !ddlStartDateValidateAllOrNoneSet.IsValid ||
            !ddlDOBValidateAllOrNoneSet.IsValid)
        {
            return;
        }

        txtPwd.Attributes["value"] = txtPwd.Text;  // pwd fields is unset on send back to server, so re-set it

        if (GetUrlParamType() == UrlParamType.View)
        {
            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "edit"));
        }
        else if (GetUrlParamType() == UrlParamType.Edit)
        {
            Staff staff = StaffDB.GetByID(Convert.ToInt32(this.lblId.Text));

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text, staff.StaffID))
            {
                SetErrorMessage("Login name already in use by another user");
                return;
            }
            if (staff.Pwd != txtPwd.Text && txtPwd.Text.Length < 6)
            {
                SetErrorMessage(staff.Pwd.Length >= 6 ? "Password must be at least 6 characters" : "New passwords must be at least 6 characters");
                return;
            }

            bool loggedInUserIsStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
            bool loggedInUserIsMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);
            bool setIsStakeholder          = loggedInUserIsStakeholder ? chkIsStakeholder.Checked : staff.IsStakeholder;
            bool setIsMasterAdmin          = loggedInUserIsStakeholder || loggedInUserIsMasterAdmin ? chkIsMasterAdmin.Checked : staff.IsMasterAdmin;

            if (!staff.IsProvider && chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to update them or hit cancel. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }


            if (chkIsProvider.Checked)
            {
                System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

                bool         roleSetAsProvider = false;
                IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                    if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                    {
                        roleSetAsProvider = true;
                    }
                }

                if (!roleSetAsProvider)
                {
                    if (fields.Length == 1)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                        return;
                    }
                    else if (fields.Length == 2)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                        return;
                    }
                    else
                    {
                        string providerFields = string.Empty;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                        }

                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                        return;
                    }
                }
            }



            if (chkIsMasterAdmin.Checked)
            {
                chkIsAdmin.Checked = true;
            }

            PersonDB.Update(staff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), staff.Person.Nickname, ddlGender.SelectedValue, GetDOBFromForm(), DateTime.Now);
            StaffDB.Update(staff.StaffID, staff.Person.PersonID, txtLogin.Text, txtPwd.Text, staff.StaffPosition.StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), staff.CostCentre.CostCentreID,
                           chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                           ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                           setIsStakeholder, setIsMasterAdmin, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, staff.IsExternal,
                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, chkSMSBKs.Checked, chkEmailBKs.Checked);

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text)
            {
                UserDatabaseMapper curDBMapper = UserDatabaseMapperDB.GetByLogin(staff.Login, Session["DB"].ToString());
                if (curDBMapper == null)
                {
                    UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }
                else
                {
                    UserDatabaseMapperDB.Update(curDBMapper.ID, txtLogin.Text, Session["DB"].ToString());
                }
            }

            Response.Redirect(UrlParamModifier.AddEdit(Request.RawUrl, "type", "view"));
        }
        else if (GetUrlParamType() == UrlParamType.Add)
        {
            if (chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
            {
                SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to add them. Contact Mediclinic if you would like to upgrade your account.");
                return;
            }

            if (chkIsProvider.Checked)
            {
                System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

                bool         roleSetAsProvider = false;
                IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                    if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                    {
                        roleSetAsProvider = true;
                    }
                }

                if (!roleSetAsProvider)
                {
                    if (fields.Length == 1)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                        return;
                    }
                    else if (fields.Length == 2)
                    {
                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                        return;
                    }
                    else
                    {
                        string providerFields = string.Empty;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                        }

                        SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                        return;
                    }
                }
            }

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
            {
                lblErrorMessage.Text    = "Login name already in use by another user";
                lblErrorMessage.Visible = true;
                return;
            }
            if (StaffDB.LoginExists(txtLogin.Text))
            {
                lblErrorMessage.Text    = "Login name already in use by another user";
                lblErrorMessage.Visible = true;
                return;
            }
            if (txtPwd.Text.Length < 6)
            {
                SetErrorMessage("Password must be at least 6 characters");
                return;
            }


            int  person_id    = -1;
            int  staff_id     = -1;
            bool staff_added  = false;
            int  mainDbUserID = -1;

            try
            {
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                }

                bool loggedInUserIsStakeholder = Session["IsStakeholder"] != null && Convert.ToBoolean(Session["IsStakeholder"]);
                bool loggedInUserIsMasterAdmin = Session["IsMasterAdmin"] != null && Convert.ToBoolean(Session["IsMasterAdmin"]);
                bool setIsStakeholder          = loggedInUserIsStakeholder ? chkIsStakeholder.Checked : false;
                bool setIsMasterAdmin          = loggedInUserIsStakeholder || loggedInUserIsMasterAdmin ? chkIsMasterAdmin.Checked : false;

                if (chkIsMasterAdmin.Checked)
                {
                    chkIsAdmin.Checked = true;
                }

                Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
                person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, GetDOBFromForm());
                staff_id  = StaffDB.Insert(person_id, txtLogin.Text, txtPwd.Text, StaffPositionDB.GetByDescr("Unknown").StaffPositionID, Convert.ToInt32(ddlField.SelectedValue), 59,
                                           chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                                           ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                                           setIsStakeholder, setIsMasterAdmin, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, false,
                                           GetStartDateFromForm(), GetEndDateFromForm(), txtComments.Text, chkSMSBKs.Checked, chkEmailBKs.Checked);
                staff_added = true;

                string url = Request.RawUrl;
                url = UrlParamModifier.AddEdit(url, "type", "view");
                url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                Response.Redirect(url);
            }
            catch (Exception)
            {
                if (staff_added)
                {
                    string url = Request.RawUrl;
                    url = UrlParamModifier.AddEdit(url, "type", "view");
                    url = UrlParamModifier.AddEdit(url, "id", staff_id.ToString());
                    Response.Redirect(url);
                    return;
                }

                // roll back - backwards of creation order
                PersonDB.Delete(person_id);
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }

                throw;
            }
        }
        else
        {
            HideTableAndSetErrorMessage();
        }
    }
예제 #5
0
    protected void GrdStaff_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId         = (Label)GrdStaff.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlTitle      = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlTitle");
        TextBox      txtFirstname  = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtFirstname");
        TextBox      txtMiddlename = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtMiddlename");
        TextBox      txtSurname    = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtSurname");
        DropDownList ddlGender     = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlGender");
        DropDownList ddlDOB_Day    = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Day");
        DropDownList ddlDOB_Month  = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Month");
        DropDownList ddlDOB_Year   = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlDOB_Year");

        TextBox txtLogin = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtLogin");
        TextBox txtPwd   = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtPwd");
        //DropDownList ddlStaffPosition     = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlStaffPosition");
        DropDownList ddlField             = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlField");
        CheckBox     chkContractor        = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkContractor");
        TextBox      txtTFN               = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtTFN");
        DropDownList ddlStatus            = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlStatus");
        DropDownList ddlCostCentre        = (DropDownList)GrdStaff.Rows[e.RowIndex].FindControl("ddlCostCentre");
        TextBox      txtProviderNumber    = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtProviderNumber");
        CheckBox     chkIsCommission      = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsCommission");
        TextBox      txtCommissionPercent = (TextBox)GrdStaff.Rows[e.RowIndex].FindControl("txtCommissionPercent");
        CheckBox     chkIsStakeholder     = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsStakeholder");
        CheckBox     chkIsAdmin           = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsAdmin");
        CheckBox     chkIsMasterAdmin     = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsMasterAdmin");
        CheckBox     chkIsPrincipal       = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsPrincipal");
        CheckBox     chkIsProvider        = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkIsProvider");
        CheckBox     chkSMSBKs            = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkSMSBKs");
        CheckBox     chkEmailBKs          = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkEmailBKs");
        CheckBox     chkHideBKNotes       = (CheckBox)GrdStaff.Rows[e.RowIndex].FindControl("chkHideBKNotes");



        int staff_id  = Convert.ToInt32(lblId.Text);
        int person_id = GetPersonID(Convert.ToInt32(lblId.Text));

        if (person_id == -1) // happens when back button hit after update .. with option to update again ... but no selected row exists within page data
        {
            GrdStaff.EditIndex = -1;
            FillGrid();
            return;
        }


        Staff staff = StaffDB.GetByID(staff_id);

        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
        {
            SetErrorMessage("Login name already in use by another user");
            return;
        }
        if (staff.Login != txtLogin.Text && StaffDB.LoginExists(txtLogin.Text, staff_id))
        {
            SetErrorMessage("Login name already in use by another user");
            return;
        }
        if (staff.Pwd != txtPwd.Text && txtPwd.Text.Length < 6)
        {
            SetErrorMessage(staff.Pwd.Length >= 6 ? "Password must be at least 6 characters" : "New passwords must be at least 6 characters");
            return;
        }

        DataTable dt = Session["staffinfo_data"] as DataTable;

        DataRow[] foundRows = dt.Select("person_id=" + person_id.ToString());
        DataRow   row       = foundRows[0]; // Convert.ToInt32(row["person_id"])



        if (!Convert.ToBoolean(row["is_provider"]) && chkIsProvider.Checked && (StaffDB.GetCountOfProviders() >= Convert.ToInt32(SystemVariableDB.GetByDescr("MaxNbrProviders").Value)))
        {
            SetErrorMessage("You have reached your maximum allowable providers. Please uncheck their status as a provider to update them or hit cancel. Contact Mediclinic if you would like to upgrade your account.");
            return;
        }


        if (chkIsProvider.Checked)
        {
            System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "has_offerings=1 AND field_id <> 0", "", "field_id", "descr");

            bool         roleSetAsProvider = false;
            IDandDescr[] fields            = new IDandDescr[tbl.Rows.Count];
            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                fields[i] = new IDandDescr(Convert.ToInt32(tbl.Rows[i]["field_id"]), tbl.Rows[i]["descr"].ToString());
                if (Convert.ToInt32(ddlField.SelectedValue) == Convert.ToInt32(tbl.Rows[i]["field_id"]))
                {
                    roleSetAsProvider = true;
                }
            }

            if (!roleSetAsProvider)
            {
                if (fields.Length == 1)
                {
                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "'.");
                    return;
                }
                else if (fields.Length == 2)
                {
                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as '" + fields[0].Descr + "' or '" + fields[1].Descr + "'.");
                    return;
                }
                else
                {
                    string providerFields = string.Empty;
                    for (int i = 0; i < fields.Length; i++)
                    {
                        providerFields += (providerFields.Length == 0 ? "" : ", ") + (fields.Length >= 2 && i == (fields.Length - 2) ? "or " : "") + fields[i].Descr;
                    }

                    SetErrorMessage("When setting a staff member as a provider, you need to set their Role as one of the following: " + providerFields);
                    return;
                }
            }
        }



        if (chkIsMasterAdmin.Checked)
        {
            chkIsAdmin.Checked = true;
        }

        PersonDB.Update(person_id, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), row["nickname"].ToString(), ddlGender.SelectedValue, GetDate(ddlDOB_Day.SelectedValue, ddlDOB_Month.SelectedValue, ddlDOB_Year.SelectedValue), DateTime.Now);
        StaffDB.Update(staff_id, person_id, txtLogin.Text, txtPwd.Text, Convert.ToInt32(row["staff_position_id"]), Convert.ToInt32(ddlField.SelectedValue), Convert.ToInt32(ddlCostCentre.SelectedValue),
                       chkContractor.Checked, txtTFN.Text, txtProviderNumber.Text.ToUpper(),
                       ddlStatus.SelectedValue == "Inactive", chkIsCommission.Checked, Convert.ToDecimal(txtCommissionPercent.Text),
                       chkIsStakeholder.Checked, chkIsMasterAdmin.Checked, chkIsAdmin.Checked, chkIsPrincipal.Checked, chkIsProvider.Checked, staff.IsExternal,
                       row["start_date"] == DBNull.Value ? DateTime.MinValue : (DateTime)row["start_date"], row["end_date"] == DBNull.Value ? DateTime.MinValue : (DateTime)row["end_date"], row["comment"].ToString(), chkSMSBKs.Checked, chkEmailBKs.Checked, chkHideBKNotes.Checked);

        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && staff.Login != txtLogin.Text)
        {
            UserDatabaseMapper curDBMapper = UserDatabaseMapperDB.GetByLogin(staff.Login, Session["DB"].ToString());
            if (curDBMapper == null)
            {
                UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
            }
            else
            {
                UserDatabaseMapperDB.Update(curDBMapper.ID, txtLogin.Text, Session["DB"].ToString());
            }
        }


        GrdStaff.EditIndex = -1;
        FillGrid();
    }
예제 #6
0
    protected void Button4_Click(object sender, EventArgs e)
    {
        // need to be able to have them put in their own field instead of physio/podiatry ....


/*
 * select * from UserDatabaseMapper order by id desc
 * delete UserDatabaseMapper where dbname in ('Mediclinic_0002','Mediclinic_0003','Mediclinic_0004','Mediclinic_0005')
 */

        // also need to not import field type phys/pod ....


        try
        {
            decimal decNum;
            int     intNum;

            if (txtInitialStaffFirstname.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Staff Firstname is a required field.");
            }
            if (txtInitialStaffSurname.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Staff Surname is a required field.");
            }
            if (txtInitialStaffLogin.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Staff Login is a required field.");
            }
            if (txtMedicareEclaimsLicenseNbr.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Medicare Eclaims License Nbr is a required field.");
            }
            if (!Decimal.TryParse(txtSMSPrice.Text.Trim(), out decNum))
            {
                throw new CustomMessageException("SMS Price must be a decimal.");
            }
            if (!Int32.TryParse(txtMaxNbrProviders.Text.Trim(), out intNum))
            {
                throw new CustomMessageException("Max Nbr Providers must be a number.");
            }
            if (txtSiteName.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Clinic Site Name is a required field.");
            }
            if (txtEmail_FromName.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Email Sending From Name is a required field.");
            }
            if (!Utilities.IsValidEmailAddress(txtEmail_FromEmail.Text.Trim()))
            {
                throw new CustomMessageException("Email Sending From Email must be a valid email address.");
            }
            if (!Utilities.IsValidEmailAddress(txtAdminAlertEmail_To.Text.Trim()))
            {
                throw new CustomMessageException("Admin Alert Email must be a valid email address.");
            }
            if (txtField1.Text.Trim().Length == 0)
            {
                throw new CustomMessageException("Field 1 is a required field.");
            }
        }
        catch (CustomMessageException ex)
        {
            Label4.Text = "<font color=\"red\"><br>" + ex.Message + "</b></font>";
            return;
        }



        string initialStaffFirstname = txtInitialStaffFirstname.Text.Trim();
        string initialStaffSurname   = txtInitialStaffSurname.Text.Trim();
        string initialStaffLogin     = GetUniqueLogin(txtInitialStaffLogin.Text.Trim().ToLower());


        //
        // clone the DB with new name
        //

        string newDBName = GetNewDBName();

        CloneDB("Mediclinic_StubDB", "Mediclinic_StubDB_log", newDBName);


        //
        // update any config items
        //

        SystemVariableDB.Update("MedicareEclaimsLicenseNbr", txtMedicareEclaimsLicenseNbr.Text.Trim(), newDBName);
        SystemVariableDB.Update("SMSPrice", txtSMSPrice.Text.Trim(), newDBName);
        SystemVariableDB.Update("MaxNbrProviders", txtMaxNbrProviders.Text.Trim(), newDBName);
        SystemVariableDB.Update("AllowAddSiteClinic", ddlAllowAddSiteClinic.SelectedValue, newDBName);
        SystemVariableDB.Update("AllowAddSiteAgedCare", ddlAllowAddSiteAgedCare.SelectedValue, newDBName);
        SystemVariableDB.Update("BannerMessage", txtBannerMessage.Text.Trim(), newDBName);
        SystemVariableDB.Update("ShowBannerMessage", ddlShowBannerMessage.SelectedValue, newDBName);
        SystemVariableDB.Update("Email_FromName", txtEmail_FromName.Text, newDBName);
        SystemVariableDB.Update("Email_FromEmail", txtEmail_FromEmail.Text.Trim(), newDBName);
        SystemVariableDB.Update("AdminAlertEmail_To", txtAdminAlertEmail_To.Text.Trim(), newDBName);



        //
        // update login/pwd for first staff memeber and for support staff
        //

        string sql_update_staff = @"

            UPDATE Person
            SET 
                Person.firstname = '" + initialStaffFirstname + @"'  
               ,Person.surname   = '" + initialStaffSurname + @"'  
            FROM Person
            JOIN Staff ON Person.person_id = Staff.person_id
            WHERE Staff.staff_id = 1;


            UPDATE Staff SET login = '******'         WHERE staff_id = 1;
            UPDATE Staff SET pwd   = '" + initialStaffLogin + @"'         WHERE staff_id = 1;

            UPDATE Staff SET login = '******'   WHERE staff_id = -2;
            UPDATE Staff SET login = '******'   WHERE staff_id = -3;
            UPDATE Staff SET login = '******'   WHERE staff_id = -4;
        ";

        if (txtField1.Text.Trim().Length > 0)
        {
            sql_update_staff += @"INSERT Field (descr, has_offerings) VALUES ('" + txtField1.Text.Trim() + @"' , 1);" + Environment.NewLine;
        }
        if (txtField2.Text.Trim().Length > 0)
        {
            sql_update_staff += @"INSERT Field (descr, has_offerings) VALUES ('" + txtField2.Text.Trim() + @"' , 1);" + Environment.NewLine;
        }

        sql_update_staff += @"UPDATE Site SET name = '" + txtSiteName.Text.Trim() + @"' WHERE site_type_id = 1;" + Environment.NewLine;


        DBBase.ExecuteNonResult(sql_update_staff, newDBName);

        UserDatabaseMapperDB.Insert(initialStaffLogin, newDBName);
        UserDatabaseMapperDB.Insert(newDBName + "_support1", newDBName);
        UserDatabaseMapperDB.Insert(newDBName + "_support2", newDBName);
        UserDatabaseMapperDB.Insert(newDBName + "_support3", newDBName);


        Label4.Text =
            @"Database created successfully.<br />
<table border=""0"" cellpadding=""0"" cellspacing=""0"">
<tr>
    <td>Database : </td>
    <td style=""width:20px;""></td>
    <td><b>" + newDBName + @"</b></td>
</tr>
<tr>
    <td>Staff Username & Password : </td>
    <td></td>
    <td><b>" + initialStaffLogin + @"</b></td>
</tr>
</table>";
    }
예제 #7
0
    protected bool ExistsAndCreatedLogin_FromEmail(int orgID, string phoneNumber, string email, int siteID, ref int register_patient_id, ref int phone_id, ref int email_id)
    {
        bool patientAlreadyExists = false;


        int[] entityIDs;
        if (Utilities.GetAddressType().ToString() == "Contact")
        {
            entityIDs = ContactDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
        }
        else if (Utilities.GetAddressType().ToString() == "ContactAus")
        {
            entityIDs = ContactAusDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
        }
        else
        {
            throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
        }

        foreach (int entityID in entityIDs)
        {
            Patient patient = PatientDB.GetByEntityID(entityID);
            if (patient == null || patient.IsDeceased || patient.IsDeleted)
            {
                continue;
            }

            // if no login set, create it

            bool hasLoginDetails = patient.Login.Length > 0;
            if (!hasLoginDetails)
            {
                string login    = txtLogin.Text;
                string loginTry = login;

                Random rnd = new Random();
                int    nbr = rnd.Next(11, 999);

                do
                {
                    bool loginUsed = (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(loginTry)) ||
                                     (PatientDB.LoginExists(loginTry));


                    if (loginUsed)
                    {
                        throw new CustomMessageException("Login name in use. Please choose another");
                    }

                    if (!loginUsed)
                    {
                        patient.Login = loginTry;
                        patient.Pwd   = txtPwd.Text;

                        PatientDB.UpdateLoginPwd(patient.PatientID, patient.Login, patient.Pwd);
                        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                        {
                            UserDatabaseMapperDB.Insert(loginTry, Session["DB"].ToString());
                        }

                        break;
                    }

                    nbr++;
                    loginTry = login + nbr;
                } while (true);
            }


            // add phone number if different from existing
            phone_id = AddPhoneNbrIfNotExists(patient, siteID, phoneNumber);

            // add clinic if different from existing
            register_patient_id = AddOrgIfNotExists(patient, siteID, orgID);


            SendInfoEmail(email, patient.Login, patient.Pwd);
            patientAlreadyExists = true;
        }

        return(patientAlreadyExists);
    }
예제 #8
0
    protected bool ExistsAndCreatedLogin_FromNameAndDOB(int orgID, string phoneNumber, string email, string firstname, string surname, DateTime DOB, int siteID, ref int register_patient_id, ref int phone_id, ref int email_id)
    {
        bool patientAlreadyExists = false;

        Patient[] matchingPatients = PatientDB.GetByFirstnameSurnameDOB(firstname, surname, DOB);
        foreach (Patient patient in matchingPatients)
        {
            if (patient == null || patient.IsDeceased || patient.IsDeleted)
            {
                continue;
            }

            if (patient.Person.Firstname != firstname ||
                patient.Person.Surname != surname ||
                patient.Person.Dob == DateTime.MinValue ||
                patient.Person.Dob != DOB)
            {
                continue;
            }

            // if no login set, create it

            bool hasLoginDetails = patient.Login.Length > 0;
            if (!hasLoginDetails)
            {
                string login    = txtLogin.Text;
                string loginTry = login;

                Random rnd = new Random();
                int    nbr = rnd.Next(11, 999);

                do
                {
                    bool loginUsed = (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(loginTry)) ||
                                     (PatientDB.LoginExists(loginTry));

                    if (loginUsed)
                    {
                        throw new CustomMessageException("Login name in use. Please choose another");
                    }

                    if (!loginUsed)
                    {
                        patient.Login = loginTry;
                        patient.Pwd   = txtPwd.Text;

                        PatientDB.UpdateLoginPwd(patient.PatientID, patient.Login, patient.Pwd);
                        if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                        {
                            UserDatabaseMapperDB.Insert(loginTry, Session["DB"].ToString());
                        }

                        break;
                    }

                    nbr++;
                    loginTry = login + nbr;
                } while (true);
            }



            // add phone number if different from existing
            phone_id = AddPhoneNbrIfNotExists(patient, siteID, phoneNumber);

            // add email if different from existing
            email_id = AddEmailIfNotExists(patient, siteID, email);

            // add clinic if different from existing
            register_patient_id = AddOrgIfNotExists(patient, siteID, orgID);


            SendInfoEmail(email, patient.Login, patient.Pwd);
            patientAlreadyExists = true;
        }

        return(patientAlreadyExists);
    }
예제 #9
0
    protected void CreatePatientButton_Click(object sender, EventArgs e)
    {
        if (!ddlDOBValidateAllSet.IsValid)
        {
            return;
        }

        int  person_id           = -1;
        int  patient_id          = -1;
        int  register_patient_id = -1;
        bool patient_added       = false;
        int  mainDbUserID        = -1;

        int  phone_id       = -1;
        int  email_id       = -1;
        bool contacts_added = false;

        try
        {
            string[] clinicInfo = ddlClinic.SelectedValue.Split(new string[] { "__" }, StringSplitOptions.None);
            string   dbID       = clinicInfo[0];
            int      siteID     = Convert.ToInt32(clinicInfo[1]);
            int      orgID      = Convert.ToInt32(clinicInfo[2]);

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

            txtEmailAddr.Text   = txtEmailAddr.Text.Trim();
            txtPhoneNumber.Text = txtPhoneNumber.Text.Trim();
            if (!Utilities.IsValidEmailAddress(txtEmailAddr.Text))
            {
                throw new CustomMessageException("Email must be in valid email format.");
            }

            txtLogin.Text = txtLogin.Text.Trim();
            txtPwd.Text   = txtPwd.Text.Trim();

            txtFirstname.Text = txtFirstname.Text.Trim();
            txtSurname.Text   = txtSurname.Text.Trim();



            // check if patient exists in the system, if so use existing patietn

            bool patientAlreadyExists = false;

            // check if email exists in the system
            if (!patientAlreadyExists)
            {
                if (ExistsAndCreatedLogin_FromEmail(orgID, txtPhoneNumber.Text, txtEmailAddr.Text, siteID, ref register_patient_id, ref phone_id, ref email_id))
                {
                    patientAlreadyExists      = true;
                    patient_added             = true;
                    contacts_added            = true;
                    this.lblErrorMessage.Text = "Your email alrady exist in this sytem.<br/>An email has been sent with new login details.<br/>When you receieve it, use the login link below.";
                }
            }

            // check if firstname / surname / DOB exists in the system
            if (!patientAlreadyExists)
            {
                if (ExistsAndCreatedLogin_FromNameAndDOB(orgID, txtPhoneNumber.Text, txtEmailAddr.Text, txtFirstname.Text, txtSurname.Text, GetDOBFromForm(), siteID, ref register_patient_id, ref phone_id, ref email_id))
                {
                    patientAlreadyExists      = true;
                    patient_added             = true;
                    contacts_added            = true;
                    this.lblErrorMessage.Text = "You alrady exist in this sytem.<br/>An email has been sent with new login details.<br/>When you receieve it, use the login link below.";
                }
            }



            if (!patientAlreadyExists)
            {
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(txtLogin.Text))
                {
                    throw new CustomMessageException("Login name already in use. Please choose another");
                }
                if (PatientDB.LoginExists(txtLogin.Text))
                {
                    throw new CustomMessageException("Login name already in use. Please choose another");
                }


                // 1. Create Patient

                Staff loggedInStaff = StaffDB.GetByID(-6);
                person_id           = PersonDB.Insert(loggedInStaff.Person.PersonID, Convert.ToInt32(ddlTitle.SelectedValue), Utilities.FormatName(txtFirstname.Text), "", Utilities.FormatName(txtSurname.Text), "", ddlGender.SelectedValue, GetDOBFromForm());
                patient_id          = PatientDB.Insert(person_id, true, false, false, "", -1, DateTime.MinValue, "", "", DateTime.MinValue, false, false, DateTime.MinValue, -1, -1, txtLogin.Text, txtPwd.Text, false, "", "", "", "");
                register_patient_id = RegisterPatientDB.Insert(orgID, patient_id);
                patient_added       = true;   // added this because was throwing a thread aborted exception after patient added before Response.Redirect


                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    if (txtLogin.Text.Length > 0)
                    {
                        mainDbUserID = UserDatabaseMapperDB.Insert(txtLogin.Text, Session["DB"].ToString());
                    }
                }


                // 2. Add Contact Info

                Patient patient = PatientDB.GetByID(patient_id);

                phone_id            = AddPhoneNbrIfNotExists(patient, siteID, txtPhoneNumber.Text);
                email_id            = AddEmailIfNotExists(patient, siteID, txtEmailAddr.Text);
                register_patient_id = AddOrgIfNotExists(patient, siteID, orgID);
                contacts_added      = true;


                SendInfoEmail(txtEmailAddr.Text, txtLogin.Text, txtPwd.Text);

                this.lblErrorMessage.Text = "An email has been sent with new login details.<br />When you receieve it, use the login link below.";
            }
        }
        catch (Exception ex)
        {
            if (!patient_added || !contacts_added)
            {
                // roll back - backwards of creation order

                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    ContactDB.Delete(phone_id);
                    ContactDB.Delete(email_id);
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    ContactAusDB.Delete(phone_id);
                    ContactAusDB.Delete(email_id);
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }

                RegisterPatientDB.Delete(register_patient_id);
                PatientDB.Delete(patient_id);
                PersonDB.Delete(person_id);

                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                {
                    UserDatabaseMapperDB.Delete(mainDbUserID);
                }

                if (ex is CustomMessageException)
                {
                    this.lblErrorMessage.Text = ex.Message;
                }
                else
                {
                    lblErrorMessage.Text = ex.ToString();
                }
            }
        }
        finally
        {
            //Session["DB"] = curDbName;
            //Session["SystemVariables"] = SystemVariableDB.GetAll();
            Session.Remove("DB");
            Session.Remove("SystemVariables");
        }
    }
    protected void CreateLogin(string email)
    {
        email = email.Replace("'", "''");

        //string curDbName = Session["DB"].ToString();

        try
        {
            List <Tuple <string, Patient, bool> > list = new List <Tuple <string, Patient, bool> >();


            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;

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

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


                bool allowPatientLogins            = ((SystemVariables)Session["SystemVariables"])["AllowPatientLogins"].Value == "1";
                bool allowPatientsToCreateOwnLogin = ((SystemVariables)Session["SystemVariables"])["AllowPatientsToCreateOwnLogin"].Value == "1";

                if (!allowPatientLogins || !allowPatientsToCreateOwnLogin)
                {
                    continue;
                }


                int[] entityIDs;
                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    entityIDs = ContactDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    entityIDs = ContactAusDB.GetByAddrLine1(null, email, 27).Select(r => r.EntityID).ToArray();
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }


                foreach (int entityID in entityIDs)
                {
                    Patient patient = PatientDB.GetByEntityID(entityID);
                    if (patient == null || patient.IsDeceased || patient.IsDeleted)
                    {
                        continue;
                    }

                    bool hasLoginDetails = patient.Login.Length > 0;
                    if (!hasLoginDetails)
                    {
                        string login    = Regex.Replace(patient.Person.Firstname, @"[^A-Za-z]+", "").ToLower() + Regex.Replace(patient.Person.Surname, @"[^A-Za-z]+", "").ToLower();
                        string loginTry = login;

                        Random rnd = new Random();
                        int    nbr = rnd.Next(11, 999);

                        do
                        {
                            bool loginUsed = (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]) && UserDatabaseMapperDB.UsernameExists(loginTry)) ||
                                             (PatientDB.LoginExists(loginTry));

                            if (!loginUsed)
                            {
                                patient.Login = loginTry;
                                patient.Pwd   = loginTry == login ? login + nbr : loginTry;

                                PatientDB.UpdateLoginPwd(patient.PatientID, patient.Login, patient.Pwd);
                                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["UseConfigDB"]))
                                {
                                    UserDatabaseMapperDB.Insert(loginTry, Session["DB"].ToString());
                                }

                                break;
                            }

                            nbr++;
                            loginTry = login + nbr;
                        } while (true);
                    }

                    SendPasswordRetrievalEmail(patient.Login, patient.Pwd, email);
                    list.Add(new Tuple <string, Patient, bool>(databaseName, patient, hasLoginDetails));
                }

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


            System.Text.StringBuilder finalOutput = new System.Text.StringBuilder();
            foreach (Tuple <string, Patient, bool> item in list)
            {
                finalOutput.Append("<tr><td>" + item.Item1 + "</td><td>" + item.Item2.Person.FullnameWithoutMiddlename + "</td><td>" + item.Item3 + "</td><td>" + item.Item2.Login + " | " + item.Item2.Pwd + "</td></tr>");
            }


            //FailureText.Text = "Count: " + list.Count + "<br /><table border=\"1\" class=\"block_center padded-table-2px\">" + finalOutput.ToString() + "</table>";


            if (list.Count == 0)
            {
                throw new CustomMessageException("No patients found with this email");
            }

            this.FailureText.Text = "An email has been sent with new login details";
        }
        catch (CustomMessageException cmEx)
        {
            this.FailureText.Text = cmEx.Message;
        }
        finally
        {
            //Session["DB"] = curDbName;
            //Session["SystemVariables"] = SystemVariableDB.GetAll();
            Session.Remove("DB");
            Session.Remove("SystemVariables");
        }
    }