Getting portal context

In WebPart developement, many a times, we'd want to retrieve the context of the current site and do some operations based on it. A simple and most common scenario is retrieving the user information from the site context.

There are different ways to do this in SharePoint, but the below is kool since it doesn't require any hard coding and it works of all our portal, site and mysites.

string goodUrl = Page.Request.Url.ToString();

int startCount = 7;

/* this is to rip-off https:// unless you are using https:// in which case 7 needs to be 8 */

int index = goodUrl.IndexOf("/",startCount,goodUrl.Length-(startCount+1));

goodUrl = goodUrl.Substring(0,index);

SPSite site = new SPSite(goodUrl);

Guid guid = site.ID;

PortalContext portalContext = PortalApplication.GetContext(guid);

UserProfileManager profileManager = new UserProfileManager(portalContext);

UserProfile profile = profileManager.GetUserProfile(HttpContext.Current.User.Identity.Name);

Hope the above was helpful!