예제 #1
0
        protected void OnSubmit(object sender, EventArgs e)
        {
            // ModifiedBySolvion
            // bhi - 09.01.2012
            // Reset message labels
            lblMessage.Text = lblAnswerMessage.Text = lblEmailMessage.Text = lblPasswordMessage.Text = lblQuestionMessage.Text = "";
            // EndModifiedBySolvion

            bool _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles;

            // check to see if username already in use
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(txtUsername.Text, false);

            if (user == null)
            {
                try
                {
                    // get site reference
                    string provider = Utils.GetMembershipProvider(this.Site);

                    // create FBA database user
                    MembershipCreateStatus createStatus;

                    if (Utils.BaseMembershipProvider().RequiresQuestionAndAnswer)
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, isActive.Checked, null, out createStatus);
                    }
                    else
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, null, null, isActive.Checked, null, out createStatus);
                    }


                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        SetErrorMessage(createStatus);
                        return;
                    }

                    if (user == null)
                    {
                        lblMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "UnknownError");
                        return;
                    }

                    bool groupAdded = false;

                    if (_showRoles)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value });
                            }
                        }

                        // add user to SharePoint whether a role was selected or not
                        AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                    }
                    else
                    {
                        // add user to each group that was selected
                        for (int i = 0; i < groupList.Items.Count; i++)
                        {
                            if (groupList.Items[i].Selected)
                            {
                                // add user to group
                                SPGroup group = this.Web.SiteGroups[groupList.Items[i].Value];
                                group.AddUser(
                                    Utils.EncodeUsername(user.UserName),
                                    user.Email,
                                    txtFullName.Text,
                                    "");

                                // update
                                group.Update();
                                groupAdded = true;
                            }
                        }

                        // if no group selected, add to site with no permissions
                        if (!groupAdded)
                        {
                            AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                        }
                    }

                    // Email User
                    if ((emailUser.Checked == true))
                    {
                        //InputFormTextBox txtEmailSubject = (InputFormTextBox)emailUser.FindControl("txtEmailSubject");
                        //InputFormTextBox txtEmailBody = (InputFormTextBox)emailUser.FindControl("txtEmailBody");
                        if ((!string.IsNullOrEmpty(txtEmailSubject.Text)) && (!string.IsNullOrEmpty(txtEmailBody.Text)))
                        {
                            Email.SendEmail(this.Web, user.Email, txtEmailSubject.Text, txtEmailBody.Text);
                        }
                    }

                    SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }
            else
            {
                lblMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "DuplicateUserName");;
            }
        }
