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

<%@RegisterTagPrefix="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%>" VisibleSuggestions="3" Rows="1" AllowMultipleEntities="false" CssClass

The column name that you entered is already in use or reserved. Choose another name.

The problem: 
You want to create column with a specific name in SharePoint but SharePoint gives you the message "The column name that you entered is already in use or reserved. Choose another name."



Why this is a problem?
Because you need to create custom columns and content types using the default SharePoint interface.
And the business users have to see properly named columns - for example "Description", not "My Description".

Solution:
It is important to know something technical about SharePoint (versions Office 365, 2013, 2010):
 - it supports columns with same Display Names.
 - you can’t have columns with same Internal names

Let’s implement the following common scenario:
You are creating a SharePoint customization and you need the following column:
   Type: Multiple lines of text
   Internal Name: MyProjectDescription
   Display Name: Description

 Here is the correct way to achieve it:
1. Create the column MyProjectDescription.
This will create column with I…

Office 365 Migration API: how to migrate the taxonomy metadata

If you wander whether the Office 365 Migration API supports migration of taxonomy metadata, the answer is YES. The API supports it but there isn't good documentation about how to modify your xml files after the command ConvertTo-SPOMigrationTargetedPackage.

In this post, I'm going to show you the approach. I assume that you have base knowledge of how to use the Migration API.

The scenario I'm going to use is simple - migrate single Document library with single document.
The document has one taxonomy column (MyTaxonomy) and three versions:

Here are the steps:

Step 1: Export the document library

Export-SPWeb "https://portal.cosingens.com/" ` -ItemUrl "/Shared Documents" ` -Path "\\cos-dev-03\export1\Export" ` -NoFileCompr -IncludeVersions 4
This command will export the document library and will create the initial package.
The command is not part of the Migration API. It is well know since SharePoint 2010 and is part of the server side obje…