Monday, January 16, 2012

How to create new sharepoint user - sharepoint 2010


        private SPUser CreateUser(string strLoginName, string strEMail,string strName, string strNotes)
        {
            SPUser result = null;
            SPSite spSite = null;
            SPWeb spWeb = null;
            
            try
            {

                //Open the SharePoint site
                SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
                spSite = new SPSite(SPContext.Current.Site.RootWeb.Url, sysToken);
                using (spSite)
                {
                    spWeb = spSite.OpenWeb();

                    //Assign role and add user to site
                    spWeb.AllowUnsafeUpdates = true;
                    SPRoleAssignment spRoleAssignment = new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);

                    //Using Contribute, might need high access
                    SPRoleDefinition spSPRoleDefinition = spWeb.RoleDefinitions["Contribute"];

                    spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
                    spWeb.RoleAssignments.Add(spRoleAssignment);

                    //Update site
                    result = spWeb.AllUsers[strLoginName];
                    spWeb.Update();

                }
            }
           
            catch (Exception ex)
            {
               //do some exception handling here
            }
            finally
            {
                spWeb.AllowUnsafeUpdates = false;
                spWeb.Close();                                              
            }

            return result;
        }

No comments:

Post a Comment