Friday, June 19, 2009

Getting a download count for the documents

Scenario:
Getting a download count for the documents.

Solution:
I personally feel this may not be the best way to get an accurate counter. But if this is just to get an idea of document popularity , then this will work.

Code below shows my test console application , this need need to run in timer job to able to update the counter regularly.

Code:

using Microsoft.SharePoint;

namespace Training {

class Program
{
static void Main(string[] args)
{
var lastVersion = "N/A";

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (var elevatedSiteCollection = new SPSite("http://localhost"))
{
using (var elevatedSite = elevatedSiteCollection.OpenWeb())
{
var list = elevatedSite.Lists["Shared Documents"];
var item = list.Items.GetItemById(6);

var wssQuery = new SPAuditQuery(elevatedSiteCollection);
wssQuery.RestrictToListItem(item);
SPAuditEntryCollection auditCol = elevatedSite.Audit.GetEntries(wssQuery);

item["Counter"] = 0;
foreach (SPAuditEntry entry in auditCol)
{
if ((entry.Event == SPAuditEventType.View) ||
(entry.Event == SPAuditEventType.View))
{
if ((lastVersion == "N/A") ||
(ParseVersionNumber(entry.EventData) == lastVersion)) {
item["Counter"] = int.Parse(item["Counter"].ToString()) + 1;
}
else {
lastVersion = ParseVersionNumber(entry.EventData);
}

}
}
item.SystemUpdate(false);
}
}
});
}

static string ParseVersionNumber(string versionString)
{
try
{
int startMajor = versionString.IndexOf("<Major>") + 7;
int endMajor = versionString.IndexOf("</Major>");
int lengthMajor = endMajor - startMajor;
int startMinor = versionString.IndexOf("<Minor>") + 7;
int endMinor = versionString.IndexOf("</Minor>");
int lengthMinor = endMinor - startMinor;

string majorNumber = versionString.Substring(startMajor, lengthMajor);
string minorNumber = versionString.Substring(startMinor, lengthMinor);

if (majorNumber == "0" && minorNumber == "-1")
return "N/A";

return majorNumber + "." + minorNumber;
}
catch{
return "N/A";
}
}
}
}
Follow me on Twitter

0 comments: