Friday, July 20, 2012

Download all files from SharePoint Document Library and then set Author value to Author field in every single document

SharePoint 2010 has "Author" column as a default site column. Author means a primary author of each document.

*Note: Author (InternalFieldName: _Author) and Created By (InternalFieldName: Author) is different.

Here is the screenshots in order to set author name to author column of SharePoint 2010 Document Library.



After clicking on "Grant Author(s)" button at the bottom, you wee see that all Author fields are filled up as shown below.





Here is the code I have written down:

#region Set Author Button EventHandler
protected void btnSetAuthor_Click(object sender, EventArgs e)
{
 try
 {
  SPSecurity.RunWithElevatedPrivileges(delegate()
  {
   using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
   {
    using (SPWeb elevatedWeb = elevatedSite.OpenWeb(SPContext.Current.Web.ID))
    {
     SPListItemCollection items = elevatedWeb.Lists[WebPart.PrimaryAuthorList.ToString()].Items;
     // Get a default author for an empty field
     string primaryAuthor = "";
     foreach (SPListItem item in items)
     {
      if (item != null)
      {
       primaryAuthor = item["Title"].ToString();
      }
     }
     // Set a default author with an empty field
     elevatedWeb.AllowUnsafeUpdates = true;
     // Get the length of Server Relative URL
     int serverRelativeUrlStrLength = elevatedWeb.ServerRelativeUrl.Length;
     // Get the relative url of current document library
     // docServerRelativeUrl = "/Collaboration/ConnectIntranet/Documents";
     string docLibServerRelativeUrl = SPContext.Current.RootFolderUrl;                           
     // Get the title of Document Library                           
     SPList list = elevatedWeb.GetList(docLibServerRelativeUrl);

     SPView view = list.Views["All Documents"];
     //SPView view = list.DefaultView;
     // Query all documents in Library including files under subfolders
     SPQuery squery = new SPQuery(view);
     squery.ViewAttributes = "Scope=\"Recursive\"";
     // Get the current rowLimit value from Document Library                       
     int _rowLimit = (int)squery.RowLimit;
     // Set the value as 1000 row limits
     squery.RowLimit = (uint)WebPart.RowLimitPerPage;
     SPListItemCollection listItems = list.GetItems(squery);
     foreach (SPListItem item in listItems)
     {
      if (item != null)
      {                                   
       if ((item["_Author"] == null) || (item["_Author"].ToString().Trim() == ""))
       {
        item["_Author"] = primaryAuthor;
       }
       else
       {
        // Contractor Employee ID
        if (item["_Author"].ToString().ToLower().Contains("gw"))
        {
         string logonName = string.Format("{0}{1}", @"CHINA\", (String)item["_Author"]);
         bool isDomainUser = Utilities.IsUserContainedToAD(elevatedWeb, logonName);
         // Existing User
         if (isDomainUser)
         {                                               
          SPUser user = elevatedWeb.EnsureUser(logonName);
          item["_Author"] = user.Name;
         }
         // Terminated User
         else
         {
          item["_Author"] = primaryAuthor;
         }
        }
        // All Users with FTE except a contractor
        else
        {
         bool isUserFTE = Utilities.IsUserFTE((String)item["_Author"]);
         if (isUserFTE)
         {
          string logonName = string.Format("{0}{1}", @"CHINA\", (String)item["_Author"]);
          //string logonName = string.Format("{0}{1}", @"CHINA\", item["_Author"].ToString().Trim());
          bool isDomainUser = Utilities.IsUserContainedToAD(elevatedWeb, logonName);
          // Existing User
          if (isDomainUser)
          {
           SPUser user = elevatedWeb.EnsureUser(logonName);
           item["_Author"] = user.Name;
          }
          // Terminated User
          else
          {
           item["_Author"] = primaryAuthor;
          }
         }
        }
       }
      }
      item.Update();
      // Operation Successfully Completed message
      lblMSG.Text = "Operation Successfully Completed...";
      lblMSG.ForeColor = Color.FromArgb(54, 97, 97);
      lblMSG.Font.Bold = true;
     }
     // Recover the previous value of row limit
     squery.RowLimit = (uint)_rowLimit;
     //// Operation Successfully Completed message
     //lblMSG.Text = "Operation Successfully Completed...";
     //lblMSG.ForeColor = Color.FromArgb(54, 97, 97);
     //lblMSG.Font.Bold = true;
    }
   }
  });
 }
 catch(SPException ex)
 {
  lblMSG.Text = "Error Message: " + ex.Message;
  lblMSG.ForeColor = Color.Red;
  lblMSG.Font.Bold = true;
 }
}
#endregion

No comments:

Post a Comment