Only You Can Help Prevent Accidental Deletion in SharePoint
Question
An anonymous user asks, "i want to prevent the user to delete a folder in document Library, if user selects the folder and clicks an delete document icon on ribbon, he is only able to delete the files in the folder not the folder itself. how can i do this?".
Answer
Preventing users from deleting items in SharePoint is a common issue. The recycle bin in SharePoint 2010 helps prevent the permanent deletion of files, folders, and sites, but you still need administrative assistance sometimes to restore the item. Ideally, the user's security permissions should be configured to restrict their access so they don’t even have the option to delete. You could break the security inheritance on the folder and change the permissions so that certain users cannot delete the folder, but the files in the folder will inherit the authorization permissions. You could also break the inheritance of each file in the folder, but that would be time consuming and hard to maintain when new files are added. You could probably create a workflow to give each added file the correct permissions, but all the unique permissions would get messy to maintain in the future.
To prevent any item from being deleted in a list or a site I would use an event handler if security permissions will not due. Event handlers are a compiled module of custom managed code that responds when specific SharePoint triggering events take place. In our case, we would want attach our event handler to the list and wait until the list fires an ItemDeleting event. An ItemDeleting event will run your custom code just before it starts deleting the folder. In your code you want to stop SharePoint from executing the rest of the SharePoint deletion code by cancelling the event.
Below are the instructions on how to create an event handler to stop a folder from being deleted:
- Start Microsoft Visual Studio 2010.
- On the File menu, point to New, and then click Project.
- In Project Types, under C#, select Event Receiver.
- In the SharePoint Customization Wizard under What local site do you want to user for debugging?, type the address to the site that contains the document library (ex: http://intranet.contoso.com/hr/).
- In the SharePoint Customization Wizard, choose Deploy as a sandboxed solution. Click Next.
- In the Choose Event Receiver Settings dialog, select List Item Events in the What type of event receiver do you want? dropdown.
- In the What item should be the event source? dropdown, choose Document Library.
- Choose the An item is being deleted option in the Handle the following events list. Click Finish.
- In the EventReceiver1 file that is created, insert the following code in the ItemDeleting method:
- In the solution explorer, delete the element.xml file because we do not need it for a single document library.
- In the solution explorer, click on the EventReceiver1 and view the folder properties.
- Under Feature Receiver in the Safe Control Entries properties, click on Collection and then the ... button.
- If there not a list item under Members on the Safe Control Entries screen, then click the Add button and then press the OK button to add a safe control entry for your DLL in the web application's web.config.
- In the solution explorer, right click on the Feature1 and click the Add Event Reciever menu item to create a event receiver cs file for your feature.
- In the Feature1.EventReceiver.cs file that was created, insert the following code in the FeatureActivated and FeatureDeactivating methods:
- Now that your event handler will be attached to your list programmatically, press F5 to compile and deploy the solution.
- Navigate to your document library list and select an item in the list. Click the Delete Item button on the Server ribbon.
- Your error message should appear and the folder will not be deleted.
public override void ItemDeleting(SPItemEventProperties properties)
{
//A Try Catch statement to capture any unexpected errors
try
{
//Check to make sure the list item we are looking at is a folder
if (properties.ListItem.Folder != null)
{
//Get folder object
SPFolder folder = properties.ListItem.Folder;
//Check folder name to make sure we have the correct folder
if (folder.Name == "Name of your folder")
{
//Cancel the delete event with an error message
properties.Status = SPEventReceiverStatus.CancelWithError;
//Create an error message so the user knows why the folder can't be deleted
properties.ErrorMessage = "This folder is restricted from being deleted.";
}
}
}
catch (Exception e)
{
//Create an error message so you know in the event logs what happened and where the error occurred.
throw new Exception("Restrict Folder Deletion Event Handler: Exception: [" + e.ToString() + "].");
}
}
//Define variables
string listName = "YourListName";
string receiverName = "Event Receiver Name";
string assemblyFullName = "EventReceiverProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=94de0004b6e3fcc5";
string assemblyClassName = "EventReceiverProject1.EventReceiver1";
int sequenceNumber = 2001;
string receiverData = "Data";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
//A Try Catch statement to capture any unexpected errors
try
{
//Get current SharePoint site the feature was activated on
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
//Get List
SPList list = web.Lists[listName];
//Get event handlers for the list
SPEventReceiverDefinitionCollection eventReceivers = list.EventReceivers;
//Create the event handler definition object
SPEventReceiverDefinition eventReceiver = eventReceivers.Add();
//Set event handler properties
eventReceiver.Name = receiverName;
eventReceiver.Assembly = assemblyFullName;
eventReceiver.Class = assemblyClassName;
eventReceiver.SequenceNumber = sequenceNumber;
eventReceiver.Data = receiverData;
eventReceiver.Type = SPEventReceiverType.ItemDeleting;
//Create the event handler definition object with data
eventReceiver.Update();
//Update List
list.Update();
}
}
catch (Exception e)
{
//Create an error message so you know in the event logs what happened and where the error occurred.
throw new Exception("Event Handler Feature: Exception: [" + e.ToString() + "].");
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
//A Try Catch statement to capture any unexpected errors
try
{
//Get current SharePoint site the feature was deactivated on
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
//Get List
SPList list = web.Lists[listName];
//Get event handlers for the list
SPEventReceiverDefinitionCollection eventReceivers = list.EventReceivers;
//Define new Guid variable from the eventReceiver ID
Guid eventReceiverID = new Guid();
//Search through all the event handlers in the list
foreach (SPEventReceiverDefinition eventReceiver in eventReceivers)
{
//If the event handler matches our event handler name
if (eventReceiver.Name == receiverName)
{
//Save the event handler guid
eventReceiverID = eventReceiver.Id;
}
}
//If a guid is found for the event handler
if (eventReceiverID != null)
{
//Get the event handler for the event hander collection of the list
SPEventReceiverDefinition eventReceiver = eventReceivers[eventReceiverID];
//Delete the eventReceiver reference
eventReceiver.Delete();
//Update the list
list.Update();
}
}
}
catch (Exception e)
{
//Create an error message so you know in the event logs what happened and where the error occurred.
throw new Exception("Event Handler Feature: Exception: [" + e.ToString() + "].");
}
}
For more information on event handlers visit Events in SharePoint Foundation 2010, Using Event Receivers in SharePoint Foundation 2010 (Part 1 of 2), and Using Event Receivers in SharePoint Foundation 2010 (Part 2 of 2).
Why Do You Attend Microsoft TechDays? A) To learn, B) To socialize, C) For the swag, D) To get answers, or E) All of the above
I wasn't surprised to read in "Here’s the Scoop on TechDays 2011" on IT Pro Connection that TechDays Canada 2011 would only be coming to Vancouver, Montreal, and Toronto. Attendance at TechDays 2010 in Halifax was half of what it was the year before. A common theme amongst the people I talked to at the conference was that their organization could only send a single representative to the event and that their job was to collect as much information as possible and bring it back to their colleagues back at the office. Further, some attendees were not even sure that they'd be returning this year due to the low turnout and the pervasive feeling that the content covered at TechDays wasn't helping solve their immediate issues or concerns.
This year's sessions will be made available through the TechDays Canada Online website for everyone to enjoy, but it just won't be the same. Watching sessions, learning new technologies and best practices, and expanding my technical knowledge is just one aspect of what makes TechDays valuable to me. Personally, I find that it's the interaction with people who attend that defines the true value - and at its heart, I think of TechDays as a social experience and an opportunity to network in a way that IT Pros and developers otherwise can't.
Each year at TechDays, I get to mingle with likeminded people who use Microsoft technologies throughout the Atlantic region and get to “geek out” by telling technical war stories, lamenting over technical huddles, bragging about successful solutions, and sharing our enthusiasm for the technology. I enjoy listening to other people explain what they are currently tackling within their organization and what successful solutions they've implemented. Sometimes, as a IT Pros and developers, we forget that there are many companies throughout our region that are tackling the same issues. Call me an idealist, but part of the reason I attend these conferences is to ask questions and to provide answers where possible so that we can help and get to know one another.
To me, attending TechDays is like going to a rock concert for techies. I want to go to see the big names, listening to their music, see them dance a little, see what cool things they are selling at the concession stands, and if I have a VIP pass then I get to chat a little with the big stars. As great as technology is it doesn't replace the satisfaction of personal interaction and feedback from presenters, Microsoft Most Valuable Professionals (MVPs), and subject matter experts. People typically go to these conferences hoping that someone will be able to solve their problems or point them in a new direction, but sometimes it is just nice to chat with someone who is technically savvy in the area you have interest in. The best part about talking with local vendors and Microsoft partners is that you can continue the conversation after the conference is over and see about buying or developing solutions for your company's immediate needs.
As much as I enjoy TechDays each year I realize that pulling together and putting on these events is not a small or inexpensive endeavour. I have had small glimpses of how the TechDays conferences are put together. There are months of planning involved, reviewing of attendee feedback, creating content for the sessions, finding local presenters, getting sponsors, and setting up venues across the country. There are many dedicated people who that help bring it all together smoothly and seemingly effortlessly. My limited understanding is that ticket fees and advertising rarely cover all the cost involved.
I will be attending TechDays Canada 2011 online this year, but my hope is that TechDays will be back in Halifax for 2012. The Atlantic region may not be able to afford attending TechDays annually, but if that cost were spread over two years then I think it becomes more entertainable. In the mid-2000s, TechDays stopped coming out to the Atlantic region due to poor attendance, but later returned with overwhelming online support and feedback. If you are like me and wish to see TechDays return to your region next year then you have to let the TechDays Canada organizers know! It's your feedback and support that allows them to come back each year. You can tweet your support on Twitter with #techdays_ca tag, retweet this post with the twitter button above or below this post, reply to the @techdays_ca twitter account, write your comments on the TechDays Canada Facebook page, write a blog posting about why you want TechDays to come to your region, or visit the TechDays Canada Online website and send an email explaining why TechDays events are important in your region.
Additionally, below are just a few ideas I had to improve TechDays events and reduce spending in the future for consideration. What do you think? Let me know in the comments below.
- Please offer some of the sessions live on the Internet for people to enjoy.
- Please have an online chat room if the TechDays sessions will be live on the online website. These will allow attendees across the country to ask questions and discuss session topics.
- Please ask the presenters be available online for questions after the presentation is complete.
- Let prospective attendees help choose session areas or topics. Having an online survey may help target particular topics of interest and let the Canadian Microsoft community feel like they are helping contribute to the event. A contest prize such as an Xbox 360 or Windows Phone 7 for helping to fill out the survey would be great.
- I like the TechDays shirt, however I would rather go to an online store and redeem my shirt. Unfortunately, men’s large size shirts are useless to me and would rather not receive them.
- Conference swag is cool if it is useful. Free software is always awesome. Pens and bags seldom serve a purpose. Books are great (if relevant).
- I would pay more to see big name MVPs or other Microsoft rock stars come out and speak in my region.
