tags:

views:

22

answers:

1

Hi all.

I got an exception when executing this snippet code

SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(siteUrl.Trim())) { using (SPWeb web = site.OpenWeb()) { try { web.AllowUnsafeUpdates = true; SPUser spUser = web.AllUsers[userName];

                        if (spUser != null)
                        {
                            SPGroup spGroup = web.Groups[groupName];
                            if (spGroup != null)
                                spGroup.AddUser(spUser);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.TraceData(LogLevel.Error, "Error at function Named               [AddUserToSPGroupWidget.AddUserToGroup] . With Error Message: " + ex.ToString());

                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
             });

PLease guide me. Thanks in advance.

A: 

I don’t know what your exact exception is, but you can try to do following changes:

  1. Instead of

    SPUser spUser = web.AllUsers[userName];

use (it will ensure that user exists on the web)

SPUser spUser = web.EnsureUser(userName);
  1. Instead of

    SPGroup spGroup = web.Groups[groupName];

use (Groups collection contains only groups that are defined on the current sub web)

SPGroup spGroup = web.SiteGroups[groupName];
  1. There is no need to check (spGroup != null) because if group is not found then always exception will be thrown.
EG