예제 #2
0
        private void AddChangePasswordControl()
        {
            TemplateHelper helper;

            string provider = Utils.GetMembershipProvider(Context);

            //Exit if membership provider not defined
            if (provider == null || !Utils.IsProviderConfigured())
            {
                Controls.Add(new LiteralControl(LocalizedString.GetString("FBAPackFeatures", "MembershipNotConfigured")));
                return;
            }

            if (SPContext.Current.Web.CurrentUser == null)
            {
                //Login Control won't work with SP2010, so for now, just don't show a control at all
                //Login ctlLogin = new Login();
                //this.Controls.Add(ctlLogin);
            }
            else
            {
                _ctlChangePassword = new System.Web.UI.WebControls.ChangePassword();
                _ctlChangePassword.ChangePasswordTemplate    = new TemplateLoader(ChangePasswordTemplate, Page);
                _ctlChangePassword.SuccessTemplate           = new TemplateLoader(SuccessTemplate, Page);
                _ctlChangePassword.MembershipProvider        = provider;
                _ctlChangePassword.ChangePasswordFailureText = ChangePasswordFailureText;

                if (!String.IsNullOrEmpty(CancelDestinationPageUrl))
                {
                    _ctlChangePassword.CancelDestinationPageUrl = CancelDestinationPageUrl;
                }
                else
                {
                    string url = SPUtility.OriginalServerRelativeRequestUrl;
                    SPUtility.DetermineRedirectUrl(url, SPRedirectFlags.UseSource, this.Context, null, out url);
                    _ctlChangePassword.CancelDestinationPageUrl = url;
                }

                if (!String.IsNullOrEmpty(ContinueDestinationPageUrl))
                {
                    _ctlChangePassword.ContinueDestinationPageUrl = ContinueDestinationPageUrl;
                }
                else
                {
                    string url = SPUtility.OriginalServerRelativeRequestUrl;
                    SPUtility.DetermineRedirectUrl(url, SPRedirectFlags.UseSource, this.Context, null, out url);
                    _ctlChangePassword.ContinueDestinationPageUrl = url;
                }


                _ctlChangePassword.ToolTip        = ToolTip;
                _ctlChangePassword.SuccessPageUrl = SuccessPageUrl;
                _ctlChangePassword.NewPasswordRegularExpressionErrorMessage = NewPasswordRegularExpressionErrorMessage;

                //ChangePasswordTemplate
                //have to initially force DisplayUserName true to access template
                _ctlChangePassword.DisplayUserName = true;
                helper = new TemplateHelper(_ctlChangePassword.ChangePasswordTemplateContainer);
                _ctlChangePassword.DisplayUserName = DisplayUserName;
                helper.SetText("ChangePasswordTitle", ChangePasswordTitleText);
                helper.SetText("Instruction", InstructionText);
                helper.SetVisible("UserNameRow", DisplayUserName);
                helper.SetText("UserNameLabel", UserNameLabelText);
                helper.SetValidation("UserNameRequired", UserNameRequiredErrorMessage, this.UniqueID);
                helper.SetText("CurrentPasswordLabel", PasswordLabelText);
                helper.SetValidation("CurrentPasswordRequired", PasswordRequiredErrorMessage, this.UniqueID);
                helper.SetText("NewPasswordLabel", NewPasswordLabelText);
                helper.SetValidation("NewPasswordRequired", NewPasswordRequiredErrorMessage, this.UniqueID);
                helper.SetText("PasswordHint", PasswordHintText);
                helper.SetVisible("PasswordHintRow", !String.IsNullOrEmpty(PasswordHintText));
                helper.SetText("ConfirmNewPasswordLabel", ConfirmNewPasswordLabelText);
                helper.SetValidation("ConfirmNewPasswordRequired", ConfirmPasswordRequiredErrorMessage, this.UniqueID);
                helper.SetValidation("ConfirmNewPasswordCompare", ConfirmPasswordCompareErrorMessage, this.UniqueID);

                switch (ChangePasswordButtonType)
                {
                case ButtonType.Button:
                    helper.SetButton("ChangePasswordButton", ChangePasswordButtonText, this.UniqueID);
                    helper.SetVisible("ChangePasswordButton", true);
                    break;

                case ButtonType.Image:
                    helper.SetImageButton("ChangePasswordImageButton", ChangePasswordButtonImageUrl, ChangePasswordButtonText, this.UniqueID);
                    helper.SetVisible("ChangePasswordImageButton", true);
                    break;

                case ButtonType.Link:
                    helper.SetButton("ChangePasswordLinkButton", ChangePasswordButtonText, this.UniqueID);
                    helper.SetVisible("ChangePasswordLinkButton", true);
                    break;
                }

                switch (CancelButtonType)
                {
                case ButtonType.Button:
                    helper.SetButton("CancelButton", CancelButtonText, this.UniqueID);
                    helper.SetVisible("CancelButton", true);
                    break;

                case ButtonType.Image:
                    helper.SetImageButton("CancelImageButton", CancelButtonImageUrl, CancelButtonText, this.UniqueID);
                    helper.SetVisible("CancelImageButton", true);
                    break;

                case ButtonType.Link:
                    helper.SetButton("CancelLinkButton", CancelButtonText, this.UniqueID);
                    helper.SetVisible("CancelLinkButton", true);
                    break;
                }

                helper.SetVisible("EditProfileRow", !String.IsNullOrEmpty(EditProfileUrl));
                helper.SetImage("EditProfileIcon", EditProfileIconUrl, EditProfileText, false);
                helper.SetLink("EditProfileLink", EditProfileText, EditProfileUrl);

                helper.SetVisible("HelpPageRow", !String.IsNullOrEmpty(HelpPageUrl));
                helper.SetImage("HelpPageIcon", HelpPageIconUrl, HelpPageText, false);
                helper.SetLink("HelpPageLink", HelpPageText, HelpPageUrl);

                helper.SetVisible("CreateUserRow", !String.IsNullOrEmpty(CreateUserUrl));
                helper.SetImage("CreateUserIcon", CreateUserIconUrl, CreateUserText, false);
                helper.SetLink("CreateUserLink", CreateUserText, CreateUserUrl);

                helper.SetVisible("PasswordRecoveryRow", !String.IsNullOrEmpty(PasswordRecoveryUrl));
                helper.SetImage("PasswordRecoveryIcon", PasswordRecoveryIconUrl, PasswordRecoveryText, false);
                helper.SetLink("PasswordRecoveryLink", PasswordRecoveryText, PasswordRecoveryUrl);

                //SuccessTemplate
                helper = new TemplateHelper(_ctlChangePassword.SuccessTemplateContainer);
                helper.SetText("Success", SuccessText);

                helper.SetVisible("EditProfileRow", !String.IsNullOrEmpty(EditProfileUrl));
                helper.SetImage("EditProfileIcon", EditProfileIconUrl, EditProfileText, false);
                helper.SetLink("EditProfileLink", EditProfileText, EditProfileUrl);

                switch (ContinueButtonType)
                {
                case ButtonType.Button:
                    helper.SetButton("ContinueButton", ContinueButtonText, this.UniqueID);
                    helper.SetVisible("ContinueButton", true);
                    break;

                case ButtonType.Image:
                    helper.SetImageButton("ContinueImageButton", ContinueButtonImageUrl, ContinueButtonText, this.UniqueID);
                    helper.SetVisible("ContinueImageButton", true);
                    break;

                case ButtonType.Link:
                    helper.SetButton("ContinueLinkButton", ContinueButtonText, this.UniqueID);
                    helper.SetVisible("ContinueLinkButton", true);
                    break;
                }

                //_ctlChangePassword.ChangingPassword += new LoginCancelEventHandler(ctlChangePassword_ChangingPassword);
                _ctlChangePassword.ChangedPassword += new EventHandler(_ctlChangePassword_ChangedPassword);
                _ctlChangePassword.Load            += new EventHandler(_ctlChangePassword_Load);

                this.Controls.Add(_ctlChangePassword);
            }
        }
예제 #3
0
        private void AddPasswordRecoveryControl()
        {
            TemplateHelper helper;

            string provider = Utils.GetMembershipProvider(Context);

            //Exit if membership provider not defined
            if (provider == null || !Utils.IsProviderConfigured())
            {
                Controls.Add(new LiteralControl(LocalizedString.GetString("FBAPackFeatures", "MembershipNotConfigured")));
                return;
            }

            /* bms I couldn't figure out how to set the smtp server from code so I added the SendMailError as a hack for now */

            _ctlPasswordRecovery = new System.Web.UI.WebControls.PasswordRecovery();
            _ctlPasswordRecovery.UserNameTemplate = new TemplateLoader(UserNameTemplate, Page);
            _ctlPasswordRecovery.SuccessTemplate  = new TemplateLoader(SuccessTemplate, Page);
            _ctlPasswordRecovery.QuestionTemplate = new TemplateLoader(QuestionTemplate, Page);
            //bms Added the event to catch the error and send our own email
            _ctlPasswordRecovery.SendMailError      += new SendMailErrorEventHandler(_ctlPasswordRecovery_SendMailError);
            _ctlPasswordRecovery.VerifyingUser      += new LoginCancelEventHandler(_ctlPasswordRecovery_VerifyingUser);
            _ctlPasswordRecovery.SendingMail        += new MailMessageEventHandler(_ctlPasswordRecovery_SendingMail);
            _ctlPasswordRecovery.MembershipProvider  = provider;
            _ctlPasswordRecovery.GeneralFailureText  = GeneralFailureText;
            _ctlPasswordRecovery.QuestionFailureText = QuestionFailureText;
            _ctlPasswordRecovery.UserNameFailureText = UserNameFailureText;

            //UsernameTemplate
            helper = new TemplateHelper(_ctlPasswordRecovery.UserNameTemplateContainer);
            helper.SetText("UserNameInstruction", UserNameInstructionText);
            helper.SetText("UserNameLabel", UserNameLabelText);
            helper.SetText("UserNameTitle", UserNameTitleText);
            helper.SetValidation("UserNameRequired", UserNameRequiredErrorMessage, this.UniqueID);
            switch (SubmitButtonType)
            {
            case ButtonType.Button:
                helper.SetButton("SubmitButton", SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitButton", true);
                break;

            case ButtonType.Image:
                helper.SetImageButton("SubmitImageButton", SubmitButtonImageUrl, SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitImageButton", true);
                break;

            case ButtonType.Link:
                helper.SetButton("SubmitLinkButton", SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitLinkButton", true);
                break;
            }

            //QuestionTemplate
            helper = new TemplateHelper(_ctlPasswordRecovery.QuestionTemplateContainer);
            helper.SetText("QuestionInstruction", QuestionInstructionText);
            helper.SetText("UserNameLabel", UserNameLabelText);
            helper.SetText("QuestionLabel", QuestionLabelText);
            helper.SetText("QuestionTitle", QuestionTitleText);
            helper.SetValidation("AnswerRequired", AnswerRequiredErrorMessage, this.UniqueID);
            switch (SubmitButtonType)
            {
            case ButtonType.Button:
                helper.SetButton("SubmitButton", SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitButton", true);
                break;

            case ButtonType.Image:
                helper.SetImageButton("SubmitImageButton", SubmitButtonImageUrl, SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitImageButton", true);
                break;

            case ButtonType.Link:
                helper.SetButton("SubmitLinkButton", SubmitButtonText, this.UniqueID);
                helper.SetVisible("SubmitLinkButton", true);
                break;
            }

            //SuccessTemplate
            helper = new TemplateHelper(_ctlPasswordRecovery.SuccessTemplateContainer);
            helper.SetText("Success", SuccessText);

            this.Controls.Add(_ctlPasswordRecovery);
        }
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            // only continue if a membership provider has been configured
            if (!Utils.IsProviderConfigured())
            {
                return(null);
            }

            // get site details
            SPSite site     = SPContext.Current.Site;
            string provider = Utils.GetMembershipProvider(site);

            if (provider == null)
            {
                return(null);
            }

            SPWeb web = site.RootWeb;

            string yes = LocalizedString.GetString("FBAPackFeatures", "Yes");

            string no = LocalizedString.GetString("FBAPackFeatures", "No");

            string cacheKey = String.Format("Visigo.SharePoint.FormsBasedAuthentication.FBAUsersView.{0}", provider);

            Dictionary <string, SPListItem> spUsers = _cache.Get(cacheKey) as Dictionary <string, SPListItem>;

            //Reload site user info list or grab from cache
            if (_owner.ResetCache || spUsers == null)
            {
                spUsers = new Dictionary <string, SPListItem>();

                // we only display users that have been added to SharePoint
                // we use the localized name, safe for non-English SharePoint servers
                SPList list = web.SiteUserInfoList; //web.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];

                // create query list
                SPQuery query = new SPQuery();
                query.Query = string.Format(
                    "<Where>" +
                    "<And>" +
                    "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
                    "<Contains><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></Contains>" +
                    "</And>" +
                    "</Where>", provider);

                query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";
                query.RowLimit   = 100000;
                //Convert SPListItemCollection to dictionary for fast lookup

                try
                {
                    SPListItemCollection userList = list.GetItems(query);

                    if (userList != null)
                    {
                        foreach (SPListItem item in userList)
                        {
                            string username    = item["Name"] as string;
                            string decodedName = Utils.DecodeUsername(username);
                            if (username != decodedName)
                            {
                                spUsers.Add(decodedName, item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex);
                    return(null);
                }

                _cache.Add(cacheKey, spUsers, null,
                           DateTime.UtcNow.AddMinutes(1.0),
                           System.Web.Caching.Cache.NoSlidingExpiration,
                           System.Web.Caching.CacheItemPriority.Normal, null);
            }

            //Create a datatable for returning the results
            DataTable users = new DataTable();

            users.Columns.Add("Title");
            users.Columns.Add("Name");
            users.Columns.Add("Email");
            users.Columns.Add("Modified", typeof(DateTime));
            users.Columns.Add("Created", typeof(DateTime));
            users.Columns.Add("Active");
            users.Columns.Add("Locked");
            users.Columns.Add("LastLogin", typeof(DateTime));
            users.Columns.Add("IsInSharePoint");

            int totalRecords = 0;
            int spUsersCount = spUsers.Count;
            int spUsersFound = 0;

            users.BeginLoadData();

            //Add all membership users to the datatable
            foreach (MembershipUser memberuser in Utils.BaseMembershipProvider(site).GetAllUsers(0, 100000, out totalRecords))
            {
                string   title          = null;
                string   email          = memberuser.Email;
                DateTime?modified       = null;
                DateTime?created        = null;
                string   isInSharepoint = no;

                SPListItem spUser = null;

                //See if there is a matching sharepoint user - if so grab the values
                if (spUsersFound < spUsersCount)
                {
                    if (spUsers.TryGetValue(memberuser.UserName.ToLower(), out spUser))
                    {
                        spUsersFound++;
                        title          = spUser["Title"] as string;
                        created        = spUser["Created"] as DateTime?;
                        modified       = spUser["Modified"] as DateTime?;
                        isInSharepoint = yes;
                        //Make sure the SharePoint email field has a value before copying it over
                        string spEmail = spUser["EMail"] as string;
                        if (!String.IsNullOrEmpty(spEmail))
                        {
                            email = spEmail;
                        }
                    }
                }

                //Add the matched up membership + sharepoint data to the datatable
                users.LoadDataRow(new object[] {
                    title,
                    memberuser.UserName,
                    email,
                    modified,
                    created,
                    memberuser.IsApproved ? yes : no,
                    memberuser.IsLockedOut ? yes : no,
                    memberuser.LastLoginDate,
                    isInSharepoint
                }, false);
            }

            users.EndLoadData();

            // sort if a sort expression available
            DataView dataView = new DataView(users);

            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
            }

            //Filter the data if a filter is provided
            if (_owner.SearchText.Length > 0)
            {
                dataView.RowFilter = string.Format("Name LIKE '%{0}%' OR Email LIKE '%{0}%' OR Title LIKE '%{0}%'", _owner.SearchText);
            }
            else
            {
                dataView.RowFilter = "";
            }

            // return as a DataList
            return((IEnumerable)dataView);
        }
        protected void OnSubmit(object sender, EventArgs e)
        {
            // ModifiedBySolvion
            // bhi - 09.01.2012
            // Reset message labels
            //lblMessage.Text =
            lblAnswerMessage.Text = lblEmailMessage.Text = lblPasswordMessage.Text = lblQuestionMessage.Text = "";
            // EndModifiedBySolvion

            bool _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles;

            // check to see if username already in use
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(txtEmail.Text, false);

            if (user == null)
            {
                try
                {
                    // get site reference
                    string provider = Utils.GetMembershipProvider(this.Site);

                    // create FBA database user
                    MembershipCreateStatus createStatus;

                    if (Utils.BaseMembershipProvider().RequiresQuestionAndAnswer)
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, isActive.Checked, null, out createStatus);
                    }
                    else
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, null, null, isActive.Checked, null, out createStatus);
                    }

                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        SetErrorMessage(createStatus);
                        return;
                    }

                    if (user == null)
                    {
                        lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "UnknownError");
                        return;
                    }

                    bool groupAdded = false;

                    if (_showRoles)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value });
                            }
                        }

                        // add user to SharePoint whether a role was selected or not
                        AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                    }
                    else
                    {
                        // add user to each group that was selected
                        for (int i = 0; i < groupList.Items.Count; i++)
                        {
                            if (groupList.Items[i].Selected)
                            {
                                // add user to group
                                SPGroup group = this.Web.SiteGroups[groupList.Items[i].Value];
                                group.AddUser(
                                    Utils.EncodeUsername(user.UserName),
                                    user.Email,
                                    txtFullName.Text,
                                    "");

                                // update
                                group.Update();
                                groupAdded = true;
                            }
                        }

                        // if no group selected, add to site with no permissions
                        if (!groupAdded)
                        {
                            AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                        }
                    }

                    SPSite site = SPContext.Current.Site;
                    SPWeb  web  = site.RootWeb;
                    SPList list = web.SiteUserInfoList;

                    SPUser     SPuser   = web.AllUsers.GetByEmail(txtEmail.Text);
                    SPListItem userItem = null;
                    try
                    {
                        userItem = list.GetItemById(SPuser.ID);
                    }
                    catch (Exception ex)
                    {
                        Utils.LogError(ex);
                    }

                    if (userItem != null)
                    {
                        userItem["CMIT Location"]        = txtCMITLocation.Text;
                        userItem["CMITTitle"]            = txtTitle.Text;
                        userItem["Telephone Number"]     = txtTelephoneNumber.Text;
                        userItem["Date of provisioning"] = txtDatofProvisionaing.SelectedDate;
                        userItem.Update();
                    }

                    // Email User
                    if ((emailUser.Checked == true))
                    {
                        if ((!string.IsNullOrEmpty(txtEmailSubject.Text)) && (!string.IsNullOrEmpty(txtEmailBody.Text)))
                        {
                            var emailBody = txtEmailBody.Text + Environment.NewLine + "Use your email as user name :" + txtEmail.Text + " and password as :" + txtPassword.Text + Environment.NewLine + "We recommand you to change your password when you login for first time.";
                            Email.SendEmail(this.Web, user.Email, txtEmailSubject.Text, emailBody);
                        }
                    }

                    SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }
            else
            {
                lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "DuplicateUserName");;
            }
        }
