Membership Request Adding fields

Topics: Internet/Extranet Edition
Sep 8, 2008 at 7:25 PM
Edited Sep 8, 2008 at 7:26 PM
First of all awesome project!! Thanks!!

We have FBA installed and working well. Of course there is always something missing.

Is there an easy way to add a field to gather a phone number to the membership request web part?

Developer
Sep 8, 2008 at 10:30 PM
Not an easy way, but it's not too hard either.  You'll have to modify the source code.  The approach depends on whether you're using WSS only or MOSS.  If custom development is an option for you (or you decided to contract with a developer to do it for you), you would need to add the fields to the CreateUserWizard control, and then decide where you want the extra fields stored.  In the ApproveMembership method you can update the data source.  You'd have to also modify pages and web parts where the user data is updated. 

One possiblity it to store the extra field in the User Information List, which is a hidden list on every SharePoint site.  You can see a view of it at http://ServerName/_catalogs/users/simple.aspx but there are lots of gotchas, especially around synchronization of this list with membership changes.  MOSS has a profile database where you would probably want to store this information. 

There are a fair number of code examples out there that could get you started.

We were just discussing this offline, but will probably not release it with the upcoming 1.0 release, as a generic solution is going to be a fair amount of work.

Regards,
Mike Sharp

 

Sep 9, 2008 at 1:26 PM
Thanks for the excellent answer! Understand what the options are and will investigate whether it's worth it.

Good to hear that a generic solution is bing considered.

Developer
Sep 14, 2008 at 10:03 AM
Edited Sep 14, 2008 at 10:07 AM
Hi,
I've faced the same request and modified the code from the newest code set reorganised by Zac sept 7th ish. I opted to mark a field as "Required" in the "User Information List" and capture that in the Sign up. I added a couple of new fields, marked them up as required and my changes capture those. The code checks the user info list and adds them into the signup wizard at runtime.

Its working nicely BUT, as Mike says, we have started a discussion on this but we want to get a stable release 1.0 out before we include this feature. Your input would be most welcome.

Each sharepoint field type needs to be implemented in the code, I've implemented only 3 which match my requirements and even these type like radio boxes versus checkboxes and dropdown lists need to be correctly implemented to match the settings in the User Information List.

I suspect most of the design decisions takes into account the profile abilities in the SQL Provider Vs the User Information list. My implementation met with my needs but for this to be a feature in the next FBA it needs to be optional and or a correct fit for most FBA use.

Take a look at the register new user on http://www.chamberoffers.co.uk/pages/signup.aspx 

Anthony
Sep 15, 2008 at 6:51 PM
Nice work! My 2 cents on what I would like to see is the ability to add different controls to the form similar to what can be done with Microsoft InfoPath. 

I know that may be a lot to ask but it's the perfect scenario.  
Developer
Sep 15, 2008 at 8:46 PM
Edited Sep 16, 2008 at 7:19 AM
vcrocca,

Can you give me an example of what you mean when you say you'd like to add different controls?

Paint the perfect scenario and it might just drive the project that way ;)

Anthony
Developer
Sep 16, 2008 at 1:15 AM
I think what Zac and I were talking about offline was a more generalized approach.  I can think of serveral implementation approaches; some would use a profile provider, others might be based on the existing membership provider and serialize the extra fields into an existing field in the aspnetsqlmembership database. 

I think what we want to avoid are hard-coded extra fields, because it would be difficult to get agreement on what they should be.  Far better to have a configuration page that sets this up in Central Admin.  I'm leaning personally toward a profile provider that can be activated as a feature, and configured in Central Admin based on the web application or site collection.  You could configure either the User Information List or AspNetDB database as the back end persistence store, and if you have MOSS implemented on the farm, it would also be available.  But that's probably for a later release.

Regards,
Mike Sharp

Ps.  Hey Anthony, what's up with all the $0$0$0$0 in your post?  is this an encoding issue with CodePlex?  Are you replying by email or posting directly on the CodePlex site?

Developer
Sep 16, 2008 at 7:28 AM
Edited Sep 16, 2008 at 9:20 AM
Hi mike,

For Serializing extra fields into existing aspnetsqlmembership would mean a db change and implementing code outside the provider to get access to them?

There are no hard coded fields in the code I've needed so far :) Just need a better way to pick the fields and save that as a config somewhere. It's easy to activate that block with a feature in the same way the Membership Approval uses. Storing the info in the User Information List means the data is useable from day one. As far as the provider goes, I understood that we are basically using it to authenticate users. (I don't know what or how we use the role provider which may impact things).

Anthony

PS. Mike, the $0$0$0$0$0 in some posts is caused by Google Chrome! (I love it! but it does have subtle bugs so I use ie to edit them back out when I forget :) )
Sep 16, 2008 at 1:38 PM
Sure. The types of controls I am referring to are:

Text Boxes - For adding fields like phone number or other string based data
Check Boxes - For asking simple yes/no questions
Drop Down List boxes - For providing a drop down for visitors choose from a series of options.

Being able to add and define these fields via web part configuration would be ideal. I believe the ability to add 2 additional text boxes and 2 Drop Down List Boxes and 6 Check boxes should satisfy all scenarios.

Does this help?
Vince
Developer
Sep 16, 2008 at 1:54 PM
Hi Vince, $0$0$0$0Well my changes support most of those, but understand this :) I read the field from the "User Information List" and depending on what Sharepoint Field Type it is I create a matching ASP.NET control. I would like to see all possible Sharepoint Field Types supported, it's not hard I just haven't been back to add in ones yet since I didn't need them yet.  Check boxes and Dropdown lists I've done:)$0$0$0$0$0Whats more important is if we get the data would it suit you to put it inside the "User Information List" i.e each the screen that pops up if you "Edit my profile" on the login drop down.$0$0$0$0$0Anthony$0
Sep 16, 2008 at 3:49 PM
Thanks Anthony! That sounds very promising! Does the latest source code include these features?

Developer
Sep 16, 2008 at 7:59 PM
Vince,

We're focused on a beta 1 for the push. Extra fields is a feature to be developed and added later, although my code is in production.

Anthony
Sep 18, 2008 at 3:11 PM
Hi Anthony, I'm working on a similar requirement but need two separate registrations on the same web application.  I'm going to try and achieve this by having two groups and depending on which group the registration is set to, display the appropriate fields. 

I'm particulary interested in how you go about adding the extra data to the user information list.  I was thinking of getting a handle to the user item from the list, adding the data, then updating it.  This would be after adding the user to the group in MembershipRequestControl.OnCreatingUser.  Are you doing it like or is there a better way?

Thanks
Jade
Developer
Sep 19, 2008 at 1:06 PM
Edited Sep 19, 2008 at 1:08 PM
Hi Jade,

I'm doing the work in the MembershipRequestControl.cs and here it is (I can't check it in as a changeset because its not a generic feature yet). PS. Backup your original file first!

If you mark the fields Required in the User Info List then they will automagically appear and will be saved when the user is created. Its not quite your approach but its a base to build upon. Note that I only implemented enough SPField controls to meet my requirement. More are needed.

In your case, what would be ideal is that each webpart placed on a page has its own unique settings for the fields that it requires. Then you can have a "Silver Membership" with minimum extra fields and a "Gold Membership" with more comprehensive set of fields required.

Also, if you are just adding more information to the User Registration List behind the scenes, this will serve as a partial model for that too.

Enjoy

Anthony

== new version start MembershipRequestControl.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Resources;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using CKS.FormsBasedAuthentication.HIP;
using System.Web.Security;
using System.Collections;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Data;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;

 

namespace CKS.FormsBasedAuthentication
{
    public partial class MembershipRequestControl : CreateUserWizard
    {
        enum CharMix { upper, lower, mix }
       
