in

SharePoint University

Clean slate. Nothing but SharePoint.
Go, SharePoint!

RunWithElevatedPrivileges usage error

Last post 11-12-2007 3:15 AM by ossigeno. 1 replies.
Page 1 of 1 (2 items)
Sort Posts: Previous Next
  • 10-10-2007 4:45 AM

    • frodema
    • Not Ranked
    • Joined on 08-03-2007
    • Norway

    RunWithElevatedPrivileges usage error

    I get an error trying to use SPSecurity.RunWithElevatedPrivileges in a webpart.

    The webpart iterates through all sites, and populates an SPGridView with the result. This works fine using the System account, but when I login using Forms Authentication I get the Access Denied page, and an UnauthorizedAccessException.

    I tried to use the SPSecurity.RunWithElevatedPrivileges, but I get this error:cannot convert from 'anonymous method' to 'Microsoft.SharePoint.SPSecurity.CodeToRunElevated'

    The method:

    (SiteHyperLink is just a small class with two properties Title and Url, and ConvertURLsToHyperLinks is a Regex.Replace method for the urls)

    private ArrayList ProcessHyperLinks()
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = SPContext.Current.Site)
                    {
                        SPWebCollection allWebs = mySite.AllWebs;
                        ArrayList returnArrayList = new ArrayList();
                        foreach (SPWeb subWeb in allWebs)
                        {
                            SiteHyperLink sh = new SiteHyperLink(
                            subWeb.Title, ConvertURLsToHyperLinks(subWeb.Url));
                            returnArrayList.Add(sh);
                        }
                        return returnArrayList;
                    }
                });
            }

    Seems I can't do it like this. Any ideas or solutions would be appreciated very much.

     

  • 11-12-2007 3:15 AM In reply to

    Re: RunWithElevatedPrivileges usage error

    Couple of issues I can see here. 

    1. You have a return value inside the anonymous method SPSecurity.RunWithElevatedPrivileges(delegate()..});

    2. SPSite mySite = SPContext.Current.Site. This will use the current user context. Not the elevated context. You need to create a new SPSite object:-

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
     

    using (SPSite site = new SPSite(web.Site.ID))
    {

    }

    });

Page 1 of 1 (2 items)

Need SharePoint Training? Attend a SharePoint Bootcamp!
Forum content (c) original posters. Everything else (c) 2008 SharePoint Experts, Inc.