SharePoint Document Counter Counts The Document Downloads

In this post I’m going to show you how to count the document events of SharePoint site, after going through this post you will learn how to count the document downloads, views, updates, deletion, restoration etc.

I remember this solution has been asked by few people on this blog.

Before knowing the document events (add, delete, update, view etc) we have to configure the audit entry settings for the SharePoint site collection in site settings page under Site Collection Administration section (see figure 1)

Figure 1 - Configure Site Collection Audit Settings

Figure 1 – Configure Site Collection Audit Settings

On Audit Settings page check the required events to track, in this example I’m configuring for Opening or downloading documents, viewing items in lists, or viewing item properties, Editing items, Deleting or restoring items

Figure 2 - Configure Audit Events

Figure 2 – Configure Audit Events

You can also configure audit entry settings programmatically with few lines of code, here it is:

static void Main()
        {
            using (SPSite mySite = new SPSite("http://<servername>:port"))
            {
                using (SPWeb myWeb = mySite.OpenWeb())
                {
                    mySite.Audit.AuditFlags = SPAuditMaskType.All; //Configures all settings

                    //you can even configure specific settings using the below lines of code

                    //mySite.Audit.AuditFlags = SPAuditMaskType.CheckIn | SPAuditMaskType.CheckOut | SPAuditMaskType.ChildDelete |
                    //     SPAuditMaskType.Copy | SPAuditMaskType.Delete | SPAuditMaskType.Move | SPAuditMaskType.ProfileChange |
                    //     SPAuditMaskType.SchemaChange | SPAuditMaskType.Search | SPAuditMaskType.SecurityChange |
                    //     SPAuditMaskType.Undelete | SPAuditMaskType.Update | SPAuditMaskType.View | SPAuditMaskType.Workflow;

                    //mySite.Audit.AuditFlags = SPAuditMaskType.None; //Configures to none
                    mySite.Audit.Update();

                }
            }
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }

After configuring the settings, SharePoint audits the library events on item viewing, downloading, editing, deleting etc.,
SharePoint also generates audit log reports on this events in .CSV format. In this example we are reading the data from the configured audit entry logs to know event actions on documents.

Use the below code to know the event count on documents

using System;
using System.ComponentModel;
using System.Web;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace DownloadCounter.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/DownloadCounter/DownloadCounterWebPart/DownloadCounterUserControl.ascx";
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();
        string errorMessage = string.Empty;

        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);

            base.CreateChildControls();

            myGridView = new SPGridView();
            myGridView.AutoGenerateColumns = false;
            myGridView.Enabled = true;
            myGridView.AllowSorting = true;
            myGridView.AllowGrouping = true;
            myGridView.AllowGroupCollapse = true;
            myGridView.GroupField = "Event";
            myGridView.DisplayGroupFieldName = false;
            myGridView.AllowPaging = true;
            myGridView.PageSize = 50;
            myGridView.PageIndexChanging += new GridViewPageEventHandler(myGridView_PageIndexChanging);

            BoundField colEvent = new BoundField();
            colEvent.DataField = "Event";
            colEvent.HeaderText = "Event";
            this.myGridView.Columns.Add(colEvent);

            BoundField colItemType = new BoundField();
            colItemType.DataField = "ItemType";
            colItemType.HeaderText = "ItemType";
            this.myGridView.Columns.Add(colItemType);

            BoundField colDocLocation = new BoundField();
            colDocLocation.DataField = "DocLocation";
            colDocLocation.HeaderText = "DocLocation";
            this.myGridView.Columns.Add(colDocLocation);

            BoundField colOccurred = new BoundField();
            colOccurred.DataField = "Occurred";
            colOccurred.HeaderText = "Occurred";
            this.myGridView.Columns.Add(colOccurred);

            BoundField colUserName = new BoundField();
            colUserName.DataField = "UserName";
            colUserName.HeaderText = "UserName";
            this.myGridView.Columns.Add(colUserName);

            Controls.Add(myGridView);
            myGridView.PagerTemplate = null;
            GetAudEntries();
            GroupByGridView();
        }
        private void GroupByGridView()
        {
            StringBuilder scriptFunction = new StringBuilder();
            scriptFunction.Append("<script src='/SiteAssets/jquery-1.4.2.min.js' type='text/javascript'></script>");
            scriptFunction.Append("<script type='text/javascript'>");
            scriptFunction.Append("$(document).ready(function(){$('.ms-gb').each(function(){var rowNums=$(this).nextUntil('.ms-gb').length;");
            scriptFunction.Append("$(this).children(0).append('('+rowNums+')');");
            scriptFunction.Append("$(this).children(0).children(0).trigger('onclick');");
            scriptFunction.Append("});");
            scriptFunction.Append("});");
            scriptFunction.Append("</script>");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "GroupBy", scriptFunction.ToString());
        }

        private void GetAudEntries()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite mySite = SPContext.Current.Site;
                SPWeb myWeb = SPContext.Current.Web;
                DataTable myDataTable = new DataTable();
                DataRow myRow;
                SPUser user;
                try
                {
                    SPAuditQuery wssQuery = new SPAuditQuery(mySite);
                    SPAuditEntryCollection auditCol = mySite.Audit.GetEntries(wssQuery);

                    myDataTable.Columns.Add("Event");
                    myDataTable.Columns.Add("ItemType");
                    myDataTable.Columns.Add("DocLocation");
                    myDataTable.Columns.Add("Occurred", typeof(DateTime));
                    myDataTable.Columns.Add("UserName");

                    foreach (SPAuditEntry entry in auditCol)
                    {
                        if (entry.DocLocation.EndsWith(".xls") || (entry.DocLocation.EndsWith(".doc")) || (entry.DocLocation.EndsWith(".ppt")))
                        {
                            user = myWeb.SiteUsers.GetByID(entry.UserId);
                            myRow = myDataTable.NewRow();
                            myRow["Event"] = entry.Event;
                            myRow["ItemType"] = entry.ItemType.ToString();
                            myRow["DocLocation"] = entry.DocLocation;
                            myRow["Occurred"] = entry.Occurred.ToLocalTime();
                            myRow["UserName"] = user.ToString();
                            myDataTable.Rows.Add(myRow);
                        }
                    }
                    myGridView.DataSource = myDataTable;
                    myGridView.DataBind();
                }
                catch (Exception ex)
                {
                    errorMessage = ex.ToString();
                }
            });

        }
        void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            myGridView.PageIndex = e.NewPageIndex;
            myGridView.DataBind();
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Write(errorMessage);
            EnsureChildControls();
            RenderChildren(writer);
        }
    }
}

Use the above code or try to deploy the DownloadCounter.wsp
Note: In the above code we have used JQuery jquery-1.4.2.min.js files to show the count of the group by field, so please download the jquery-1.4.2.min.js file from http://code.jquery.com/jquery-1.4.2.min.js and place in some location of the SharePoint site and also refer the same source location in the above code, in this example I have placed the Jquery file in Site Assets library, you can even place in the same location if you don’t want to change the code.

After deploying the downloaded solution, please try to activate Download Counter Feature see figure 3

Figure 3 - Activate Download Counter Feature

Figure 3 – Activate Download Counter Feature

Then add the webpart to the page see figure 4

Figure 4 - Adding Download Counter WebPart to SharePoint Site

Figure 4 – Adding Download Counter WebPart to SharePoint Site

Then you can view the webpart updating on every action of documents see figure 5

Figure 5 - Download counter webPart shows the count of events for the documents

Figure 5 – Download counter webPart shows the count of events for the documents