Sunday, March 13, 2011

Protecting SharePoint Library Views from being overwritten by end users

You may have experienced this before – it has happened to me in the past:

  1. You create a document using Microsoft Word
  2. To save it, you navigate to the library where you want to save it in and copy the entire URL into your clipboard (which is in fact a link to the View in SharePoint, for example, /Forms/AllItems.aspx
  3. You paste that in the MS Word "Save As" dialog and click Enter
  4. The AllItems.aspx is officially overwritten by your new Word Document and no one can see the items in the library using this view

Ways to fix the view are listed in several sites – that's easy enough to do if you are familiar with SharePoint but this is still a good hassle when your users do this from time to time.

I checked and learned that the ItemUpdating event in SharePoint is fired when you perform such an action but is not fired when you modify a View in SharePoint.

This means that if an ItemUpdating event is fired against an .aspx file which is in the /Forms/ hidden folder then it means that someone is trying to overwrite a View in this library.

I have developed a simple feature for SharePoint 2010 to catch this and cancel the update and throw an error (code below).

namespace ProtectViews.EventReceiver1

{


///
<summary>


/// List Item Events


///
</summary>


public
class
EventReceiver1 : SPItemEventReceiver

{


///
<summary>


/// An item is being updated.


///
</summary>


public
override
void ItemUpdating(SPItemEventProperties properties)

{


if (properties.AfterUrl.ToLower().Contains("/forms/") && properties.AfterUrl.ToLower().EndsWith(".aspx"))

{


//Overwriting a view

properties.Cancel = true;

properties.ErrorMessage = "Your library view was protected by Ensyst's ProtectView.\n" +


"It seems that you are trying to overwrite a view instead of saving a document in a protected environment,\n" +


"please remove the /forms/XXX.aspx from the end of the path you are trying to save to and try again";


return;

}


else

{


//Normal save

properties.Cancel = false;

}


base.ItemUpdating(properties);

}

}

}


 

The way I see it, if you wanted to properly overwrite a view with an .aspx file you have, you can just disable the feature, overwrite the file and then re-enable the feature.


This definitely helps you avoid users overwriting the views and fixing it, while the error message may not always appear it will cancel the even altogether and you can save the file somewhere else.

Enjoy…

No comments:

Post a Comment