Wesley
Wesley

Reputation: 5621

Is this Data Access Pattern acceptable in SharePoint?

I'm creating a SharePoint application and want to do things the right way as often as possible.

I'm deploying a series of Lists in a Site Definition, and I want to lock down Data Access to a series of Get() methods to maintain conventions.

Some of my lists have SecurityBits="22" set in the list definition, because I want List Item entries to be modified only in the UI.

I want to avoid abusing SPSecurity.RunWithElevatedPrivileges. I also want to sidestep the limitation of SPSecurity.RunWithElevatedPrivileges where you cannout have return functions in the delegates.

This seems like a good way to enforce this. If you're calling a list to get list items with normal security, you can call var PostList = CoreLists.Posts. If you need to call that same list with elevated permissions, you can call var PostList = CoreLists.SystemAccount.Posts

Is this a good way to do this?

public static class CoreLists
{
    public static SPList Posts()
    {
        return SPContext.Current.Web.GetList(SPContext.Current.Web.ServerRelativeUrl + "/lists/CommunityPost");
    }
    public static class SystemAccount
    {
        public static SPList Posts()
        {
            using (var elevatedSite = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.SystemAccount.UserToken))
            using (var web = elevatedSite.OpenWeb())
                return web.GetList(web.ServerRelativeUrl + "/lists/CommunityPost");
        }
    }
}

Upvotes: 1

Views: 109

Answers (1)

str8killinit
str8killinit

Reputation: 167

I think the first class looks fine as long as your security context makes sense (i.e. the user with lowest security can access the list items using these methods). I would be curious how the using statements in the second affect code calling that.

The thing with ElevatePriveleges is that sometimes when you have data access code that is widely used, a lot of times you have to elevate priveleges if you don't want to give them access to the list directly in the SharePoint UI, but want to have code executing in their context access the list items for user controls and the like.

A couple things to keep in mind: 1. always be cognizant of memory leaks with list access code in SharePoint. In your classes you handled both situations well as far as dealing with any SPRequest disposing. 2. You almost never want to use SPList.Items in your code. If you surface lists this way and you don't manage the code calling the list you may run into performance issues with larger lists as calling the .Items property, and not a specific query, loads every single item and field possible for every item in that list.

hope this helps

Upvotes: 1

Related Questions