Here is some code that I find myself using in all of my web parts. You are also free to use it. I simply reuse it in all of my web parts.
It returns “DOMAIN\\USERNAME”
private string GetUserAccount()
{
// Normally used with all web parts
// By: Bill Daugherty II
// Date Modified: 08/15/2010string impersonate = string.Empty;
try
{
if (Request.QueryString["impersonate"].Length > 0) impersonate = Request.QueryString["impersonate"];
if (Request.QueryString["i"].Length > 0) impersonate = Request.QueryString["i"];
}
catch
{}
string staffMember = string.Empty;// Gets the staff SAM account
SPSite site = SPContext.Current.Site;SPServiceContext context = SPServiceContext.GetContext(site);
// Uses the profile manager that was set up in Central Admin
UserProfileManager profileManager = new UserProfileManager(context);if (impersonate.Length == 0)
{
// staffMember = SPContext.Current.Web.CurrentUser.LoginName.ToString();
staffMember = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
}
else
{
staffMember = impersonate;
}return staffMember;
}
If you find that you use this also, please just add a comment.
Bill
I am having trouble getting in all the namespaces to support this class. So far I have:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
What am I missing? Thanks!