Archive for February 25, 2014

Run With Elevated Privilges

SharePoint Short #20

Instead of explicitly wrapping code in a RunWithElevatedPrivileges block, it’s better to first check if the user has sufficient privileges and only elevate when they don’t.

Instead of:

SPSecurity.RunWithElevatedPrivileges(() =>
    {
        // elevated code...
    });

Do this:

public void RunWithElevatedPrivileges(SPWeb web, SPSecurity.CodeToRunElevated elevatedCode)
{
    if (web.CurrentUser.IsSiteAdmin)
    {
        elevatedCode();
        return;
    }
    SPSecurity.RunWithElevatedPrivileges(elevatedCode);
}
 
public void TestMethod()
{
    RunWithElevatedPrivileges(SPContext.Current.Web, ()=>
        {
            // elevated code...
        });
}

This way the code will only be encapsulated in the elevated block when the user does not have adequate permissions and you’ll help to increase the performance of your code by avoiding executing unnecessary code.

You could further extend this by only opening the SPSite\SPWeb object when elevating the code.

Cannot invoke HTTP DAV request

When using the Client-Side Object Model (CSOM) for SharePoint and you’re trying to create\overwrite a file using binary data, you’d naturally try and use the SaveBinaryDirect method of the File class:

public void SaveFile(Microsoft.SharePoint.Client.ClientContext context, Microsoft.SharePoint.Client.File file,
                     string relativeItemUrl, byte[] fileData)
{
    using (Stream ms = new MemoryStream(fileData))
    {
        File.SaveBinaryDirect(context, relativeItemUrl, ms, true);
    }
}

When using a MemoryStream the following error will more than likely be raised:

Cannot invoke HTTP DAV request. There is a pending query
Read more

Follow

Get every new post delivered to your Inbox

Join other followers: