Tuesday, January 19, 2010

Fetching Sharepoint User Information dynamically

Hi All,
In sharepoint A user account Information can be fetched out on the fly like Name,Picture,Attachments,About Me etc etc.
In a requirement of my Project i need to find the attachment of the Sharepoint User.

First of all let me know you all that when a user is created Sharepoint internally creates a List called as "User Information List".From this list we can get everything related to SharePoint User.

So here i go with the code snippet:


SPSite objSite = new SPSite(http://YourServerName/YourSiteName);
SPWeb objWeb = objSite.OpenWeb();
SPUser spusr = objWeb.CurrentUser;
SPList list = objWeb.SiteUserInfoList;

SPUserCollection users = objWeb.SiteUsers;
objWeb.AllowUnsafeUpdates = true;
string userId = Request.QueryString["UserId"].ToString();
string userName = "";
foreach (SPUser us in users)
{
if (userId == us.ID.ToString())
{
userName = us.LoginName;
}
}
SPListItem LstItem = list.Items.GetItemById(Convert.ToInt32(userId));
Tempimage.ImageUrl = LstItem.Attachments.UrlPrefix + "/" + LstItem.Attachments[0].ToString() ;



Well the catch here is the Last 2 lines where u give the attachment(here a JPeg image) its source.TempImage is an ASP:Image control.


Similary if you want to update the Profile Picture of a SP User..here you may go like this.

Microsoft.SharePoint.SPList list = web.Lists["User Information List"];
Microsoft.SharePoint.SPUser u = web.SiteUsers["domain\user1"];
Microsoft.SharePoint.SPListItem it = list.Items.GetItemById(u.ID);

it["Picture"] =”http://sharepointApp/sites/wss/photos/abc.jpg”;
it.Update();

Also, you are able to add a custom field to user profile like this:

Microsoft.SharePoint.SPList list = web.Lists["User Information List"];if (!list.Fields.ContainsField("Favorites")){ list.Fields.Add("Favorites", SPFieldType.Text, false); list.Update();}



Do visit for more ideas:
http://www.zimmergren.net/archive/2008/06/25/sharepoints-hidden-user-list-user-information-list.aspx

http://furuknap.blogspot.com/2009/08/sharepoint-user-information-list.html

http://vspug.com/jimyang/2006/12/05/update-wss-3-0-user-profile-programmatically/


Hope it helps.


Thanks,
Nitin Sharma