        #region Fields
        protected string[] _randCharacters = { "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
                "2","3","4","5","6","7","8","9",
                "a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
        private string _HipInstructionsLabelText = string.Empty;
        private string _HipPictureLabelText = string.Empty;
        private string _HipPictureDescription = string.Empty;
        private string _HipCharactersLabelText = string.Empty;
        private string _HipErrorMessage = string.Empty;
        private string _HipResetLabelText = string.Empty;
        private string _FirstNameLabelText = String.Empty;
        private string _LastNameLabelText = string.Empty;
        private string _FirstNameRequiredErrorMessage = String.Empty;
        private string _LastNameRequiredErrorMessage = String.Empty;
        private string _DefaultGroup = string.Empty;
        private List<SPField> customSignupFields = new List<SPField>();
        #endregion
       
        #region Controls
        //HIP controls
        protected ImageHipChallenge imgHip;
        protected HipValidator vldHip;
        protected TextBox txtHip;
        protected Label lblHipPicture;
        protected Label lblHipCharacters;
        protected Label lblHipInstructions;
        protected Label lblHipPictureDescription;
        protected LinkButton lnkHip;
        protected TextBox txtFirstName;
        protected TextBox txtLastName;

        #endregion

        #region Properties
        public string HipInstructionsLabelText
        {
            get { return _HipInstructionsLabelText; }
            set { _HipInstructionsLabelText = value; }
        }

        public string HipPictureLabelText
        {
            get { return _HipPictureLabelText; }
            set { _HipPictureLabelText = value; }
        }

        public string HipPictureDescription
        {
            get { return _HipPictureDescription; }
            set { _HipPictureDescription = value; }
        }

        public string HipCharactersLabelText
        {
            get { return _HipCharactersLabelText; }
            set { _HipCharactersLabelText = value; }
        }

        public string HipErrorMessage
        {
            get { return _HipErrorMessage; }
            set { _HipErrorMessage = value; }
        }

        public string HipResetLabelText
        {
            get { return _HipResetLabelText; }
            set { _HipResetLabelText = value; }
        }
        public string FirstNameLabelText
        {
            get { return _FirstNameLabelText; }
            set { _FirstNameLabelText = value; }
        }

        public string LastNameLabelText
        {
            get { return _LastNameLabelText; }
            set { _LastNameLabelText = value; }
        }

        public string FirstNameRequiredErrorMessage
        {
            get { return _FirstNameRequiredErrorMessage; }
            set { _FirstNameRequiredErrorMessage = value; }
        }

        public string LastNameRequiredErrorMessage
        {
            get { return _LastNameRequiredErrorMessage; }
            set { _LastNameRequiredErrorMessage = value; }
        }

        public string FirstName
        {
            get { return txtFirstName.Text; }
            set { txtFirstName.Text = value; }
        }

        public string LastName
        {
            get { return txtLastName.Text; }
            set { txtLastName.Text = value; }
        }

        public string DefaultGroup
        {//Asumner fixed missing get
            get { return _DefaultGroup; }
            set { _DefaultGroup = value; }
        }

        #endregion       

        #region Rendering Methods
        private Table GetCreateUserTable()
        {
            // Gets a reference to the table
            Table tblResult = null;
            Table outertbl = this.CreateUserStep.ContentTemplateContainer.Controls[0] as Table;
            if (outertbl != null)
            {
                Table innertbl = outertbl.Rows[0].Cells[0].Controls[0] as Table;
                if (innertbl != null)
                {
                    tblResult = innertbl;
                }
            }
            return tblResult;
        }
      
        /// <summary>
        ///     Adds a field and label to the CreateUserWizard control
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="controlName"></param>
        /// <param name="requiredValuePrompt"></param>
        /// <returns></returns>
        private TableRow AddField(string prompt, Control controlToAdd, string requiredValuePrompt)
        {
          
            // Asumner modified to accept other control types not just text
            TableRow tr1 = new TableRow();
            TableCell td1 = new TableCell();
            TableCell td2 = new TableCell();
            Label lblPrompt = new Label();                                

            lblPrompt.Text = prompt;
            lblPrompt.AssociatedControlID = controlToAdd.ID;
            td1.Controls.Add(lblPrompt);
            td1.HorizontalAlign = HorizontalAlign.Right;           
          
            td2.Controls.Add(controlToAdd);
            tr1.Cells.Add(td1);
            tr1.Cells.Add(td2);
            if (requiredValuePrompt != null)
            {
                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ControlToValidate = controlToAdd.ID;
                rfv.ID = "rfv" + controlToAdd.ID;
                rfv.ValidationGroup = this.ID;
                rfv.Text = requiredValuePrompt;
                td2.Controls.Add(rfv);
            }

            return tr1;
        }

        private void AddHipControls()
        {
            Table cuwTable = GetCreateUserTable();
            TableRow tr;
            TableCell td;
            TableCell td2;

            lblHipInstructions = new Label();
            lblHipInstructions.Text = HipInstructionsLabelText;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
           // td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lblHipInstructions);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lblHipPicture = new Label();
            lblHipPicture.Text = HipPictureLabelText;
            StringCollection scWords = new StringCollection();
            string randString = GenerateRandomString(6, CharMix.upper);
            scWords.Add(randString);
            imgHip = new ImageHipChallenge();
            imgHip.ID = "imgHip";
            imgHip.Width = Unit.Pixel(210);
            imgHip.Height = Unit.Pixel(70);
            imgHip.Words = scWords;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipPicture);
            td2.Controls.Add(imgHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lblHipPictureDescription = new Label();
            lblHipPictureDescription.Text = HipPictureDescription;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
           // td2.HorizontalAlign = HorizontalAlign.Center;
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(lblHipPictureDescription);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            txtHip = new TextBox();
            txtHip.ID = "txtHip";
            txtHip.MaxLength = 20;
            lblHipCharacters = new Label();
            lblHipCharacters.Text = HipCharactersLabelText;
            vldHip = new HipValidator();
            vldHip.ID = "vldHip";
            vldHip.Display = ValidatorDisplay.Static;
            vldHip.ControlToValidate = txtHip.ID;
            vldHip.ValidationGroup = this.ID;
            vldHip.HipChallenge = imgHip.ID;
            vldHip.Text = HipErrorMessage;
            vldHip.ErrorMessage = HipErrorMessage;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipCharacters);
            td2.Controls.Add(txtHip);
            td2.Controls.Add(vldHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lnkHip = new LinkButton();
            lnkHip.Click += new EventHandler(lnkHip_Click);
            lnkHip.Text = HipResetLabelText;
            lnkHip.CausesValidation = false;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lnkHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
        }

        private void AddNameFields()
        {
            Table cuwTable = GetCreateUserTable();
            //Add Extra Fields
            txtFirstName = new TextBox();
            txtFirstName.ID = "txtFirstName";
            TableRow tr1 = AddField(FirstNameLabelText, txtFirstName, FirstNameRequiredErrorMessage);

            txtLastName = new TextBox();
            txtLastName.ID = "txtLastName";           
            TableRow tr2 = AddField(LastNameLabelText, txtLastName, LastNameRequiredErrorMessage);
           
            cuwTable.Rows.Add(tr1);
            cuwTable.Rows.Add(tr2);         
        }

        private static Control CreateDropDownListControl(SPFieldChoice userField)
        {
            // To do? work out the default and set it.
            DropDownList newControl = new DropDownList();

            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;

            return newControl;
        }

 

        protected override void CreateControlHierarchy()
        {
           
            base.CreateControlHierarchy();
            AddNameFields();
            AddCustomFields();
            AddHipControls();
            this.CreateUserStep.Title = "";
        }

        private void AddCustomFields()
        {
            Table cuwTable = GetCreateUserTable();

            // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
            // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                {
                    using (SPWeb web = site2.RootWeb)
                    {
                        SPList userlist = web.Lists["User Information List"]; // needs to be multi cultural? or use list GUID?

                        Control newCtrl;
                        TableRow newRow;

                        foreach (SPField userField in userlist.Fields)
                        {
                            if (userField.Required)
                            {
                                switch (userField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        newCtrl = CreateMultiChoiceControl((SPFieldMultiChoice)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;

                                    case SPFieldType.Choice:
                                        newCtrl = CreateDropDownListControl((SPFieldChoice)userField);
                                        newRow = AddField(userField.Title+":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;

                                    case SPFieldType.DateTime:
                                        newCtrl = CreateDateTimeControl((SPFieldDateTime)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null); // Struggling to provide validation!
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                      
                                       
                                        CompareValidator cpv = new CompareValidator();
                                        cpv.ID = "cpv" + userField.StaticName;
                                        cpv.Text = "Please enter a valid date dd/mm/yyyy.";
                                        cpv.ControlToValidate = userField.StaticName + "$" + userField.StaticName+ "Date";
                                        cpv.Type = ValidationDataType.Date;
                                        cpv.Operator = ValidationCompareOperator.DataTypeCheck;
                                        cpv.ValidationGroup = this.ID;
                                        newRow = AddField("", cpv, null);
                                        cuwTable.Rows.Add(newRow);
                                        break;
                                }
                            }
                        }
                    }
                }
            });
        }

