Wednesday, September 17, 2008

Reading Change Log for a User Profile

Code:

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

namespace ChangeLog
{
class Program
{
static void Main(string[] args)
{
try
{
using (SPSite spSite = new SPSite(@"http://localhost"))
{
ServerContext siteContext = ServerContext.GetContext(spSite);
UserProfileManager pmManager = new UserProfileManager(siteContext);

// This gets some subset of changes to a user profile

// Display the changes that have occurred in the last month
DateTime dtNumberDays =
DateTime.UtcNow.Subtract(TimeSpan.FromDays(30));
// Create a change token to compare the number of days
UserProfileChangeToken upChangeToken =
new UserProfileChangeToken(dtNumberDays);

// Create a query object to determine which changes are displayed
UserProfileChangeQuery QueryAnniversayAndColleagues =
new UserProfileChangeQuery(false, true);
QueryAnniversayAndColleagues.ChangeTokenStart = upChangeToken;
QueryAnniversayAndColleagues.Anniversary = true;
QueryAnniversayAndColleagues.Colleague = true;

string strUserName = "domain\\sandeep";

if (pmManager.UserExists(strUserName))
{
UserProfile spMyUser = pmManager.GetUserProfile(strUserName);

UserProfileChangeCollection MyUserProfileChanges = spMyUser.GetChanges(QueryAnniversayAndColleagues);

foreach (UserProfileChange MyUserChange in MyUserProfileChanges)
{
Console.WriteLine(MyUserChange.EventTime.ToString());
if (MyUserChange is UserProfileAnniversaryChange)
{
UserProfileAnniversaryChange AnniversryEvent =
(UserProfileAnniversaryChange)MyUserChange;
Console.WriteLine(AnniversryEvent.Anniversary);
Console.WriteLine(AnniversryEvent.ProfileProperty);
}
else if (MyUserChange is UserProfileColleagueChange)
{
UserProfileColleagueChange ColleagueEvent = (UserProfileColleagueChange)MyUserChange;
}
}
}
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}

4 comments:

Chirag Patel September 25, 2009 at 2:34 PM  

Sandeep,

Is there a way to get a list of all users that change their profiles within let's say last day?

I guess I could loop through all users and check if they have updated their userprofile but that may have a performance hit if there is a large list of users.

Thank's

Chirag

Sandeep September 25, 2009 at 7:24 PM  

Chirag yes this is possible but using
UserProfileChangeQuery(true, true) object

Chirag Patel September 28, 2009 at 4:22 PM  

I've tried that but it returns a collection of all changes, what I mean by that is if UserA modifies 3 different properties on his profile (i.e. AboutMe, CellPhone, and Office) 3 records are returned for UserA in the UserProfileChangeCollection. I just want a collection of users that have made changes to their profiles no a list of all the changes also.

Thoughts?

Sandeep September 28, 2009 at 4:41 PM  

once u get the change set , u can easily get the unique rows ( by user ) using LINQ or iteration