Friday 27 August 2010

Create Activity Feed Event by Non Admin Users

To Start with i was really excited about Activity Feed Stuff Sharepoint 2010 is providing but then when i tried using object model i realised SPServiceContext doesnt support impersonation directly. It requires HttpContext to be impersonated so that a non User Profile Admin User can also create Events .After lots of googling and modifying/updating the logic a bit , just want to share how i did this

SPServiceContext poweredCtx = null;
SPUser currentUser = SPContext.Current.Web.CurrentUser;
HttpContext currentHttpContext = HttpContext.Current;
try
{
Guid siteId = SPContext.Current.Site.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite aSite = new SPSite(sampleSite))
{
using (SPWeb web = aSite.OpenWeb())
{
SPServiceContext currentCtx = SPServiceContext.Current;
SPUser user = web.CurrentUser;
web.AllowUnsafeUpdates = true;
/*
* Impersonate here ....
*/
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(wi, user.LoginName);
HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);
WindowsIdentity wi2 = WindowsIdentity.GetCurrent();
poweredCtx = SPServiceContext.GetContext(HttpContext.Current);

m_UPM = new UserProfileManager(poweredCtx);
/*
* Create Events here and publish them
*/
}
}
});
}
finally
{
//undo the impersonated httpcontext very much required
HttpContext.Current = currentHttpContext;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(wi, currentUser.LoginName);
HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);
}


Big Thanks to STEVE CURRAN
Reference :http://sharepointfieldnotes.blogspot.com/2010/02/creating-sp2010-social-comments.html