Skip to main content

Using SharePoint Attachments' controls with elevated security


The scenario:  Create custom forms for Add/Edit/Delete items to a list which is not accessible by the regular users. The forms should support working with attachments.

The problem: The default SharePoint controls don’t work if the current user doesn’t have access to the list items.

The solution: Use custom code for generating the SharePoint default HTML so the out-of-the-box javascript works correct.

Explanations: 
The scenario occurs when some list need to be hidden form the users. The list has broken security inheritance and users can't navigate directly to it.

Working with its fields requires crating web warts or application pages with appropriate controls on them and server-side code running under elevated privileges. The issue here is that the OOTB (out-of-the-box) controls for Attachments don't work if the user doesn’t have access to the related list item.

The OOTB controls are: AttachmentsField, AttachmentUpload, AttachmentButton. There is a lot of code how to use them so here I won’t repeat it again.
AttachmentsField is used for showing and deleting existing attachments.


AttachmentButton and  AttachmentUpload give the functionality for browsing and saving new attachments.


Code sample for ‘bind’ the AttachmentsField control is the following one:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
  SPSite site1 = SPContext.Current.Site;
  SPWeb web1 = SPContext.Current.Web;
  using (SPSite newSite = new SPSite(site1.ID))
  {
      using (SPWeb newWeb = newSite.OpenWeb(web1.ID))
      {
        var itemID = Request.QueryString.Get("id");
        SPListItem item  =newWeb.GetList("/Lists/Tasks/").GetItemById(Convert.ToInt32(itemID));
        if (item.Attachments.Count > 0)
        {
            attachmentField.ListId = item.ParentList.ID;
            attachmentField.ItemId = item.ID;
            attachmentField.FieldName = "Attachments";
            attachmentField.ControlMode = SPControlMode.Edit;
        }
      }
  }
});


Even the code is elevated correctly, when a user who doesn’t have access to the list open the form, he will not see the attachments. This is due the fact the AttachmentsField control gets ListId and ItemId and performs its own code for retrieving the item data. The code is executed in the context of the logged user, not in the context of the elevated one. Even setting the context directly this doesn’t solve the problem:

attachmentField.RenderContext = SPContext.GetContext(newWeb);
attachmentField.ItemContext = SPContext.GetContext(newWeb);
I spent one day researching and debugging it and I found that it won’t work. Here is a good thread about the similar issue.

My decision in this case is – custom logic that reuses the default SharePoint html and javascript.

The AttachmentsField renders the following HTML:


What you need to keep is the table id and the concept to rendering the items in elements. What you need also to add is a request to custom page which can download the file because the current user can’t access the file.
New HTML looks like this:

The functionality that AttachmentUpload and AttachmentButton  provide can be replace from the markup:

<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="core.js" LoadAfterUI="true" EnableViewState="true" />
    <SharePoint:ScriptLink ID="ScriptLink3" runat="server" Name="FORM.debug.js" LoadAfterUI="true" EnableViewState="true" />
    <table style="width: 100%; padding-bottom: 10px;">
        <tbody>
            <tr>
                <td>
                    <asp:HiddenField Value="hDeleteAttachs" ID="hHiddenFields" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <span id="part1">
                        <div id="ctl00_PlaceHolderMain_AttachmentButtonPanel">
                            <table cellspacing="0" cellpadding="1">
                                <tbody>
                                    <tr>
                                        <td class="ms-toolbar" nowrap="nowrap">
                                            <img width="16" height="16" align="absmiddle"
                                                style="border-width: 0px;" alt="Attach File"
                                                src="/_layouts/15/images/attachtb.gif"></td>
                                        <td class="ms-toolbar" nowrap="nowrap">
                                            <a id="ctl00_PlaceHolderMain_diidIOAttach" style="visibility: hidden;"
                                                 onclick="javascript:UploadAttachment();" href="javascript:UploadAttachment()"></a>
                                            <a class="ms-toolbar" id="ctl00_PlaceHolderMain_diidIOAttach_LinkText" accesskey="I"
                                                 onclick="javascript:UploadAttachment();"
                                                 href="javascript:UploadAttachment()">Attach File</a></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </span>
                </td>
            </tr>
            <tr>
                <td id="idAttachmentsRow" colspan="2">
                    <div id="ctl00_PlaceHolderMain_AttachmentUploadPanel">

                        <input name="attachmentsToBeRemovedFromServer" type="hidden">
                        <input name="RectGifUrl" type="hidden" value="/_layouts/15/images/rect.gif?rev=23">
                        <span id="partAttachment" style="display: none;">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tbody>
                                    <tr>
                                        <td class="ms-descriptiontext" valign="top" style="padding-bottom: 8px;" colspan="4">
                                            Use this page to add attachments to an item.
                                        </td>
                                    </tr>
                                    <tr>
                                        <td width="190" height="50" class="ms-formlabel" valign="top">Name  </td>
                                        <td height="15" class="ms-formbody" id="attachmentsOnClient" valign="bottom">
                                            <span dir="ltr">
                                                <input name="fileupload0" title="Name  " class="ms-fileinput" id="onetidIOFile" type="file" size="56">
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="1" class="ms-formline" colspan="4">
                                            <img width="1" height="1" alt="" src="/_layouts/15/images/blank.gif?rev=23"></td>
                                    </tr>
                                    <tr>
                                        <td height="10" colspan="4">
                                            <img width="1" height="1" alt="" src="/_layouts/15/images/blank.gif?rev=23"></td>
                                    </tr>
                                    <tr>
                                        <td class="ms-attachUploadButtons" colspan="4">
                                            <input class="ms-ButtonHeightWidth" id="attachOKbutton" onclick="OkAttach()" type="BUTTON" value="OK  ">
                                            <span class="ms-SpaceBetButtons" id="idSpace"></span>
                                            <input name="attachCancelButton" class="ms-ButtonHeightWidth"
                                                id="attachCancelButton"
                                                 accesskey="C" onclick="CancelAttach()" type="BUTTON" value="Cancel ">
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </span>
                        <span dir="none">
                            <table id="idAttachmentsTable" border="0" cellspacing="0" cellpadding="0">
                                <tbody>
        <%--  render here existing attachments in the way shown above --%>
                                </tbody>
                            </table>
                        </span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
    <table id="Table1" border="0" cellspacing="0" cellpadding="0">
        <tbody>
            <tr>
                <td></td>
            </tr>
        </tbody>
    </table>

Reusing the existing functionalities save time and makes your solution to behave in a SharePoint native way.

Comments

  1. Hi,
    I cant display the control with full permission as well. It works fine for new mode but not displlaying in edit mode...can u please help

    ReplyDelete

Post a Comment

Popular posts from this blog

ClientPeoplePicker in SharePoint 2013

Start using SharePoint 2013 I noticed that the way for selecting people or groups is changed. The new way is simple – just ‘Enter name or email address’ without any icons for ‘Check Names’ or ‘Browse’. I guess that the PeoplePicker is changed but NO. PeoplePicker sitll has the same functionality as before. There is a new control called ClientPeoplePicker . How to use it: 1. Add this references <% @ Register TagPrefix ="wssawc" Namespace ="Microsoft.SharePoint.WebControls" Assembly ="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 2. Add the following control declaration       < wssawc : ClientPeoplePicker          Required ="true"          ValidationEnabled ="true"          ID ="peoplePicker"          runat ="server"          InitialHelpText =" <% $Resources:wss,aclinv_PickerIntialHelperText %> "          VisibleSu

Error: A duplicate field name "xxxx" was found

Soon I have some experience with migrating solution from SharePoint 2010 to SharePoint 2013. The migration was on 3 steps. First one was just to copy the custom fields, content types and list definitions from the old VS 2010 project into a new VS 2012 project for SharePoint 2013. Looks like pretty simple task but ….. The problem:  Error “ A duplicate field name "xxxx" was found ” when the feature for provisioning the fields and content types is activated. The solution: Review the field definitions and make sure no field has Name property equal to some of the ‘reserved’ values. Explanations: In SharePoint 2010 there was no problem to have these fields as a definition of custom fields: < Field     Type = " Note "     ID = " {893FB9BC-2DA4-4451-A1D1-88010CDC6A08} "     Name = " Description "     StaticName = " Description "     DisplayName = " Description 1 "     Required = " FALSE "     MaxL