        private static Control CreateMultiChoiceControl(SPFieldMultiChoice userField)
        {
            // To do? work out the default and set it.
            CheckBoxList newControl = new CheckBoxList();

            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;
     
            return newControl;
        }

        private static Control CreateDateTimeControl(SPFieldDateTime spDateTime)
        {
            // To do? work out the default and set it.
            DateTimeControl newControl = new DateTimeControl();
          
            newControl.ID = spDateTime.StaticName;
            if (spDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
            {
                newControl.DateOnly = true;
            }
            else
            {
                // accept time as well?
                newControl.DateOnly = false;              
            }
            newControl.LocaleId = (int)SPContext.Current.RegionalSettings.LocaleId;
            newControl.ErrorMessage = "Please enter a valid date.";
            newControl.IsRequiredField = true;
            newControl.ClearSelection();                    
            return newControl;
        }

        protected override void OnCreatingUser(LoginCancelEventArgs e)
        {           
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] != null)
            {
                /* bms Prevent user from being added to the list multiple times if the user */
                /* is already in use.                                                       */
                if (Membership.GetUser(this.UserName) == null)
                {
                    MembershipRequest request = new MembershipRequest();
                    request.UserEmail = this.Email;
                    request.UserName = this.UserName;
                    request.PasswordQuestion = this.Question;
                    request.PasswordAnswer = this.Answer;
                    request.FirstName = this.FirstName;
                    request.LastName = this.LastName;
                    request.DefaultGroup = this._DefaultGroup;
                    MembershipRequest.CopyToReviewList(request);
                }
                this.MoveTo(this.CompleteStep);
               
            }
            else
            {
                base.OnCreatingUser(e);
                //Add the user to the default group
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {
                        using (SPWeb web = site2.RootWeb)
                        {
                            web.AllowUnsafeUpdates = true;
                            web.Groups[this._DefaultGroup].AddUser(string.Format("{0}:{1}", System.Web.Security.Membership.Provider.Name.ToLower(), this.UserName.ToLower()), this.Email, this.FirstName + " " + this.LastName, "Self Registration");
                            web.Update();
                        }
                    }
                });
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected override void OnCreatedUser(EventArgs e)
        {
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] == null)
            {
                #region Process new user request if we're NOT using the Request List
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original Site even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {                       
                        using (SPWeb web = site2.RootWeb)
                        {
                            // from this point allowunsafeupdates is required because the call is initiated from a browser with
                            // anonymouse rights only
                            web.AllowUnsafeUpdates = true;

                            MembershipRequest request = new MembershipRequest();
                            request.UserEmail = this.Email;
                            request.UserName = this.UserName;
                            if (System.Web.Security.Membership.RequiresQuestionAndAnswer)
                            {
                                request.PasswordQuestion = this.Question;
                                request.PasswordAnswer = this.Answer;
                            }
                            request.FirstName = this.FirstName;
                            request.LastName = this.LastName;
                            request.SiteName = web.Title;
                            request.SiteURL = web.Url;
                            request.ChangePasswordURL = string.Format("{0}/{1}", web.Url, web.Properties[MembershipReviewSiteURL.CHANGEPASSWORDPAGE]);
                            request.DefaultGroup = this.DefaultGroup;
                            // Asumner fixed this
                            request.LoginCreatedUser = LoginCreatedUser;

                            MembershipRequest.ApproveMembership(request, web);

                           

                            #region Update any custom "User List Information" fields
                            // Asumner Custom Fields handling

                          

                            // we use the localized name, safe for non-English SharePoint servers
                            SPList userInfoList = site2.RootWeb.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];
                            // get site details                             
                            SPIisSettings settings = Utils.GetFBAIisSettings(site2);
                            // Find the table
                            Table cuwTable = GetCreateUserTable();

                           
                            foreach (SPField customSignupField in customSignupFields)
                            {
                                // Get the user record                                                            
                                SPUser user = site2.RootWeb.AllUsers[settings.MembershipProvider.ToString() + ":" + this.UserName];
                                SPListItem userProfileItem = userInfoList.GetItemById(user.ID);                               
                               
                                // grab matching customfield
                                Control customFieldControl = cuwTable.FindControl(customSignupField.StaticName);
                                // for each data type work out what it is so we know how to
                                // get its value, then update the users profile
                                switch (customSignupField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        CheckBoxList checkBoxList = (CheckBoxList)customFieldControl;
                                        SPFieldMultiChoiceValue chosen = new SPFieldMultiChoiceValue();
                                        foreach (ListItem item in checkBoxList.Items)
                                        {
                                            if (item.Selected)
                                            {
                                                chosen.Add(item.Value);
                                            }
                                        }

                                        userProfileItem[customSignupField.StaticName] = chosen;
                                        userProfileItem.Update();
                                        break;

                                    case SPFieldType.Choice:
                                        DropDownList dropDown = (DropDownList)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = dropDown.SelectedValue.ToString();
                                        userProfileItem.Update();
                                        break;

                                    case SPFieldType.DateTime:
                                        DateTimeControl dateTime = (DateTimeControl)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = DateTime.Parse(dateTime.SelectedDate.ToLongDateString());
                                        userProfileItem.Update();
                                        break;
                                }
                            }

                            // redundant since thise code is about to be disposed?
                            web.AllowUnsafeUpdates = false;
                            #endregion

                            this.MoveTo(this.CompleteStep);
                        }
                    }
                });
                #endregion
            }
            else
            {
                base.OnCreatedUser(e);

               
            }
        }
        
        #endregion

        #region Events
        void lnkHip_Click(object sender, EventArgs e)
        {
            //Nothing to do, the image will reset automatically
        }
        #endregion

        private string GenerateRandomString(int NumAlphs, CharMix Mix)
        {
            Random rGen = new Random();

            int iMix = (int)Mix;

            int p = 0;
            string sPass = "";
            int iCharMax = 32;
            if (iMix > 0) iCharMax = 55;
            for (int x = 0; x < NumAlphs; x++)
            {
                p = rGen.Next(0, iCharMax);
                sPass += _randCharacters[p];
            }
            if (iMix < 1)
            {
                sPass = sPass.ToUpper();
            }
            else if (iMix < 2)
            {
                sPass = sPass.ToLower();
            }
            return sPass;
        }
       
        protected override void OnContinueButtonClick(EventArgs e)
        {
            base.OnContinueButtonClick(e);
          
            HttpContext.Current.Response.Redirect(FinishDestinationPageUrl);
         
        }
    }
}

== new version

Sep 22, 2008 at 9:13 AM
Anthony, many thanks for posting your code.  I'm fairly new to .Net and MOSS so it is a great help.

Jade
Sep 29, 2008 at 2:54 PM
What I need in my specific case is this:

Users of the company's worldwide intranet choose (from a dropdown or whatever of 7 choices) which location they work at. This information has to be stored in a plce where I can then create Audiences based on this data. So, after the user is in an Audience, he then is able to see one of the seven "My Location" sites existing in the intranet. He can there see information for his work place.

Regards,
Magganpice
Developer
Sep 29, 2008 at 5:59 PM
Magganpice,$0$0$0$0Drop in the code above in the MembershipRequestControl.cs (take a backup!) and then make a new field "Required" in the "User Information List" and the new field should pop up in the sign up. - Anthony$0
Sep 30, 2008 at 3:18 PM
Anthony,

I had a look at that site you mentioned (http://www.chamberoffers.co.uk/pages/signup.aspx)

Does your implementation save those additional fields in a place where you can create a SharePoint Audience based on them - like for instance a "Shopping Audience"? I will be trying this code as soon as I've gathered enough courage :-)

Magganpice
Sep 30, 2008 at 4:24 PM
Anthony,

This may be a stupid question: where is the "User Info List" you mention? Where would I create those additional required fields, so that they pop up in the membership request webpart? I tried Site Membership Review List but nothing seemed to change...

Magganpice
Developer
Sep 30, 2008 at 4:32 PM
Hi, People & Groups when you go into the list settings (where you add new fields) you will see its called "User Information List" try  /_layouts/listedit.aspx?List=1a9b4d86-b491-4833-813b-de96178e6508  - Anthony
Developer
Sep 30, 2008 at 5:09 PM
The list itself is located at:  /_catalogs/users

...in case you want to do things other than what you can do with listedit.aspx, open SharePoint Designer and you can navigate to it.

Regards,
Mike Sharp
Oct 1, 2008 at 9:11 AM
OK, I found the list, adding a new field (using your code above) works - at least for registration.

Do I understand right, the information in "User Info List" does not write anything into the user profiles we see in the SSP - so we can't create Audiences based on the information the user enters when registring...? Is this due to the stuff I removed from the "SaveButtonTemplate" - would the code in MySettings have synchronized the data with the "real" user profile?

Magganpice
Developer
Oct 1, 2008 at 10:37 AM
Hi Magganpice,

Making a field "required" (of the field types I've built in support for) makes the field appear at registration. The data is written back to the User Information List. The "real" information is the User Information List. The SQL based FBA is only used to authenticate the user and has no other data in the table.

Hopefully you have seen your new data populated inside the User Information List. As for the SSP, I don't know what it is, if its in MOSS. There are MOSS user Sync tools out there but I've no idea what they are used for. For as long as I can get away with it I don't intend to use MOSS, simply because the costs are too high, so I doubt I'm the right person to comment on this bit :)

Anthony
Oct 1, 2008 at 11:29 AM
Well, in MOSS, the real real users are stored in user profiles in the SSP (Shared Services Provider) which is not included in WSS. Audiences is therefore also a MOSS feature, not available in WSS. I cannot create an audience based on the "User Info List".

I guess I will have to write my own code in MembershipRequestControl that creates user profiles in the SSP, so as to be able to use audience targeting.
Developer
Oct 1, 2008 at 11:37 AM
Thats why this thread is talking about creating a generic approach, a provider model I guess. - Anthony
Oct 2, 2008 at 7:54 AM
An small bit of information that would have saved me some hours:

What I decided to do was add an ItemAdded EventHandler to the User Information List. So that I don't have my custom code mixed in the FBA code (except that I'm using Anthony's code for MembershipRequestControl.cs). The EventHandler would Create a User Profile in the SSP and update some properties when a user requests FBA membership. I tested my code, it worked. But used as an EventHandler, the code was never exectued. No errors appeared.

The problem is (also seen on other discussion boards): the ItemAdded event is not fired on the User Information List!

I changed it to ItemUpdated - and now it works fine. Don't forget to run the code with elevated privileges.
Oct 10, 2008 at 9:35 AM
My 2 cents on this...

you can instantiate the User Information List this way in order to avoid language issues.

SPList userInformationList = SPContext.Current.Web.SiteUserInfoList; 

I'm trying to extend this solution by modifying MembershipRequest.cs so you don't need any eventhandler to pass the custom parameters to the sharepoint user. If any of you guys think it might be of your interest, I can post the changes later.
Developer
Oct 10, 2008 at 9:48 AM
Hi davidmartos,

Thanks for the SiteUserInfo list tip!

I'll gladly consider integrating any code since adding custom fields is a useful feature.

Anthony
Oct 10, 2008 at 11:05 AM
Hi Anthony,

I finally got it to work. I've done some changes on MembershipRequest.cs, MembershipRequestControl.cs and MembershipReviewHandler.cs.  I can post the changes on my blog but, as it's part of CKS I don't know if there is any problem on that. I can also send you the files is you give me your contact details.

David
Oct 10, 2008 at 6:05 PM

Hi,

I've posted my changes here http://david-martos.blogspot.com/2008/10/adding-custom-fields-to-user-profiles.html just in case anyone is interested. Of course it is not fully tested and, if its useful, I'll be glad to download the next CKS release with something similar to it ;)

Thanks Anthony

David

Developer
Oct 10, 2008 at 8:48 PM

Thank you David!

Great post!

Anthony

From: davidmartos [mailto:notifications@codeplex.com]
Sent: 10 October 2008 19:06
To: Anthony Sumner .PLANETWEB
Subject: Re: Membership Request Adding fields [CKS:35189]

From: davidmartos

Hi,

I've posted my changes here http://david-martos.blogspot.com/2008/10/adding-custom-fields-to-user-profiles.html just in case anyone is interested. Of course it is not fully tested and, if its useful, I'll be glad to download the next CKS release with something similar to it ;)

Thanks Anthony

David

Read the full discussion online.

To add a post to this discussion, reply to this email (CKS@discussions.codeplex.com)

To start a new discussion for this project, email CKS@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe or change your settings on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com

Oct 21, 2008 at 6:38 PM
Hi,
I want to add fields to the membership request web part, but I am having troubles adding a new field to the user information list.  I can see the list when i go to /_catalogs/users/simple.aspx but I don't see the settings button to add a field to the list.  I also tried  /_layouts/listedit.aspx?List=1a9b4d86-b491-4833-813b-de96178e6508, I just get an error saying that the list dosn't exist.  I can navigate to where the list is in SPD but I don't see how to add a field to the list there.  I am logged in a the site collection admin.  Am I missing something here? 

Mark
Developer
Oct 21, 2008 at 8:40 PM
You can add columns by going to People and Groups, the click All People.  Then you can go to the list settings and add columns, views and whatnot.  In my case, the list is accessible at:

/_layouts/ListEdit.aspx?List=%7BBB92A991%2D0E64%2D4174%2DA308%2D2B59DD69BD3B%7D


Regards,
Mike Sharp
Oct 22, 2008 at 5:46 PM
All good now,

thanks Mike

Mark
Apr 3, 2009 at 12:35 AM
hi,

I am also needing to add some custom columns in the user profile. However, am not using the membership register part. I am using the 'New User' function in the 'FBA User Management' section to add my users.
I have added my custom columns in the 'user information list' and made them required fields. The fields are 3 text boxes and 1 check box field. My problem now is: How do I modify the 'usernew.cs, useredit.cs and userdisp.cs' so that these fields are included in the add 'New User' page so that these info can be saved to user profiles when the users are created and I can also edit them if i need via 'edit item' from the user management section.
Am also new to coding... i have been staring at the usernew.cs and have no idea where to start... any help would be much appreciated.

Thank you.

Bing
Nov 2, 2009 at 7:01 AM

Hi Antony,
Many thanks for the membershipRequestControl.cs.  As I need to add text field form, I have added text form in your code.

The custom text form is show up in the registration but not updated in the list after summit. I am new to .net.

Please kindly advice. Here is the code...

Many thanks...

Ja

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Resources;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using CKS.FormsBasedAuthentication.HIP;
using System.Web.Security;
using System.Collections;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Data;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;



namespace CKS.FormsBasedAuthentication
{
    public partial class MembershipRequestControl : CreateUserWizard
    {
        enum CharMix { upper, lower, mix }

