Friday, November 21, 2008

Best Practices while creating custom SharePoint event handlers.

When building custom event handlers, keep the following points in mind:

1. Security:
The assembly you deploy to the Global Assembly Cache(GAC) is running with full trust. Watch out for the following:
Denial of Service attack: If a user uploads 10000 items to a list, what is the effect it will have to the systems your assembly uses.
SQL Injection attack: If a user attempts to insert SQL statements into a column of a list that your assembly uses to update a database, what mechanisms are you using to make sure the input is valid.
Cross Site scripting attack: What is the effect of adding script to a column that your assembly uses to update another area in SharePoint?


2. Performance:
Watch out for the following:

Load: What burden are you placing on your web front end servers to run the assembly each time an event occurs? Use performance counters to determine this.
Long Running Operations: Consider creating a custom SharePoint timer job. Kick off/ Schedule the Timer Job from the event rather than running all the logic inside the event. This will allow you to use the features of SharePoint to view whether the Timer Job ran successfully.
Sync vs Async Events: Synchronous events have to wait until your code completes before returning the page, whereas Asynchronous events show the page immediately.


3. Error Handling:
When using synchronous events and you decide to cancel an event, let the user know why the event was cancelled. For example, update a Task List with a message why it failed.
Log your errors so that you can determine what issue is occurring when your system is in production environment.

4. Connections
Cater for external systems being down when you are trying to connect to them. Don’t let your code / solution go belly up because you cannot connect to a database.

5. Bulk Operations
The MSDN documentation mentions that event handlers will not fire when bulk operation is occurring. For example, when a new list is created, the FieldAdding event will not fire.

6. Disabling event firing
DisableEventFiring()
Do_my_changes
EnableEventFiring()

Limitations of Event Handler in SharePoint
There is no event handlers for web.

Strangely there is no “SiteAdding”, “SiteAdded” event. However, if you really need this event you could create a “feature” to accomplish this. Features in SharePoint have a “FeatureActivated” event, where you could perform an action on creation of a site.

No comments: