Wednesday, September 12, 2007

Impersonation in SharePoint 2007 using Elevated privileges

When I was working with giving permission for the logged in user to access data from BDC , I found so many articles which talks about Impersonation ...

when Searching more for simpler method i got a method which helps in
Executing code with elevated privileges .

The code goes like this

SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated(pullUserData);
SPSecurity.RunWithElevatedPrivileges(elevatedMethod);


where pullUserData() is a void method which gets data from BDC.


private void pullUserData()
{
string userName = getUserName(); // "domain\\b" ;
userprofile.UserProfileService myuser = new UserProfileService();
userprofile.PropertyData[] userprop = null;

// here userprofile is web service method
http://localhost/_vti_bin/userprofileservice.asmx

myuser.Credentials = System.Net.CredentialCache.DefaultCredentials;
myuser.PreAuthenticate = true;
long test = myuser.GetUserProfileCount();
userprop = myuser.GetUserProfileByName(userName);

for (int i = 0; i < userprop.Length; i++)
{
if (userprop[i].Name != null)
{
if (userprop[i].Name.Trim().ToLower() == gblAttribute.Trim().ToLower())
{

if (userprop[i].Values[0] != null)
{
gblResult = userprop[i].Values[0].Value.ToString();

}

}
}
}

}