        #region Fields
        protected string[] _randCharacters = { "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
                "2","3","4","5","6","7","8","9",
                "a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
        private string _HipInstructionsLabelText = string.Empty;
        private string _HipPictureLabelText = string.Empty;
        private string _HipPictureDescription = string.Empty;
        private string _HipCharactersLabelText = string.Empty;
        private string _HipErrorMessage = string.Empty;
        private string _HipResetLabelText = string.Empty;
        private string _FirstNameLabelText = String.Empty;
        private string _LastNameLabelText = string.Empty;
        private string _FirstNameRequiredErrorMessage = String.Empty;
        private string _LastNameRequiredErrorMessage = String.Empty;
        private string _DefaultGroup = string.Empty;
        private List customSignupFields = new List();
        #endregion

        #region Controls
        //HIP controls
        protected ImageHipChallenge imgHip;
        protected HipValidator vldHip;
        protected TextBox txtHip;
        protected Label lblHipPicture;
        protected Label lblHipCharacters;
        protected Label lblHipInstructions;
        protected Label lblHipPictureDescription;
        protected LinkButton lnkHip;
        protected TextBox txtFirstName;
        protected TextBox txtLastName;

        #endregion

        #region Properties
        public string HipInstructionsLabelText
        {
            get { return _HipInstructionsLabelText; }
            set { _HipInstructionsLabelText = value; }
        }

        public string HipPictureLabelText
        {
            get { return _HipPictureLabelText; }
            set { _HipPictureLabelText = value; }
        }

        public string HipPictureDescription
        {
            get { return _HipPictureDescription; }
            set { _HipPictureDescription = value; }
        }

        public string HipCharactersLabelText
        {
            get { return _HipCharactersLabelText; }
            set { _HipCharactersLabelText = value; }
        }

        public string HipErrorMessage
        {
            get { return _HipErrorMessage; }
            set { _HipErrorMessage = value; }
        }

        public string HipResetLabelText
        {
            get { return _HipResetLabelText; }
            set { _HipResetLabelText = value; }
        }
        public string FirstNameLabelText
        {
            get { return _FirstNameLabelText; }
            set { _FirstNameLabelText = value; }
        }

        public string LastNameLabelText
        {
            get { return _LastNameLabelText; }
            set { _LastNameLabelText = value; }
        }

        public string FirstNameRequiredErrorMessage
        {
            get { return _FirstNameRequiredErrorMessage; }
            set { _FirstNameRequiredErrorMessage = value; }
        }

        public string LastNameRequiredErrorMessage
        {
            get { return _LastNameRequiredErrorMessage; }
            set { _LastNameRequiredErrorMessage = value; }
        }

        public string FirstName
        {
            get { return txtFirstName.Text; }
            set { txtFirstName.Text = value; }
        }

        public string LastName
        {
            get { return txtLastName.Text; }
            set { txtLastName.Text = value; }
        }

        public string DefaultGroup
        {//Asumner fixed missing get
            get { return _DefaultGroup; }
            set { _DefaultGroup = value; }
        }

        #endregion

        #region Rendering Methods
        private Table GetCreateUserTable()
        {
            // Gets a reference to the table
            Table tblResult = null;
            Table outertbl = this.CreateUserStep.ContentTemplateContainer.Controls[0] as Table;
            if (outertbl != null)
            {
                Table innertbl = outertbl.Rows[0].Cells[0].Controls[0] as Table;
                if (innertbl != null)
                {
                    tblResult = innertbl;
                }
            }
            return tblResult;
        }

        /// 
        ///     Adds a field and label to the CreateUserWizard control
        /// 
        /// <param name="prompt" />
        /// <param name="controlName" />
        /// <param name="requiredValuePrompt" />
        /// 
        private TableRow AddField(string prompt, Control controlToAdd, string requiredValuePrompt)
        {

            // Asumner modified to accept other control types not just text
            TableRow tr1 = new TableRow();
            TableCell td1 = new TableCell();
            TableCell td2 = new TableCell();
            Label lblPrompt = new Label();

            lblPrompt.Text = prompt;
            lblPrompt.AssociatedControlID = controlToAdd.ID;
            td1.Controls.Add(lblPrompt);
            td1.HorizontalAlign = HorizontalAlign.Right;

            td2.Controls.Add(controlToAdd);
            tr1.Cells.Add(td1);
            tr1.Cells.Add(td2);
            if (requiredValuePrompt != null)
            {
                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ControlToValidate = controlToAdd.ID;
                rfv.ID = "rfv" + controlToAdd.ID;
                rfv.ValidationGroup = this.ID;
                rfv.Text = requiredValuePrompt;
                td2.Controls.Add(rfv);
            }

            return tr1;
        }

        private void AddHipControls()
        {
            Table cuwTable = GetCreateUserTable();
            TableRow tr;
            TableCell td;
            TableCell td2;

            lblHipInstructions = new Label();
            lblHipInstructions.Text = HipInstructionsLabelText;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            // td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lblHipInstructions);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lblHipPicture = new Label();
            lblHipPicture.Text = HipPictureLabelText;
            StringCollection scWords = new StringCollection();
            string randString = GenerateRandomString(6, CharMix.upper);
            scWords.Add(randString);
            imgHip = new ImageHipChallenge();
            imgHip.ID = "imgHip";
            imgHip.Width = Unit.Pixel(210);
            imgHip.Height = Unit.Pixel(70);
            imgHip.Words = scWords;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipPicture);
            td2.Controls.Add(imgHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lblHipPictureDescription = new Label();
            lblHipPictureDescription.Text = HipPictureDescription;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            // td2.HorizontalAlign = HorizontalAlign.Center;
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(lblHipPictureDescription);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            txtHip = new TextBox();
            txtHip.ID = "txtHip";
            txtHip.MaxLength = 20;
            lblHipCharacters = new Label();
            lblHipCharacters.Text = HipCharactersLabelText;
            vldHip = new HipValidator();
            vldHip.ID = "vldHip";
            vldHip.Display = ValidatorDisplay.Static;
            vldHip.ControlToValidate = txtHip.ID;
            vldHip.ValidationGroup = this.ID;
            vldHip.HipChallenge = imgHip.ID;
            vldHip.Text = HipErrorMessage;
            vldHip.ErrorMessage = HipErrorMessage;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipCharacters);
            td2.Controls.Add(txtHip);
            td2.Controls.Add(vldHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);

            lnkHip = new LinkButton();
            lnkHip.Click += new EventHandler(lnkHip_Click);
            lnkHip.Text = HipResetLabelText;
            lnkHip.CausesValidation = false;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lnkHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
        }

        private void AddNameFields()
        {
            Table cuwTable = GetCreateUserTable();
            //Add Extra Fields
            txtFirstName = new TextBox();
            txtFirstName.ID = "txtFirstName";
            TableRow tr1 = AddField(FirstNameLabelText, txtFirstName, FirstNameRequiredErrorMessage);

            txtLastName = new TextBox();
            txtLastName.ID = "txtLastName";
            TableRow tr2 = AddField(LastNameLabelText, txtLastName, LastNameRequiredErrorMessage);

            cuwTable.Rows.Add(tr1);
            cuwTable.Rows.Add(tr2);
        }

        private static Control CreateDropDownListControl(SPFieldChoice userField)
        {
            // To do? work out the default and set it.
            DropDownList newControl = new DropDownList();

            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;

            return newControl;
        }



        protected override void CreateControlHierarchy()
        {

            base.CreateControlHierarchy();
            AddNameFields();
            AddCustomFields();
            AddHipControls();
            this.CreateUserStep.Title = "";
        }

        private void AddCustomFields()
        {
            Table cuwTable = GetCreateUserTable();

            // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
            // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                {
                    using (SPWeb web = site2.RootWeb)
                    {
                        SPList userlist = web.Lists["User Information List"]; // needs to be multi cultural? or use list GUID?

                        Control newCtrl;
                        TableRow newRow;

                        foreach (SPField userField in userlist.Fields)
                        {
                            if (userField.Required)
                            {
                                switch (userField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        newCtrl = CreateMultiChoiceControl((SPFieldMultiChoice)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;

                                    case SPFieldType.Choice:
                                        newCtrl = CreateDropDownListControl((SPFieldChoice)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;

                                    case SPFieldType.DateTime:
                                        newCtrl = CreateDateTimeControl((SPFieldDateTime)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null); // Struggling to provide validation!
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);


                                        CompareValidator cpv = new CompareValidator();
                                        cpv.ID = "cpv" + userField.StaticName;
                                        cpv.Text = "Please enter a valid date dd/mm/yyyy.";
                                        cpv.ControlToValidate = userField.StaticName + "$" + userField.StaticName + "Date";
                                        cpv.Type = ValidationDataType.Date;
                                        cpv.Operator = ValidationCompareOperator.DataTypeCheck;
                                        cpv.ValidationGroup = this.ID;
                                        newRow = AddField("", cpv, null);
                                        cuwTable.Rows.Add(newRow);
                                        break;

                                    case SPFieldType.Text:
                                        newCtrl = CreateTextControl((SPFieldText)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;
                                }
                            }
                        }
                    }
                }
            });
        }

        private static Control CreateMultiChoiceControl(SPFieldMultiChoice userField)
        {
            // To do? work out the default and set it.
            CheckBoxList newControl = new CheckBoxList();

            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;

            return newControl;
        }

