Check-In documents automatically after uploading to Sharepoint

For the last two days, we’ve been suffering from this problem where, we need the following features:

  • Support for Sharepoint library versioning
  • Documents need to be checked out before one can edit
  • Whenever a new document has been uploaded, it needs to be in checked-in state (we have a custom workflow which fires on document upload, it requires the document to be in checked-in state)

Now, if we disable the force checkout option from library settings, multiple persons can open and edit the same document, which obviously we don’t want. On the other hand, our workflow simply wont trigger on new document upload because the newly uploaded document remains checked-out. If we manually check-in the document, the workflow follows immediately. The bottom-line is, we need a post-upload event to check-in the uploaded document forcefully.

Sharepoint allows developers to create Event Receiver handlers which can be used to override sharepoint events on various levels. On this occasion, we need to override the ItemAdded method of Document Library. For this, we added a new Event Receiver item within our workflow project. Sandboxed mode was chosen for this purpose. From the Visual Studio wizard’s list of events, select An item was added fromĀ  List Item Events on Document Library. This will create a new class file with the ItemAdded method overridden. We just have to write our own code.


using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace CustomItemAdded.EventReceiver1
{
    public class EventReceiver1 : SPItemEventReceiver
    {
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           SPFile thisFile = properties.ListItem.File;

           if (!thisFile.CheckOutType.Equals(SPFile.SPCheckOutType.None))
           {
               thisFile.CheckIn("Checked in by custom event handler.");
           }
       }
    }
}