Get User Name

Get User Name

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item
  • Sitecore.Security.Accounts.User

User Name C# Web Control Code

Sitecore.Data.Items.Item item = this.GetItem();
if (item == null) return;

Sitecore.Security.Accounts.User user = Sitecore.Context.User;
if (user == null) return;

string fullUserName = Sitecore.Context.GetUserName();
string justUserName = user.Name.Substring(user.Name.LastIndexOf("\\") + 1);

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag(); //Div

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and ? for question mark and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

if (!string.IsNullOrEmpty(fullUserName))
    output.Write("{0}&#58;&#160;{1}", "Full User Name", "<b>" + fullUserName + "</b><br/>");

if (!string.IsNullOrEmpty(justUserName))
    output.Write("{0}&#58;&#160;{1}", "User Name", "<b>" + justUserName + "</b>");

output.RenderEndTag(); //Div


User Name XSLT Rendering Code

<div style="font-weight:bold; width:100%; clear:both"> <br/>
<xsl:value-of select="'XSLT Rendering Real-time Output'"/>
</div>

<div style="font-size:x-small; width:100%; clear:both">
<!-- using &#58 for colon and &#160 for space -->
<p><b><xsl:value-of select="'Item'" />&#58;&#160;<sc:text field="title" select="$sc_item"/></b></p>

<xsl:value-of select="'Full Name'"/>&#58;&#160;<b><xsl:value-of select="sc:UserInfo('fullname')"/></b><br/>

</div>


User Name C# Web Control Output

Full Name: 
User Name: extranet\Anonymous
User: Anonymous


Notes

  • All strings containing account names must include the domain name in the format domainName\accountName

Sources