Tuesday, November 1, 2011

Correct way to use SPWeb.EnsureUser in SharePoint

I hope you must have faced this issue at some point of time while using SPWeb.EnsureUser. Actually this method call need high level of permission. Owners group is only by default will not get any access denied.

The trick is to wrap the call within the RunWithElevatedPriviles. Please find below the code stub below for an example. This example has implementation of EnsureUser. This method takes 3 parameters and returns SPUser.

#region Get SP User From String Name Value

        public static SPUser GetSPUserFromStringNameValue(SPListItem Item, string FieldName, SPWeb oWeb)

        {

            SPUser oUser = null;

            try

            {

                string strUser = string.Empty;

                if (Item[FieldName] != null)

                {

                    if (!string.IsNullOrEmpty(Item[FieldName].ToString()))

                    {

                        strUser = Item[FieldName].ToString();

                        SPSecurity.RunWithElevatedPrivileges(delegate()

                        {

                            using (SPSite elevatedSite = new SPSite(oWeb.Site.ID))

                            {

                                using (SPWeb elevatedWeb = elevatedSite.OpenWeb())

                                {

                                    oUser = elevatedWeb.EnsureUser(strUser);

                                }

                            }

                        });

                    }

                }

            }

            catch (Exception ex)

            {

                ULSLogException(ex);

                //throw;

            }

            return oUser;

        }

        #endregion

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

1 comment:

  1. Never do that awful things, because open site and open web too high-weight operation for the such simple thing. What about for-each loop for 10000 items with invoke the method (GetSPUserFromStringNameValue)?

    ReplyDelete