Get web collection count for read permission

Issue:-

For one of requirement; I had to get subwebs and lists of current site for current user. To do so I just used “SPWeb.Web.Count”  and it works well for admin.
But for reader it throws access denied exception. If we see in debug mode then error detail would be like below:-

threw an exception of type ‘System.Threading.ThreadAbortException’ Microsoft.SharePoint.SPWeb {System.Threading.ThreadAbortException

Resolution:-

1. SPWeb.Count of immediate sub sites only.

To do this we are not require to use RunWithElevatedprivileges. See below code

1
2
3
4
5
6
7
// here web is SPWWeb object
SPWebCollection collWebsites= web.GetSubwebsForCurrentUser(); // return all immediate sub sites for current user
 
if (collWebsites.Count > 0)
{
// apply your logic
}


2. SPWeb.Count of all sub sites.

To do this we are require to use RunWithElevatedprivileges. Use below code

1
2
3
4
5
6
7
8
9
10
11
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
     SPWebCollection collWebsites = oSiteCollection.AllWebs;
        if (collWebsites.Count > 0)
        {
         // apply your logic
        }
   }
});

Hope it helps.
Thanks!
Avinash

calendarApril 16, 2012 · cardInfoyen · commentsNo Comments
tagTags: , , , , ,  · Posted in: MOSS, Security, SharePoint, Tips & Tricks

Leave a Reply

Spam Protection: , required

myworldmaps infoyen