zondag 10 oktober 2010

SharePoint 2010 custom errorpage when canceling event receiver

Event receivers are one of the most used functionalities within SharePoint. They allow us to run our own custom code when certain events are triggered. You also have the ability to cancel operations. For example, when adding n item to a custom list and the ItemAdding event is triggered, you can cancel that operation if for example the item was created after a specific hour that day. When canceling an event, an error page is shown and this page wasn't always that user friendly. It really looked liked something went wrong instead of a more informative message. I have encountered more than one user who 'freaked out' when seeing such a page.
In SharePoint 2007 it was not possible to customize this page but in SharePoint 2010, this has become very easy. Let's take a look at how to do this:

1. Create a new application page
In your Visual Studio 2010, create a new item, choose application page, give it a name. Visual Studio will automatically create a structure within the project. The application page exists of an ASPX file and two CS files for the designer and the code behind. You can edit the ASPX file to your needs so for example you can add logo's, texts and other stylings. Because it's a regular ASPX file, you can of course use all the available ASP.NET controls. Using the code behind file you can do more dynamic stuff. For example, we can send some URL query strings to the page. The code behind can pick them up and use their values.

2. In your event receiver, point to the correct custom error page
When you want to cancel your event receiver, use these two lines of code.


properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl; 
properties.RedirectUrl = "/_layouts/EventReceiverProject1/CustomErrorPage.aspx?Error=" + errorMessage;
As you can see, an URL query string is passed to the page. This variable holds the actual error message so we can use the same custom application page for each different cancel operation.

3. Result
If everything goes well, your custom application page will be shown as a popup upon canceling, just as the out of the box message.

Geen opmerkingen:

Een reactie posten