18/02/2012

Event Handlers - redirecting and httpcontext

I've been developing some event handlers, specifically on itemdeleting events and once again some SP quirks are making things difficult.

So lets imagine we want a simple event handler that intercepts itemdeleting, cancels the delete and redirects the user to a custom page.

the code is very simple

public override void ItemDeleting(SPItemEventProperties properties)
{
try
{
string url = properties.WebUrl.ToString();
string listname = properties.ListTitle.ToString();
using (SPSite site = new SPSite(url))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList myList = web.Lists[listname];
if (myList.BaseType == SPBaseType.GenericList)
{
if (list_allow_delete == "no")
{
properties.Status =SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_layouts/customError.aspx";


simple really...but there are quirks!!!

1. When a user deletes the item using the ribbon menu in the library or item they get successfully redirected to the custom page.




2. If the user deletes the item from the context menu they do not get redirected to the custom error page, instead the standard error message is displayed.



Bummer!

So the first thing that comes to mind is the httpcontext so we ensure the context in the constructor

some more simple code -
public class DeleteStubEH : SPItemEventReceiver
{
///
/// An item is being added.
///

///
HttpContext current;

public DeleteStubEH ()
{
current = HttpContext.Current;

}


If we check the context as we run through the code we can see a quirk.

If the user uses the ribbon to delete then the httpcontext remains throughout the code.
If the user users the context menu to delete then the httpcontext is lost!!!!

Ok, lets create a new context object to ensure we have an httpcontext object

if (current == null)
{

HttpRequest request = new HttpRequest("", web.Url, "");
current = new HttpContext(request, new HttpResponse(new StringWriter()));
current.Items["HttpHandlerSPWeb"] = web;
}

The result - still no redirection to our custom error page!!!!!

So I attempted a work around using the old redirect utility.

SPUtility.Redirect("/customError.aspx", SPRedirectFlags.RelativeToLayoutsPage, current);

Still doesn't work!!!!

I'm not sure if this is a context menu bug or not but its certainly annoying!
I will continue my search for a 'cure'

No comments:

Post a Comment