Showing posts with label SPFile.Approve. Show all posts
Showing posts with label SPFile.Approve. Show all posts

Wednesday, July 1, 2009

Auto Publish documents

SharePoint 2007 allows check-in, check out, publish and approve documents in the document libraries. This can be achieved via SharePoint object model. Here is an example in C#.

This code snippet will work for document libraries with 'Required Approval' disabled as well as enabled. If you try to approve document which does not require approval, exception will be generated.

   1:  private void publish(SPWeb web, string listName)
   2:  {
   3:      SPList list = web.Lists[listName];
   4:      web.AllowUnsafeUpdates = true;
   5:      foreach (SPListItem item in list.Items)
   6:      {
   7:          SPFile sourceFile = item.File;
   8:          try
   9:          {                    
  10:              if (sourceFile.Level == SPFileLevel.Draft  sourceFile.Level == SPFileLevel.Checkout)
  11:              {
  12:                  //Check in file 
  13:                  if (sourceFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
  14:                      sourceFile.CheckIn("System CheckIn", SPCheckinType.MajorCheckIn);
  15:   
  16:                  //Submit file for content approval 
  17:                  sourceFile.Publish("System published.");
  18:   
  19:                  //Approve file if 'Require content approval for submitted items' is enabled
  20:                  //Exception will occur trying to approve document which doesn't require approval
  21:                  if (sourceFile.Item.ModerationInformation != null)
  22:                  {
  23:                      if (sourceFile.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
  24:                          sourceFile.Approve("System approved.");
  25:                  }
  26:                  sourceFile.Update();
  27:                  _publishedDocuments.Append("<br>" + web.Url + "/" + sourceFile.Url);
  28:              }
  29:          }
  30:          catch (System.Exception ex)
  31:          {
  32:               //handle exception here
  33:          }
  34:      }
  35:      web.AllowUnsafeUpdates = false;
  36:  }