Saturday, June 6, 2009

HTTPModule to monitor File downloaded

Scenario:
Easy way to see who downloaded what.

Solution:
HTTPModule can help.

Code:


using System;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace SPCustomHTTPModule
{
public class CustomHttpModule :IHttpModule
{
public void Init(HttpApplication context)
{
context.PostAuthenticateRequest += ContextPostAuthenticateRequest;
}

static void ContextPostAuthenticateRequest(object sender , EventArgs e)
{
var app = sender as HttpApplication;
if (app != null)
{
string requesturl = app.Request.Url.ToString();
if (requesturl.EndsWith(".docx") || requesturl.EndsWith(".pdf"))
{
CreateEntry(requesturl, app.Request.LogonUserIdentity.Name);
}
}
}
public static void CreateEntry(string fileUrl,string userName)
{
const string rootSite = "http://localhost";
const string listName = "Links";


using (var site = new SPSite(rootSite))
{
using (SPWeb web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[listName];

SPListItem listItem = list.Items.Add();

listItem["Title"] = "File downloaded ";
listItem["Comments"] = userName + " downloaded " + SPEncode.UrlEncodeAsUrl(fileUrl);
listItem.Update();
web.AllowUnsafeUpdates = false;
}
}
}

public void Dispose() { }
}
}
Web.Config( Add to httpModules section):
<add name="SPCustomHTTPModule" type="SPCustomHTTPModule.CustomHttpModule, SPCustomHTTPModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a56fc096c595e650" />
Articles:
HTTP Handlers and HTTP Modules Overview

Follow on Twitter

0 comments: