Thursday, June 18, 2009

Programatically reading the My Links into datatable

Scenario:
Webpart to display all the my links

Solution:
Create a simple webpart


Code:

using System.Data;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

static DataTable GetQuickLinks(SPSite siteCollectionUrl, string loginName){
// string siteCollectionUrl = @"http://localhost";
// string loginName = @"domain\username";
var quickLinksTable ;

using (SPSite siteCollection = new SPSite(siteCollectionUrl))
{
using (SPWeb webSite = siteCollection.OpenWeb())
{
ServerContext serverContext = ServerContext.GetContext(siteCollection);
UserProfileManager userProfileManager = new UserProfileManager(serverContext);

if (userProfileManager.UserExists(loginName))
{
// Retreive the user profiles.
UserProfile userProfile = userProfileManager.GetUserProfile(loginName);

// Retreveing Quick Links Items from User Profile.
QuickLinkManager quickLinkManager = userProfile.QuickLinks;
QuickLink[] links = quickLinkManager.GetItems();

// Moving Items from Array of links to Data Table to bind with the Grid
quickLinksTable = new DataTable();

quickLinksTable.Columns.Add(new DataColumn("Title", typeof(System.String)));
quickLinksTable.Columns.Add(new DataColumn("Url", typeof(System.String)));

foreach (QuickLink oUserQuickLinks in links)
{
var rowLinks = quickLinksTable.NewRow();
rowLinks["Title"] = oUserQuickLinks.Title;
rowLinks["URL"] = oUserQuickLinks.Url;
quickLinksTable.Rows.Add(rowLinks);
}
}
}
}
return quickLinksTable;
}
Note:
Make sure you reference Microsoft.Office.Server.UserProfiles namespace and not Microsoft.SharePoint.Portal, as Microsoft.SharePoint.Portal is obsolete.
Article:
User Profile and Social Networking , User profile and web services
microsoft.office.server.userprofiles.quicklinkmanager
Follow me on Twitter

0 comments: