About Me

My photo
a Dynamic and Energetic guy.....

Sunday, April 27, 2014

Add a FBA User to a SharePoint Group Programatically

SPSecurity.RunWithElevatedPrivileges(delegate
                               {
                                   using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                                   {
                                       using (SPWeb web = site.OpenWeb())
                                       {
                                           //adding user to the contributor group
                                           web.AllowUnsafeUpdates = true;
                                           //i:0#.f|sql-membershipprovider|chana

                                           string usernameWithProvider = "i:0#.f|sql-membershipprovider|" + usr.UserName;
                                          
                                           web.AllUsers.Add(usernameWithProvider, txtUserName.Text, txtUserName.Text, "");
                                           try
                                           {
                                               SPUser spuser = web.AllUsers[usernameWithProvider];
                                               if (spuser != null)
                                               {
                                                   SPGroup spGroup = web.Groups["Dev Members"];

                                                   if (spGroup != null)
                                                       spGroup.AddUser(spuser);
                                                   web.Update();
                                                   web.AllowUnsafeUpdates = false;
                                               }
                                           }
                                           catch { }
                                           web.Update();
                                           web.AllowUnsafeUpdates = false;
                                       }
                                   }

                               });

My Masters