“who” is “where” given a map of SharePoint ?

Once I got a request from one of my colleagues in MS and his customer wants to find out “who” is “where” given a map of SharePoint. So, if there is a Site A being visited by X and Y and X happens to be interacting docLib B – is there a way one could query either the object model / database to find out.

1. Who is at Site A

Ans. X and Y

2. Who is uploading a document into dobLib B

Ans. X

It was really an interesting requirement, I had researched to find out a way and couldn’t find any built in feature to get this information except Auditing. Once you enable auditing it will log type of events that a specific user performing on a site in a table “AuditData”. You can see the user id and the type of objects (whether on a site, list, list item etc) and the occurred date in this table. Also you can pull the same details through object model.

I have written the following code snippet in a .NET console based application and was able to retrieve that information. I hope this will be helpful if anybody got this kind of requirement.

    1: static void Main(string[] args)
    2:         {
    3:             using (SPSite oSite = new SPSite("http://blrs2r04-08:31990"))
    4:             {
    5:                 using (SPWeb oWeb = oSite.OpenWeb())
    6:                 { 
    7:                     SPAuditQuery newQuery = new SPAuditQuery(oSite);
    9:                     newQuery.SetRangeEnd(DateTime.Now); //Retrieve information 
   11:                     SPAuditEntryCollection oAuditEntries = oSite.Audit.GetEntries(newQuery);
   13:                     foreach (SPAuditEntry oAudit in oAuditEntries)
   14:                     {
   16:                         Console.WriteLine(oWeb.AllUsers.GetByID(oAudit.UserId).ToString() + oAudit.ItemType.ToString() + oAudit.EventName +  oAudit.Occurred.ToString());
   18:                     }                    
   20:                 }
   21:             }
   22:             Console.ReadLine();
   23:         }