Tuesday, January 8, 2013

 Event Handler Example

Requirement: In a Project collaboration SharePoint site, had a requirement to Allow users to upload only PDF files to a Document library and prevent all other files from being uploaded.

Solution: Our requirement is basically to prevent files being uploaded other than PDF, Isn't it? So lets jump to visual studio and create a Event Receiver in SharePoint to prevent all other file types.

How to Create a Event Receiver in SharePoint 2010?
Compared with MOSS 2007, Creating Event receivers in SharePoint 2010 is very easy With Visual Studio 2010. Here are the steps:

1. Create a New Visual Studio Project, Choose SharePoint >> 2010 >> Event Receiver >> Give it a Name. Say "Crescent.ProjectSites.AllowPDFOnly"

2. Make it as a Farm solution, choose the event receiver properties as in the below screen.

3. On clicking "Finish" button, Visual Studio will create the project structure as:

4. Now, in the Elements.xml file, change the ListTemplateID="101" (Which means all document Libraries) to ListURL="RelativePathOfDocLibrary" say: ProjectDocuments.

Change the <Receivers attribute
5. Update the Event receiver ItemAdding section's code as below:

?
1
2
3
4
5
6
if (!properties.AfterUrl.EndsWith("pdf"))
            {
                properties.ErrorMessage = "You are allowed to upload only PDF Files!";
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.Cancel = true;
            }


So, The complete code would be:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
 
namespace Crescent.ProjectSites.AllowPDFOnly.EventReceiver1
{
    public class EventReceiver1 : SPItemEventReceiver
    {
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
 
           if (!properties.AfterUrl.EndsWith("pdf"))
           {
               properties.ErrorMessage = "You are allowed to upload only PDF Files!";
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.Cancel = true;
           }
       }
    }
}
See the the result in action!


Drawback: This will prevent creating sub-folders which doesn't end with PDF! so if you need folder, name it like "folder.pdf" and then rename!

No comments:

Post a Comment