        private static Control CreateDateTimeControl(SPFieldDateTime spDateTime)
        {
            // To do? work out the default and set it.
            DateTimeControl newControl = new DateTimeControl();

            newControl.ID = spDateTime.StaticName;
            if (spDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
            {
                newControl.DateOnly = true;
            }
            else
            {
                // accept time as well? 
                newControl.DateOnly = false;
            }
            newControl.LocaleId = (int)SPContext.Current.RegionalSettings.LocaleId;
            newControl.ErrorMessage = "Please enter a valid date.";
            newControl.IsRequiredField = true;
            newControl.ClearSelection();
            return newControl;
        }
        private static Control CreateTextControl(SPFieldText userField)
        {
            // To do? work out the default and set it.
            //TextField newControl = new TextField();
            TextBox newControl = new TextBox();
            newControl.ID = userField.StaticName;
            return newControl;
        }
        protected override void OnCreatingUser(LoginCancelEventArgs e)
        {
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] != null)
            {
                /* bms Prevent user from being added to the list multiple times if the user */
                /* is already in use.                                                       */
                if (Membership.GetUser(this.UserName) == null)
                {
                    MembershipRequest request = new MembershipRequest();
                    request.UserEmail = this.Email;
                    request.UserName = this.UserName;
                    request.PasswordQuestion = this.Question;
                    request.PasswordAnswer = this.Answer;
                    request.FirstName = this.FirstName;
                    request.LastName = this.LastName;
                    request.DefaultGroup = this._DefaultGroup;
                    MembershipRequest.CopyToReviewList(request);
                }
                this.MoveTo(this.CompleteStep);

            }
            else
            {
                base.OnCreatingUser(e);
                //Add the user to the default group
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {
                        using (SPWeb web = site2.RootWeb)
                        {
                            web.AllowUnsafeUpdates = true;
                            web.Groups[this._DefaultGroup].AddUser(string.Format("{0}:{1}", System.Web.Security.Membership.Provider.Name.ToLower(), this.UserName.ToLower()), this.Email, this.FirstName + " " + this.LastName, "Self Registration");
                            web.Update();
                        }
                    }
                });
            }
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected override void OnCreatedUser(EventArgs e)
        {
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] == null)
            {
                #region Process new user request if we're NOT using the Request List
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original Site even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {
                        using (SPWeb web = site2.RootWeb)
                        {
                            // from this point allowunsafeupdates is required because the call is initiated from a browser with
                            // anonymouse rights only
                            web.AllowUnsafeUpdates = true;

                            MembershipRequest request = new MembershipRequest();
                            request.UserEmail = this.Email;
                            request.UserName = this.UserName;
                            if (System.Web.Security.Membership.RequiresQuestionAndAnswer)
                            {
                                request.PasswordQuestion = this.Question;
                                request.PasswordAnswer = this.Answer;
                            }
                            request.FirstName = this.FirstName;
                            request.LastName = this.LastName;
                            request.SiteName = web.Title;
                            request.SiteURL = web.Url;
                            request.ChangePasswordURL = string.Format("{0}/{1}", web.Url, web.Properties[MembershipReviewSiteURL.CHANGEPASSWORDPAGE]);
                            request.DefaultGroup = this.DefaultGroup;
                            // Asumner fixed this
                            request.LoginCreatedUser = LoginCreatedUser;

                            MembershipRequest.ApproveMembership(request, web);



                            #region Update any custom "User List Information" fields
                            // Asumner Custom Fields handling



                            // we use the localized name, safe for non-English SharePoint servers
                            SPList userInfoList = site2.RootWeb.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];
                            // get site details                              
                            SPIisSettings settings = Utils.GetFBAIisSettings(site2);
                            // Find the table
                            Table cuwTable = GetCreateUserTable();


                            foreach (SPField customSignupField in customSignupFields)
                            {
                                // Get the user record                                                             
                                SPUser user = site2.RootWeb.AllUsers[settings.MembershipProvider.ToString() + ":" + this.UserName];
                                SPListItem userProfileItem = userInfoList.GetItemById(user.ID);

                                // grab matching customfield
                                Control customFieldControl = cuwTable.FindControl(customSignupField.StaticName);
                                // for each data type work out what it is so we know how to
                                // get its value, then update the users profile
                                switch (customSignupField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        CheckBoxList checkBoxList = (CheckBoxList)customFieldControl;
                                        SPFieldMultiChoiceValue chosen = new SPFieldMultiChoiceValue();
                                        foreach (ListItem item in checkBoxList.Items)
                                        {
                                            if (item.Selected)
                                            {
                                                chosen.Add(item.Value);
                                            }
                                        }

                                        userProfileItem[customSignupField.StaticName] = chosen;
                                        userProfileItem.Update();
                                        break;

                                    case SPFieldType.Choice:
                                        DropDownList dropDown = (DropDownList)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = dropDown.SelectedValue.ToString();
                                        userProfileItem.Update();
                                        break;

                                    case SPFieldType.DateTime:
                                        DateTimeControl dateTime = (DateTimeControl)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = DateTime.Parse(dateTime.SelectedDate.ToLongDateString());
                                        userProfileItem.Update();
                                        break;
                                        
                                   case SPFieldType.Text:
                                       TextBox textBox = (TextBox)customFieldControl;
                                       userProfileItem[customSignupField.StaticName] = textBox.Text;
                                       userProfileItem.Update();
                                       break;
                                }
                            }

                            // redundant since thise code is about to be disposed?
                            web.AllowUnsafeUpdates = false;
                            #endregion

                            this.MoveTo(this.CompleteStep);
                        }
                    }
                });
                #endregion
            }
            else
            {
                base.OnCreatedUser(e);


            }
        }

        #endregion

        #region Events
        void lnkHip_Click(object sender, EventArgs e)
        {
            //Nothing to do, the image will reset automatically
        }
        #endregion

        private string GenerateRandomString(int NumAlphs, CharMix Mix)
        {
            Random rGen = new Random();

            int iMix = (int)Mix;

            int p = 0;
            string sPass = "";
            int iCharMax = 32;
            if (iMix > 0) iCharMax = 55;
            for (int x = 0; x < NumAlphs; x++)
            {
                p = rGen.Next(0, iCharMax);
                sPass += _randCharacters[p];
            }
            if (iMix < 1)
            {
                sPass = sPass.ToUpper();
            }
            else if (iMix < 2)
            {
                sPass = sPass.ToLower();
            }
            return sPass;
        }

        protected override void OnContinueButtonClick(EventArgs e)
        {
            base.OnContinueButtonClick(e);

            HttpContext.Current.Response.Redirect(FinishDestinationPageUrl);

        }
    }
}
Developer
Nov 2, 2009 at 9:25 AM

Hi,

Sorry I’m too busy, but track down a codeplex user called “kevon”, he has recently been updating the same code for his own use too!, Hopefully he can share his changes.

Anthony


Anthony Sumner
Director

black



Phone:
Fax:

0845 122 7181
0870 1673883

Email:
Website:

asumner@planetweb.co.uk
www.planetweb.co.uk


From: sengja [mailto:notifications@codeplex.com]
Sent: 02 November 2009 08:02
To: Anthony Sumner
Subject: Re: Membership Request Adding fields [CKS:35189]

From: sengja

Hi Antony,
Many thanks for the membershipRequestControl.cs. As I need to add text field form, I have added text form in your code.

The custom text form is show up in the registration but not updated in the list after summit. I am new to .net.

Please kindly advice. Here is the code...

Many thanks...

Ja

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Resources;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using CKS.FormsBasedAuthentication.HIP;
using System.Web.Security;
using System.Collections;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Data;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
 
 
 
namespace CKS.FormsBasedAuthentication
{
    public partial class MembershipRequestControl : CreateUserWizard
    {
        enum CharMix { upper, lower, mix }
 
        #region Fields
        protected string[] _randCharacters = { "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
                "2","3","4","5","6","7","8","9",
                "a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
        private string _HipInstructionsLabelText = string.Empty;
        private string _HipPictureLabelText = string.Empty;
        private string _HipPictureDescription = string.Empty;
        private string _HipCharactersLabelText = string.Empty;
        private string _HipErrorMessage = string.Empty;
        private string _HipResetLabelText = string.Empty;
        private string _FirstNameLabelText = String.Empty;
        private string _LastNameLabelText = string.Empty;
        private string _FirstNameRequiredErrorMessage = String.Empty;
        private string _LastNameRequiredErrorMessage = String.Empty;
        private string _DefaultGroup = string.Empty;
        private List customSignupFields = new List();
        #endregion
 
        #region Controls
        //HIP controls
        protected ImageHipChallenge imgHip;
        protected HipValidator vldHip;
        protected TextBox txtHip;
        protected Label lblHipPicture;
        protected Label lblHipCharacters;
        protected Label lblHipInstructions;
        protected Label lblHipPictureDescription;
        protected LinkButton lnkHip;
        protected TextBox txtFirstName;
        protected TextBox txtLastName;
 
        #endregion
 
        #region Properties
        public string HipInstructionsLabelText
        {
            get { return _HipInstructionsLabelText; }
            set { _HipInstructionsLabelText = value; }
        }
 
        public string HipPictureLabelText
        {
            get { return _HipPictureLabelText; }
            set { _HipPictureLabelText = value; }
        }
 
        public string HipPictureDescription
        {
            get { return _HipPictureDescription; }
            set { _HipPictureDescription = value; }
        }
 
        public string HipCharactersLabelText
        {
            get { return _HipCharactersLabelText; }
            set { _HipCharactersLabelText = value; }
        }
 
        public string HipErrorMessage
        {
            get { return _HipErrorMessage; }
            set { _HipErrorMessage = value; }
        }
 
        public string HipResetLabelText
        {
            get { return _HipResetLabelText; }
            set { _HipResetLabelText = value; }
        }
        public string FirstNameLabelText
        {
            get { return _FirstNameLabelText; }
            set { _FirstNameLabelText = value; }
        }
 
        public string LastNameLabelText
        {
            get { return _LastNameLabelText; }
            set { _LastNameLabelText = value; }
        }
 
        public string FirstNameRequiredErrorMessage
        {
            get { return _FirstNameRequiredErrorMessage; }
            set { _FirstNameRequiredErrorMessage = value; }
        }
 
        public string LastNameRequiredErrorMessage
        {
            get { return _LastNameRequiredErrorMessage; }
            set { _LastNameRequiredErrorMessage = value; }
        }
 
        public string FirstName
        {
            get { return txtFirstName.Text; }
            set { txtFirstName.Text = value; }
        }
 
        public string LastName
        {
            get { return txtLastName.Text; }
            set { txtLastName.Text = value; }
        }
 
        public string DefaultGroup
        {//Asumner fixed missing get
            get { return _DefaultGroup; }
            set { _DefaultGroup = value; }
        }
 
        #endregion
 
        #region Rendering Methods
        private Table GetCreateUserTable()
        {
            // Gets a reference to the table
            Table tblResult = null;
            Table outertbl = this.CreateUserStep.ContentTemplateContainer.Controls[0] as Table;
            if (outertbl != null)
            {
                Table innertbl = outertbl.Rows[0].Cells[0].Controls[0] as Table;
                if (innertbl != null)
                {
                    tblResult = innertbl;
                }
            }
            return tblResult;
        }
 
        /// 
        ///     Adds a field and label to the CreateUserWizard control
        /// 
        /// <param name="prompt" />
        /// <param name="controlName" />
        /// <param name="requiredValuePrompt" />
        /// 
        private TableRow AddField(string prompt, Control controlToAdd, string requiredValuePrompt)
        {
 
            // Asumner modified to accept other control types not just text
            TableRow tr1 = new TableRow();
            TableCell td1 = new TableCell();
            TableCell td2 = new TableCell();
            Label lblPrompt = new Label();
 
            lblPrompt.Text = prompt;
            lblPrompt.AssociatedControlID = controlToAdd.ID;
            td1.Controls.Add(lblPrompt);
            td1.HorizontalAlign = HorizontalAlign.Right;
 
            td2.Controls.Add(controlToAdd);
            tr1.Cells.Add(td1);
            tr1.Cells.Add(td2);
            if (requiredValuePrompt != null)
            {
                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ControlToValidate = controlToAdd.ID;
                rfv.ID = "rfv" + controlToAdd.ID;
                rfv.ValidationGroup = this.ID;
                rfv.Text = requiredValuePrompt;
                td2.Controls.Add(rfv);
            }
 
            return tr1;
        }
 
        private void AddHipControls()
        {
            Table cuwTable = GetCreateUserTable();
            TableRow tr;
            TableCell td;
            TableCell td2;
 
            lblHipInstructions = new Label();
            lblHipInstructions.Text = HipInstructionsLabelText;
 
            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            // td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lblHipInstructions);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
 
            lblHipPicture = new Label();
            lblHipPicture.Text = HipPictureLabelText;
            StringCollection scWords = new StringCollection();
            string randString = GenerateRandomString(6, CharMix.upper);
            scWords.Add(randString);
            imgHip = new ImageHipChallenge();
            imgHip.ID = "imgHip";
            imgHip.Width = Unit.Pixel(210);
            imgHip.Height = Unit.Pixel(70);
            imgHip.Words = scWords;
 
            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipPicture);
            td2.Controls.Add(imgHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
 
            lblHipPictureDescription = new Label();
            lblHipPictureDescription.Text = HipPictureDescription;
 
            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            // td2.HorizontalAlign = HorizontalAlign.Center;
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(lblHipPictureDescription);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
 
            txtHip = new TextBox();
            txtHip.ID = "txtHip";
            txtHip.MaxLength = 20;
            lblHipCharacters = new Label();
            lblHipCharacters.Text = HipCharactersLabelText;
            vldHip = new HipValidator();
            vldHip.ID = "vldHip";
            vldHip.Display = ValidatorDisplay.Static;
            vldHip.ControlToValidate = txtHip.ID;
            vldHip.ValidationGroup = this.ID;
            vldHip.HipChallenge = imgHip.ID;
            vldHip.Text = HipErrorMessage;
            vldHip.ErrorMessage = HipErrorMessage;
 
            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipCharacters);
            td2.Controls.Add(txtHip);
            td2.Controls.Add(vldHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
 
            lnkHip = new LinkButton();
            lnkHip.Click += new EventHandler(lnkHip_Click);
            lnkHip.Text = HipResetLabelText;
            lnkHip.CausesValidation = false;
 
            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lnkHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.Add(tr);
        }
 
        private void AddNameFields()
        {
            Table cuwTable = GetCreateUserTable();
            //Add Extra Fields
            txtFirstName = new TextBox();
            txtFirstName.ID = "txtFirstName";
            TableRow tr1 = AddField(FirstNameLabelText, txtFirstName, FirstNameRequiredErrorMessage);
 
            txtLastName = new TextBox();
            txtLastName.ID = "txtLastName";
            TableRow tr2 = AddField(LastNameLabelText, txtLastName, LastNameRequiredErrorMessage);
 
            cuwTable.Rows.Add(tr1);
            cuwTable.Rows.Add(tr2);
        }
 
        private static Control CreateDropDownListControl(SPFieldChoice userField)
        {
            // To do? work out the default and set it.
            DropDownList newControl = new DropDownList();
 
            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;
 
            return newControl;
        }
 
 
 
        protected override void CreateControlHierarchy()
        {
 
            base.CreateControlHierarchy();
            AddNameFields();
            AddCustomFields();
            AddHipControls();
            this.CreateUserStep.Title = "";
        }
 
        private void AddCustomFields()
        {
            Table cuwTable = GetCreateUserTable();
 
            // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
            // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                {
                    using (SPWeb web = site2.RootWeb)
                    {
                        SPList userlist = web.Lists["User Information List"]; // needs to be multi cultural? or use list GUID?
 
                        Control newCtrl;
                        TableRow newRow;
 
                        foreach (SPField userField in userlist.Fields)
                        {
                            if (userField.Required)
                            {
                                switch (userField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        newCtrl = CreateMultiChoiceControl((SPFieldMultiChoice)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;
 
                                    case SPFieldType.Choice:
                                        newCtrl = CreateDropDownListControl((SPFieldChoice)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;
 
                                    case SPFieldType.DateTime:
                                        newCtrl = CreateDateTimeControl((SPFieldDateTime)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null); // Struggling to provide validation!
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
 
 
                                        CompareValidator cpv = new CompareValidator();
                                        cpv.ID = "cpv" + userField.StaticName;
                                        cpv.Text = "Please enter a valid date dd/mm/yyyy.";
                                        cpv.ControlToValidate = userField.StaticName + "$" + userField.StaticName + "Date";
                                        cpv.Type = ValidationDataType.Date;
                                        cpv.Operator = ValidationCompareOperator.DataTypeCheck;
                                        cpv.ValidationGroup = this.ID;
                                        newRow = AddField("", cpv, null);
                                        cuwTable.Rows.Add(newRow);
                                        break;
 
                                    case SPFieldType.Text:
                                        newCtrl = CreateTextControl((SPFieldText)userField);
                                        newRow = AddField(userField.Title + ":", newCtrl, null);
                                        cuwTable.Rows.Add(newRow);
                                        customSignupFields.Add(userField);
                                        break;
                                }
                            }
                        }
                    }
                }
            });
        }
 
        private static Control CreateMultiChoiceControl(SPFieldMultiChoice userField)
        {
            // To do? work out the default and set it.
            CheckBoxList newControl = new CheckBoxList();
 
            newControl.ID = userField.StaticName;
            newControl.DataSource = userField.Choices;
            newControl.DataBind();
            newControl.Items[0].Selected = false;
 
            return newControl;
        }
 
        private static Control CreateDateTimeControl(SPFieldDateTime spDateTime)
        {
            // To do? work out the default and set it.
            DateTimeControl newControl = new DateTimeControl();
 
            newControl.ID = spDateTime.StaticName;
            if (spDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
            {
                newControl.DateOnly = true;
            }
            else
            {
                // accept time as well? 
                newControl.DateOnly = false;
            }
            newControl.LocaleId = (int)SPContext.Current.RegionalSettings.LocaleId;
            newControl.ErrorMessage = "Please enter a valid date.";
            newControl.IsRequiredField = true;
            newControl.ClearSelection();
            return newControl;
        }
        private static Control CreateTextControl(SPFieldText userField)
        {
            // To do? work out the default and set it.
            //TextField newControl = new TextField();
            TextBox newControl = new TextBox();
            newControl.ID = userField.StaticName;
            return newControl;
        }
        protected override void OnCreatingUser(LoginCancelEventArgs e)
        {
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] != null)
            {
                /* bms Prevent user from being added to the list multiple times if the user */
                /* is already in use.                                                       */
                if (Membership.GetUser(this.UserName) == null)
                {
                    MembershipRequest request = new MembershipRequest();
                    request.UserEmail = this.Email;
                    request.UserName = this.UserName;
                    request.PasswordQuestion = this.Question;
                    request.PasswordAnswer = this.Answer;
                    request.FirstName = this.FirstName;
                    request.LastName = this.LastName;
                    request.DefaultGroup = this._DefaultGroup;
                    MembershipRequest.CopyToReviewList(request);
                }
                this.MoveTo(this.CompleteStep);
 
            }
            else
            {
                base.OnCreatingUser(e);
                //Add the user to the default group
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original RootWeb even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {
                        using (SPWeb web = site2.RootWeb)
                        {
                            web.AllowUnsafeUpdates = true;
                            web.Groups[this._DefaultGroup].AddUser(string.Format("{0}:{1}", System.Web.Security.Membership.Provider.Name.ToLower(), this.UserName.ToLower()), this.Email, this.FirstName + " " + this.LastName, "Self Registration");
                            web.Update();
                        }
                    }
                });
            }
        }
 
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        protected override void OnCreatedUser(EventArgs e)
        {
            SPSite site = SPControl.GetContextSite(Context);
            if (site.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] == null)
            {
                #region Process new user request if we're NOT using the Request List
                // Note: this doesn't run using the privileges of the anonymous user, so we elevate them
                // Also, you can't use the original Site even with elevated privileges, otherwise it reverts back to anonymous.
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site2 = new SPSite(this.Page.Request.Url.ToString()))
                    {
                        using (SPWeb web = site2.RootWeb)
                        {
                            // from this point allowunsafeupdates is required because the call is initiated from a browser with
                            // anonymouse rights only
                            web.AllowUnsafeUpdates = true;
 
                            MembershipRequest request = new MembershipRequest();
                            request.UserEmail = this.Email;
                            request.UserName = this.UserName;
                            if (System.Web.Security.Membership.RequiresQuestionAndAnswer)
                            {
                                request.PasswordQuestion = this.Question;
                                request.PasswordAnswer = this.Answer;
                            }
                            request.FirstName = this.FirstName;
                            request.LastName = this.LastName;
                            request.SiteName = web.Title;
                            request.SiteURL = web.Url;
                            request.ChangePasswordURL = string.Format("{0}/{1}", web.Url, web.Properties[MembershipReviewSiteURL.CHANGEPASSWORDPAGE]);
                            request.DefaultGroup = this.DefaultGroup;
                            // Asumner fixed this
                            request.LoginCreatedUser = LoginCreatedUser;
 
                            MembershipRequest.ApproveMembership(request, web);
 
 
 
                            #region Update any custom "User List Information" fields
                            // Asumner Custom Fields handling
 
 
 
                            // we use the localized name, safe for non-English SharePoint servers
                            SPList userInfoList = site2.RootWeb.Lists[SPUtility.GetLocalizedString("$Resources:userinfo_schema_listtitle", "core", web.Language)];
                            // get site details                              
                            SPIisSettings settings = Utils.GetFBAIisSettings(site2);
                            // Find the table
                            Table cuwTable = GetCreateUserTable();
 
 
                            foreach (SPField customSignupField in customSignupFields)
                            {
                                // Get the user record                                                             
                                SPUser user = site2.RootWeb.AllUsers[settings.MembershipProvider.ToString() + ":" + this.UserName];
                                SPListItem userProfileItem = userInfoList.GetItemById(user.ID);
 
                                // grab matching customfield
                                Control customFieldControl = cuwTable.FindControl(customSignupField.StaticName);
                                // for each data type work out what it is so we know how to
                                // get its value, then update the users profile
                                switch (customSignupField.Type)
                                {
                                    case SPFieldType.MultiChoice:
                                        CheckBoxList checkBoxList = (CheckBoxList)customFieldControl;
                                        SPFieldMultiChoiceValue chosen = new SPFieldMultiChoiceValue();
                                        foreach (ListItem item in checkBoxList.Items)
                                        {
                                            if (item.Selected)
                                            {
                                                chosen.Add(item.Value);
                                            }
                                        }
 
                                        userProfileItem[customSignupField.StaticName] = chosen;
                                        userProfileItem.Update();
                                        break;
 
                                    case SPFieldType.Choice:
                                        DropDownList dropDown = (DropDownList)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = dropDown.SelectedValue.ToString();
                                        userProfileItem.Update();
                                        break;
 
                                    case SPFieldType.DateTime:
                                        DateTimeControl dateTime = (DateTimeControl)customFieldControl;
                                        userProfileItem[customSignupField.StaticName] = DateTime.Parse(dateTime.SelectedDate.ToLongDateString());
                                        userProfileItem.Update();
                                        break;
                                        
                                   case SPFieldType.Text:
                                       TextBox textBox = (TextBox)customFieldControl;
                                       userProfileItem[customSignupField.StaticName] = textBox.Text;
                                       userProfileItem.Update();
                                       break;
                                }
                            }
 
                            // redundant since thise code is about to be disposed?
                            web.AllowUnsafeUpdates = false;
                            #endregion
 
                            this.MoveTo(this.CompleteStep);
                        }
                    }
                });
                #endregion
            }
            else
            {
                base.OnCreatedUser(e);
 
 
            }
        }
 
        #endregion
 
        #region Events
        void lnkHip_Click(object sender, EventArgs e)
        {
            //Nothing to do, the image will reset automatically
        }
        #endregion
 
        private string GenerateRandomString(int NumAlphs, CharMix Mix)
        {
            Random rGen = new Random();
 
            int iMix = (int)Mix;
 
            int p = 0;
            string sPass = "";
            int iCharMax = 32;
            if (iMix > 0) iCharMax = 55;
            for (int x = 0; x < NumAlphs; x++)
            {
                p = rGen.Next(0, iCharMax);
                sPass += _randCharacters[p];
            }
            if (iMix < 1)
            {
                sPass = sPass.ToUpper();
            }
            else if (iMix < 2)
            {
                sPass = sPass.ToLower();
            }
            return sPass;
        }
 
        protected override void OnContinueButtonClick(EventArgs e)
        {
            base.OnContinueButtonClick(e);
 
            HttpContext.Current.Response.Redirect(FinishDestinationPageUrl);
 
        }
    }
}

Read the full discussion online.

To add a post to this discussion, reply to this email (CKS@discussions.codeplex.com)

To start a new discussion for this project, email CKS@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe or change your settings on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com

Nov 3, 2009 at 5:39 AM

Many thanks Anthony for your reply.
Ja