Friday, November 4, 2011

SharePoint 2010 - Get My Personal Site URL and all other settings programmatically.

Summary

Guys, I found out a good way to retrieve the My Site > My Content(Personal Site) url using C#.

Solution

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    //Trying to get the Personal Site link or Url
    //SPContext.Current.Site = http://sp2010/
    //_url = http://sp2010:50000/personal/administrator/
                
    //The main site.
    SPSite _site = SPContext.Current.Site;
                
    //Gets the service context of the site.
    SPServiceContext _serviceContext = SPServiceContext.GetContext(_site);
                
    //On the basis of Service Manager 
    UserProfileManager _userProfileManager = new UserProfileManager(_serviceContext);
               
    //Get the User profile from User Profile Manager
    //True is passed in the constructor to create a My Site User Profile if it doesnot exists.
    UserProfile _userProfile = _userProfileManager.GetUserProfile(true);

    //Check if the Personal Site exists
    if (_userProfile.PersonalSite != null)
    {
        //This should give the link in the my site                   
        string _url = _userProfile.PersonalUrl.OriginalString;
    }
    else
    {
        //My Content(Personal Site) Does Exists
    }
});

Hope this helps someone facing issue to find a piece of code to get the url. The same way we can use _userProfile to get all the many other My Site Settings.

No comments:

Post a Comment