Quantcast
Channel: CHUVASH.eu » SPSite
Viewing all articles
Browse latest Browse all 2

WithWeb-pattern of Jonas Nilsson

$
0
0

Jonas Nilsson shows an interesting approach for working with SPSite and SPWeb which must be disposed. Create a helper method WithWeb and send an Action parameter:

public void WithWeb(string uri, Action<SPWeb> action)
{
    using (SPSite site = new SPSite(uri))
    {
        using (SPWeb web = site.OpenWeb())
        {
            action(web);
        }
    }
}

Here is my implementation of this pattern:

public static class DisposalService
{
    public static void WithWeb(string uri, Action<SPWeb> action)
    {
        using (var site = new SPSite(uri))
        {
            using (var web = site.OpenWeb())
            {
                web.UnsafeUpdate(action);
            }
        }
    }
    public  static void WithElevatedWeb(string uri, Action<SPWeb> action)
    {
        SPSecurity.RunWithElevatedPrivileges(() => WithWeb(uri, action));
    }
}

Here I use another fancy way to consolidate the unsafe updates. I added an additional method: WithElevatedWeb, it creates the web as system account.

And here comes an example of using this static method:

Action<SPWeb> update = (SPWeb w) =>
                        {
                            UserService.UpdateOwners(owners, w);
                            UserService.UpdateMembers(members, w);
                        };
DisposalService.WithWeb(SPContext.Current.Web.Url, update);


Viewing all articles
Browse latest Browse all 2

Trending Articles