예제 #6
0
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            
            // only continue if a membership provider has been configured
            if (!Utils.IsProviderConfigured())
                return null;

            // get site details
            SPSite site = SPContext.Current.Site;
            string provider = Utils.GetMembershipProvider(site);
            if (provider == null)
                return null;
            
            SPWeb web = site.RootWeb;

            string yes = LocalizedString.GetString("FBAPackFeatures", "Yes");

            string no = LocalizedString.GetString("FBAPackFeatures", "No");

            // we only display users that have been added to SharePoint
            // we use the localized name, safe for non-English SharePoint servers
            SPList list = web.SiteUserInfoList; //web.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];

            // create query list
            SPQuery query = new SPQuery();
            query.Query = string.Format(
                "<Where>" +
                    "<And>" +
                        "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
                        "<Contains><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></Contains>" +
                    "</And>" +
                "</Where>" +
                "<OrderBy>" +
                    "<FieldRef Name='LinkTitle' />" +
                "</OrderBy>", provider);

            query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";

            // run query to get table of users
            DataTable users = null;
            try
            {
                users = list.GetItems(query).GetDataTable();
            }
            catch (Exception ex) 
            {
                Utils.LogError(ex);
                return null;
            }

            if (users == null)
            {
                users = new DataTable();
                users.Columns.Add("ID");
                users.Columns.Add("Title");
                users.Columns.Add("Name");
                users.Columns.Add("LinkTitle");
                users.Columns.Add("Email");
                users.Columns.Add("Modified", typeof(DateTime));
                users.Columns.Add("Created", typeof(DateTime));
            }

            users.Columns.Add("Active");
            users.Columns.Add("Locked");
            users.Columns.Add("LastLogin", typeof(DateTime));
            users.Columns.Add("IsInSharePoint");
            users.Columns.Add("CMITLocation");
            users.Columns.Add("TelephoneNumber");
            users.Columns.Add("CMITTitle");
            users.Columns.Add("Dateofprovisioning", typeof(DateTime));
            users.Columns.Add("NonProviderName");


            // Add additional user data to table
            foreach (DataRow row in users.Rows)
            {
                // remove provider name to get actual user name
                string userName = Utils.DecodeUsername(row["Name"].ToString());
                row["NonProviderName"] = userName;
            }

            int totalRecords = 0;

            foreach (MembershipUser memberuser in Utils.BaseMembershipProvider(site).GetAllUsers(0,100000, out totalRecords))
            {
                bool bFoundMember = false;
                foreach (DataRow row in users.Rows)
                {
                    if (memberuser.UserName.ToLower() == row["NonProviderName"].ToString().ToLower())
                    {
                        SPListItem userItem = web.SiteUserInfoList.GetItemById(Convert.ToInt32(row["ID"]));
                        row["Name"] = memberuser.UserName;
                        row["Active"] = memberuser.IsApproved ? yes : no;
                        row["Locked"] = memberuser.IsLockedOut ? yes : no;
                        row["LastLogin"] = memberuser.LastLoginDate;
                        row["IsInSharePoint"] = yes;
                        row["CMITLocation"] = userItem["CMIT Location"] as string ==null? string.Empty: userItem["CMIT Location"] as string;
                        row["TelephoneNumber"] = userItem["Telephone Number"] as string ==null? string.Empty : userItem["Telephone Number"] as string;
                        row["CMITTitle"] = userItem["CMITTitle"] as string ==null ? string.Empty : userItem["CMITTitle"] as string;
                        row["Dateofprovisioning"] = (userItem["Date of provisioning"] as DateTime?).HasValue ? (userItem["Date of provisioning"] as DateTime?).Value : memberuser.CreationDate;

                        bFoundMember = true;
                        //users.Rows[i].Delete();
                        break;
                    }
                }
                if (!bFoundMember)
                {
                    //Add member to the data table
                    DataRow datanewuser = users.NewRow();
                    datanewuser["Name"] = memberuser.UserName;
                    datanewuser["Email"] = memberuser.Email;
                    datanewuser["Active"] = memberuser.IsApproved ? yes : no;
                    datanewuser["Locked"] = memberuser.IsLockedOut ? yes : no;
                    datanewuser["LastLogin"] = memberuser.LastLoginDate;
                    datanewuser["IsInSharePoint"] = no;
                    users.Rows.Add(datanewuser);
                }
                
            }

            //Remove users that weren't found in SharePoint
            for(int i = users.Rows.Count - 1; i >= 0; i--)
            {
                if (users.Rows[i]["IsInSharePoint"].ToString() != yes && users.Rows[i]["IsInSharePoint"].ToString() != no)
                {
                    users.Rows[i].Delete();
                }
            }

            // sort if a sort expression available
            DataView dataView = new DataView(users);
            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
            }

            //Filter the data if a filter is provided
            if (_owner.SearchText.Length > 0)
            {
                dataView.RowFilter = string.Format("Name LIKE '%{0}%' OR Email LIKE '%{0}%' OR Title LIKE '%{0}%'", _owner.SearchText);
            }
            else
            {
                dataView.RowFilter = "";
            }

            // return as a DataList            
            return (IEnumerable)dataView;
        }