Archive for March 15, 2014

Most viewed documents in SharePoint 2010

The Task

You want to see the top 10 most viewed documents in a library

The Answer

1. Enable the two reporting features in your site collection features.

Enable the reporting features

2. Go to the list and click on “Library Settings” in the ribbon

Library Settings

3. Click on “Information management policy settings” under “Permission and Management”

Information management policy settings

4. Click on document

5. Activate the checkbox “Enable Auditing” and select “Opening or downloading documents, viewing items in lists, or viewing item properties”

Enable Auditing

Now the auditing is enabled and each time when an item in the doclib is viewed a log entrie is generated. You can limit the size of the lib in the site collection settings under “Site collection audit settings” in the group “Site Collection Administration”. Here you can specify that the log should be holded for a period of time.

6. Create a custom webpart or control. Here is the sample code to get the entries you want

 using (SPSite site = new SPSite(mUrl))  
 {  
   using (SPWeb web = site.OpenWeb())  
   {  
     SPList list = web.Lists[mListName];  
     SPAuditQuery spQuery = new SPAuditQuery(site);  
     spQuery.RestrictToList(list);  
     SPAuditEntryCollection auditCol = site.Audit.GetEntries(spQuery);      
     // Getting Audits  
     foreach (SPAuditEntry entry in auditCol)  
     {  
       if (entry.ItemType == SPAuditItemType.Document && entry.Event == SPAuditEventType.View)  
       {                
         // Some Code to cumulate results or linq perhaps  
         // by entry.ItemIds in to an other list or array  
       }  
     }  
     // Show top ten  
     SPListItem item = null;  
     foreach (Guid guid in topTenList) {  
       item = list.GetItemByUniqueId(guid);  
       Console.WriteLine("Item: {0}", item.Name);  
     }  
   }  
 }  

You have to cumulate the results and display the top ten. This is at the same time the disadvantage of this solution. If you have large lists, the accumulation can be time consuming. A solution for that can be a timer job which writes the nr into hidden field in the library or an object cache.

Additional info

SharePoint offers a webanalytics webpart out of the box. It is within the “Content Rollup” webparts group. To use the webanalytics webparts, the webanalytics service must be started. The webanalytics webparts uses a webanalytics service proxy to get the data. Unfortunately the proxy class is internal. I couldn’t found any API to access the webanalytics data, perhaps Microsoft will provide it later. The reporting db offers some stored procedures, but they were too complicated for me.