Friday, 21 September 2012

Sharepoint 2010: Renaming listitems without delete rigths

It appears, in sharepoint 2010, that you can't rename listitems without having delete rights. Recently a client of mine wanted a solution where you could rename items but not delete them, here's what I came up with.

First of all, users must have creator rights and edit rights on the list for this solution to work. Now, the workaround here is to create a custom action to rename, that will popup a dialogue window with the new name desired, this information will then be given to a custom page that will rename the list using elevated privileges.

Let's see the custom action code below:


I created two custom action elements, one for documents and on for pages. Location, EditControlBlock, which means that the new button will appear when you right click the listitem to see the context menu. ActionUrl, javascript function below that will popup the dialogue box and send the information to the custom page.


function ExecuteRenameAction(siteUrl, listId, itemId, itemUrl) {
    var pageUrl = siteUrl + "_layouts/rename.aspx?siteUrl=" + siteUrl + "&listId=" + listId + "&itemId=" + itemId + "&itemUrl=" + itemUrl;
    var popup = SP.UI.$create_DialogOptions();
    popup.url = pageUrl;
    popup.width = 400;
    popup.height = 200
    SP.UI.ModalDialog.showModalDialog(popup);
}

The javascript show the custom page in a dialogue box and pass the parameters in the query string. Now the page code
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.IO;

namespace BDI_Boutton_Renommer.LAYOUTS
{
    public partial class rename : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string siteUrl = Request.QueryString["siteUrl"];
            string listId = Request.QueryString["listId"];
            string itemId = Request.QueryString["itemId"];
            string itemUrl = Request.QueryString["itemUrl"];
            if(string.IsNullOrEmpty(listId) || string.IsNullOrEmpty(itemId) || string.IsNullOrEmpty(itemUrl) || string.IsNullOrEmpty(siteUrl))
            {
                // break here
                throw new Exception("Les arguments fournits sont nulls ou vides");
            }
            SPWeb web = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteUrl))
                {
                    web = site.OpenWeb();
                }
            });

            SPList list = web.Lists.GetList(new Guid(listId), false);
            try
            {
                SPListItem item = list.Items.GetItemById(int.Parse(itemId));
                if (item == null)
                    throw new Exception("Impossible de trouver l'élément choisit dans la liste");
                if (item.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;
                        item.File.CheckOut();
                        if (item["Nom"] != null)
                            item["Nom"] = this.txtName.Text + Path.GetExtension(itemUrl);
                        else if (item["Name"] != null)
                            item["Name"] = this.txtName.Text + Path.GetExtension(itemUrl);
                        item.Update();
                        item.File.CheckIn("Renommage du fichier");
                        item.File.Approve("Approuvé par le système");
                    }
                    catch(Exception ex)
                    {
                        item.File.UndoCheckOut();
                        throw ex;
                    }
                    web.AllowUnsafeUpdates = false;

                    // Mimic user credentials even if the update has been done with elevated privileges
                    cheatUserCredentials(siteUrl, listId, itemId);
                    
                    lblMessage.Text = "Opération effectuée avec succès";
                    pnlInfo.Visible = false;
                    pnlMessage.Visible = true;
                }
                else
                {
                    lblMessage.Text = "Impossible de renommer le fichier maintenant, il est extrait par un autre utilisateur";
                    pnlInfo.Visible = false;
                    pnlMessage.Visible = true;
                }
            }

            catch (System.FormatException f)
            {
                // Argument supplied is not valid
                throw new System.ArgumentException("Une erreur c'est produite, l'argument n'est pas valide");
            }
            finally
            {
                
                web.Dispose();
            }
           

        }

        private void cheatUserCredentials(string siteUrl, string listId, string itemId)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[new Guid(listId)];
                    SPListItem item = list.Items.GetItemById(int.Parse(itemId));
                    web.AllowUnsafeUpdates = true;
                    item.File.CheckOut();
                    item.UpdateOverwriteVersion();
                    item.File.CheckIn("Renommer le fichier");
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
    }
}

In the page code above there's 2 function, one for renaming and one for settings the right credentials, remember that were are using elevated privileges if you don't get back the item you will see system account as last user in the history.

No comments:

Post a Comment