"Attempted to read and write protected memory. This is often an indication that other memory is corrupt" error when implementing ItemCheckingOut event handler in MOSS 2007/WSS 3

If you ever tried implementing ItemCheckingOut event handler wanting to prevent end users from checking out documents if certain business rules doesn't meet, you typically would implement the "ErrorMessage" & "Cancel" properties of SPItemEventProperties.

However, when you do this, you might have seen the below error:

"Attempted to read and write protected memory. This is often an indication that other memory is corrupt"

While this is under investigation, here's a smart mechanism to work-around this. It isn't as elegant as "ErrorMessage" & "Cancel" would be if they worked the way they should. But it's a pretty neat approach and fulfills the requirement.

Instead of implementing "ErrorMessage" & "Cancel", just use the following code snippet:

properties.Status = SPEventReceiverStatus.CancelNoError;

Once you install the event handler library, you will see a message box with the following message in SharePoint UI, when you try checking out a document:

This document could not be checked out. You may not have permission to check out the document or it is already checked out or locked for editing by another user.

Though the error message isn't that descriptive and looks more like a "generic" one, the main purpose of not allowing users to check out document if they don't meet certain business rules is achieved.

Keep hacking!