Brian
asked on
Retireve Windows User
Hello,
I have the following VB code that retrieves the Users Windows UserName and I need help converting this to C#.
VB CODE:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label3.Visible = False
Dim authUserName As String
Dim aspUserName As String
authUserName = User.Identity.Name
aspUserName = Principal.WindowsIdentity. GetCurrent .Name
LoginUser.Text = aspUserName.Split("\")(1)
lbllastupdated.Value = System.DateTime.Now
End Sub
I have the following VB code that retrieves the Users Windows UserName and I need help converting this to C#.
VB CODE:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label3.Visible = False
Dim authUserName As String
Dim aspUserName As String
authUserName = User.Identity.Name
aspUserName = Principal.WindowsIdentity.
LoginUser.Text = aspUserName.Split("\")(1)
lbllastupdated.Value = System.DateTime.Now
End Sub
You can also try this
LoginUser.text = System.Windows.Forms.Syste mInformati on.UserNam e;
LoginUser.text = System.Windows.Forms.Syste
ASKER
Ok, when I add this line I have a "red line" under ('') that says " Empty character literal ".
lblLoginUser.Text = WindowsIdentity.GetCurrent ().Name.Sp lit('')[1] ;
lblLoginUser.Text = WindowsIdentity.GetCurrent
Your vb code converted to c# as following:
protected void Page_Load(object sender, System.EventArgs e)
{
Label3.Visible = false;
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent().Name;
LoginUser.Text = aspUserName.Split("\\")[1];
lbllastupdated.Value = System.DateTime.Now;
}
If you are looking for windows forms example heres the code :
string userName = SystemInformation.UserName;
string domainName = SystemInformation.UserDomainName;
Use single quote in Split method:
LoginUser.Text = aspUserName.Split('\\')[1]
You might always try this for any conversions from vb.net to c#.net :
http://www.developerfusion.com/tools/convert/vb-to-csharp/
Just paste ur code there and click on convert button.. Simple and fast ;)
http://www.developerfusion.com/tools/convert/vb-to-csharp/
Just paste ur code there and click on convert button.. Simple and fast ;)
protected void Page_Load(object sender, EventArgs e)
{
Label3.Visible = false;
string authUserName;
string aspUserName= Environment.UserName;
LoginUser.Text = aspUserName;
lbllastupdated.value = DateTime.Now.ToShortDateSt ring();
}
{
Label3.Visible = false;
string authUserName;
string aspUserName= Environment.UserName;
LoginUser.Text = aspUserName;
lbllastupdated.value = DateTime.Now.ToShortDateSt
}
Empty character literal - yea cos it comes up as domain\userid you have to split by slash
did the one liner work? System.Windows.Forms.Syste mInformati on.UserNam e;
did the one liner work? System.Windows.Forms.Syste
ASKER
Ok, I'm using the following code block below and so far no errors when I run it. Now the other problem is that I need this value to be stored in my DB which i have now since i'm using a HiddenField to collect the value but I need to display the value within a label control. How can I use the same code below but bind that value to a label control called lblUser?
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
}
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
lblLoginUser.Value = aspUserName.Split('\\')[1]
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri
}
ASKER
Hi all,
When I run the following code below now I receive the error message below.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
}
ERROR:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceExcept ion: Object reference not set to an instance of an object.
Source Error:
Line 21:
Line 22: authUserName = User.Identity.Name;
Line 23: lblLoginUser.Value = aspUserName.Split('\\')[1] ;
Line 24:
Line 25: lblDomainUser.Text = authUserName;
Source File: c:\Inetpub\wwwroot\PSSA\se cure\index .aspx.cs Line: 23
When I run the following code below now I receive the error message below.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
lblLoginUser.Value = aspUserName.Split('\\')[1]
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri
}
ERROR:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceExcept
Source Error:
Line 21:
Line 22: authUserName = User.Identity.Name;
Line 23: lblLoginUser.Value = aspUserName.Split('\\')[1]
Line 24:
Line 25: lblDomainUser.Text = authUserName;
Source File: c:\Inetpub\wwwroot\PSSA\se
Reason for the error is: aspUserName is not assigned a value and remains null.
To fix it:
Add the below line before the Split method.
aspUserName = WindowsIdentity.GetCurrent
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent().Name;
lblLoginUser.Value = aspUserName.Split('\\')[1];
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToString();
}
ASKER
Hi kris_per,
Yes, that did work. But is there a way to drop the DOMAIN NAME so that it just displays the username? Also, is there a way to retrieve the Full Name from AD rather than the UserName?
Yes, that did work. But is there a way to drop the DOMAIN NAME so that it just displays the username? Also, is there a way to retrieve the Full Name from AD rather than the UserName?
> drop the DOMAIN NAME
Replace the line:
lblDomainUser.Text = authUserName;
To this line =>
lblDomainUser.Text = authUserName.Split('\\')[1
To get the full name from the logon name, copy the method from this link and use => http://milanl.blogspot.com/2008/08/retrieve-full-name-from-active.html
In your code, call the copied method as shown below...
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent().Name;
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1];
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToString();
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
I missed all the recent activity. When I gave you the link to WindowsIdentity I didn't realise that there was a bug to it. So sorry about that.
I know a fix already made using split but I will post what I would anyways - I make use of indexof.
By the way did this not work for you then? System.Windows.Forms.Syste mInformati on.UserNam e will return just the name.
Regarding getting full name, you could try using DirectoryServices. You need to add a project reference to System.DirectoryServices.A ccountMana gement then import that namespace i.e. using System....
This then allows you to use UserPrincipal. From this you can get the name.
See below. Two ways - one is built from given name + surname, other is using the display name.
I know a fix already made using split but I will post what I would anyways - I make use of indexof.
By the way did this not work for you then? System.Windows.Forms.Syste
Regarding getting full name, you could try using DirectoryServices. You need to add a project reference to System.DirectoryServices.A
This then allows you to use UserPrincipal. From this you can get the name.
See below. Two ways - one is built from given name + surname, other is using the display name.
string wiName = null;
string domainName = null;
string authUserName = null;
string aspUserName = null;
string fullName = null;
string displayName = null;
int i;
authUserName = WindowsIdentity.GetCurrent().Name;
i = authUserName.LastIndexOf("\\");
domainName = authUserName.Substring(0, i); // Store text before \
aspUserName = authUserName.Substring(i + 1); // Store text after \
lblLoginUser.Value = aspUserName;
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToString();
fullName = UserPrincipal.Current.GivenName + " " + UserPrincipal.Current.Surname;
displayName = UserPrincipal.Current.DisplayName;
ASKER
Hi rockiroads,
>> By the way did this not work for you then? System.Windows.Forms.Syste mInformati on.UserNam e will return just the name.
Unfortanetly not :(
Also, I'm trying to implement your code above but I'm not able to. Please see my error message below. The error is on line 40.
Server Error in '/' Application.
An operations error occurred.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServ ices.COMEx ception: An operations error occurred.
Source Error:
Line 38: lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
Line 39:
Line 40: fullName = UserPrincipal.Current.Give nName + " " + UserPrincipal.Current.Surn ame;
Line 41: displayName = UserPrincipal.Current.Disp layName;
Line 42:
Source File: c:\Inetpub\wwwroot\PSSA\se cure\index .aspx.cs Line: 40
>> By the way did this not work for you then? System.Windows.Forms.Syste
Unfortanetly not :(
Also, I'm trying to implement your code above but I'm not able to. Please see my error message below. The error is on line 40.
Server Error in '/' Application.
An operations error occurred.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServ
Source Error:
Line 38: lblLastUpdated.Value = System.DateTime.Now.ToStri
Line 39:
Line 40: fullName = UserPrincipal.Current.Give
Line 41: displayName = UserPrincipal.Current.Disp
Line 42:
Source File: c:\Inetpub\wwwroot\PSSA\se
ah, I keep forgetting this is an asp app so this could be the reason.
it could also be the reason why userprincipal is not working. let me look into that.
it could also be the reason why userprincipal is not working. let me look into that.
having keep forgetting its asp.net doh! the alternative might be this option which I found here - have a look at the last post http://forums.asp.net/t/1436712.aspx
I have got vs2010 installed (slow as anything with a core2duo 4gb laptop, damn!) but no env to run asp.net yet. I still need to set that up.
Will try the suggested code once I manage to get it running.
Will try the suggested code once I manage to get it running.
My GetFullName code above uses Directory services and a reference to System.DirectoryServices need to be added. You can do that by right-click on References => References tab => Select System.DirectoryServices. And add "using System.DirectoryServices;"
That was a tested code and it was giving my Full Name in my asp test page. Full Page code is below:
using System;
using System.Security.Principal;
using System.DirectoryServices;
namespace WebApplication5
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent().Name;
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1];
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToString();
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
}
}
ASKER
When I add your code I have a message that says "The type or Namespace Name 'DirectoryEntry' could not be found (are you missing a using directive or an essemble reference?)"
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections.Generic ;
using System.Security;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Net;
using System.Security.Principal;
using System.DirectoryServices.A ccountMana gement;
using System.DirectoryServices;
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent ().Name;
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
//string authUserName = null;
//string aspUserName = null;
//authUserName = User.Identity.Name;
//aspUserName = WindowsIdentity.GetCurrent ().Name;
//lblLoginUser.Value = aspUserName.Split('\\')[1] ;
//lblDomainUser.Text = authUserName.Split('\\')[1 ];
//lblStudentError.Visible = false;
//lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.P ropertyCol lection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections.Generic
using System.Security;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Net;
using System.Security.Principal;
using System.DirectoryServices.A
using System.DirectoryServices;
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1]
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri
//string authUserName = null;
//string aspUserName = null;
//authUserName = User.Identity.Name;
//aspUserName = WindowsIdentity.GetCurrent
//lblLoginUser.Value = aspUserName.Split('\\')[1]
//lblDomainUser.Text = authUserName.Split('\\')[1
//lblStudentError.Visible = false;
//lblLastUpdated.Value = System.DateTime.Now.ToStri
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.P
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
You need to add reference to System.DirectoryServices to the project.
In the Solution Explorer, right click on the References Node and right-click on References node => in .NET tab => scroll down and find System.DirectoryServices and double-click on it. This will add the reference to the project and you can see it by expanding the References node in Solution Explorer..
Once you did this, the error should be cleared..
ASKER
ok, this time i did not receive any errors but it's not displaying the "Display Name" just displays the user name. See attached code below.
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent ().Name;
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
//string authUserName = null;
//string aspUserName = null;
//authUserName = User.Identity.Name;
//aspUserName = WindowsIdentity.GetCurrent ().Name;
//lblLoginUser.Value = aspUserName.Split('\\')[1] ;
//lblDomainUser.Text = authUserName.Split('\\')[1 ];
//lblStudentError.Visible = false;
//lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.P ropertyCol lection coll = obDirEntry.Properties;
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent
string userFullName = GetFullName(authUserName);
// use this userFullName value in the required label
lblLoginUser.Value = aspUserName.Split('\\')[1]
lblDomainUser.Text = authUserName;
lblStudentError.Visible = false;
lblLastUpdated.Value = System.DateTime.Now.ToStri
//string authUserName = null;
//string aspUserName = null;
//authUserName = User.Identity.Name;
//aspUserName = WindowsIdentity.GetCurrent
//lblLoginUser.Value = aspUserName.Split('\\')[1]
//lblDomainUser.Text = authUserName.Split('\\')[1
//lblStudentError.Visible = false;
//lblLastUpdated.Value = System.DateTime.Now.ToStri
}
public static string GetFullName(string strLogin)
{
string str = "";
string strDomain;
string strName;
// Parse the string to check if domain name is present.
int idx = strLogin.IndexOf('\\');
if (idx == -1)
{
idx = strLogin.IndexOf('@');
}
if (idx != -1)
{
strDomain = strLogin.Substring(0, idx);
strName = strLogin.Substring(idx + 1);
}
else
{
strDomain = Environment.MachineName;
strName = strLogin;
}
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
System.DirectoryServices.P
object obVal = coll["FullName"].Value;
str = obVal.ToString();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
ASKER
Ok, if i run the following code below then when i go to the page it DOES NOT as me to login using my nework credentials which is what I NEED it to do. Also, it says Welcome, Unspecified Error instead of saying Welcome, John Doe.
Right, got my IIS environment up and running now.
I have tried 3 different ways to get the full name
By the way, the line
System.Windows.Forms.Syste mInformati on.UserNam e
did work for me, not sure why, maybe you need the namespace System.Windows.Forms. I had to put that in initially but seemed to work after removal of redundant namespaces. Weird huh.
Anyways the 3 methods I tried
1. UserPrincipal - result -> The server could not be contacted.
2. DirectoryEntry - result -> The specified domain either does not exist or could not be contacted.
3. WinNT method from kris - result -> The specified domain either does not exist or could not be contacted.
So looks like you need to be connected to the network in order to use this functionality.
Are you doing this outside say a company network on your own desktop/laptop?
I have tried 3 different ways to get the full name
By the way, the line
System.Windows.Forms.Syste
did work for me, not sure why, maybe you need the namespace System.Windows.Forms. I had to put that in initially but seemed to work after removal of redundant namespaces. Weird huh.
Anyways the 3 methods I tried
1. UserPrincipal - result -> The server could not be contacted.
2. DirectoryEntry - result -> The specified domain either does not exist or could not be contacted.
3. WinNT method from kris - result -> The specified domain either does not exist or could not be contacted.
So looks like you need to be connected to the network in order to use this functionality.
Are you doing this outside say a company network on your own desktop/laptop?
ok, I connected to my company network (remotely) and managed to get it working
UserPrincipal returned Suname, Forename
DirectoryEntry method (from that link I posted) required a password but that returned Surname, Forename
WinNT worked as well but not sure but came up as CN=username. Maybe done something wrong. Wonder if kris has tried and tested it so to confirm what I did wrong.
So confirms that the 3 methods described here appear to require a connection to the network.
UserPrincipal returned Suname, Forename
DirectoryEntry method (from that link I posted) required a password but that returned Surname, Forename
WinNT worked as well but not sure but came up as CN=username. Maybe done something wrong. Wonder if kris has tried and tested it so to confirm what I did wrong.
So confirms that the 3 methods described here appear to require a connection to the network.
Right tried a test on a local user and even then the code fails as it has to be connected to the network.
So Im afraid it looks like you have to be connected to the network, active directory and all that.
I searched the net and couldnt find anything outside of this
All the testing I did was using asp.net
So Im afraid it looks like you have to be connected to the network, active directory and all that.
I searched the net and couldnt find anything outside of this
All the testing I did was using asp.net
ASKER
Hello rockiroads,
I have been connected to my network which is also connected to AD.
I have been connected to my network which is also connected to AD.
@asp_net2,
Actually I kind of lost you in the middle. Can you describe what your app does like steps/page navigation and where does the above code come in the picture?
I am not sure then why your code is not working then. I tested it and it worked though I am using vs 2010 not express.
Just to recap now, are you using asp.nt with vb.net or c#? I know we started with vb.net but somehow ended up in c#
If its in vb.net I will rewrite my code in vb.net and post it here for you
Just to recap now, are you using asp.nt with vb.net or c#? I know we started with vb.net but somehow ended up in c#
If its in vb.net I will rewrite my code in vb.net and post it here for you
ASKER
My code works. The only thing that I would like to do is display the users Full Name from AD when they login to my application. Currently when a user logs in they only see their username and not their Full Name that is in AD.
First you have to decide which of the following to use:
WindowsIdentity.GetCurrent
OR
User.Identity.Name
These two will give different result in different config of impersonation and anonymous access. check out the following link to decide if you should use WindowsIdentity.GetCurrent
=> http://www.bluevisionsoftware.com/WebSite/TipsAndTricksDetails.aspx?Name=AspNetAccount
Then pass the Name from the correct one of (these two) to the GetFullName method above.
ASKER
I will use whatever you think is best to use.
Is this vb.net or c# I am assuming it is vb.net but some solutions given in c#
my bad, I just re-read initial question - u want c#
ok here is the code I used in c# which successfully brought back the full name
Get the username, domain name and user with domain name
Get the username, domain name and user with domain name
domainAndUserName = WindowsIdentity.GetCurrent().Name;
i = domainAndUserName.LastIndexOf("\\");
userName = domainAndUserName.Substring(i + 1); // Store text after \
domainName = domainAndUserName.Substring(0, i); // Store text before \
txtLoginUser.Text = userName;
txtWindowsUser.Text = System.Windows.Forms.SystemInformation.UserName;
txtDomainName.Text = domainName;
txtDomainUser.Text = domainAndUserName;
Get full name using UserPrincipal
try
{
// fullName = UserPrincipal.Current.GivenName + " " + UserPrincipal.Current.Surname;
txtUserPrincipalName.Text = UserPrincipal.Current.DisplayName;
}
catch (Exception ex)
{
txtUserPrincipalName.Text = ex.Message;
}
Forgot to mention the name spaces I used
using System.Security.Principal;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Configuration;
Get full name using Directory Entry
Problem with this is password required but there is a way to iterate thru all users, find the current user that way. Havent tried it but I think you can do it this way
Problem with this is password required but there is a way to iterate thru all users, find the current user that way. Havent tried it but I think you can do it this way
try
{
txtDirName.Text = GetNameUsingDirectoryEntry(userName, "password");
}
catch (Exception ex)
{
txtDirName.Text = ex.Message;
}
public string GetNameUsingDirectoryEntry(string Username, string Password)
{
string fullName;
DirectoryEntry de = new DirectoryEntry(ConfigurationManager.AppSettings.Get("ADPAth"), Username, Password, AuthenticationTypes.Secure);
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + Username + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();
if (results == null)
{
fullName = "Nothing Found";
}
else
{
de = new DirectoryEntry(results.Path, Username, Password, AuthenticationTypes.Secure);
fullName = de.Name;
}
de.Close();
return fullName;
}
The code was created and tested on asp.net and c#
ASKER
Hi rockiroads,
would you be able to combine the code for me? I'm not sure how to put it all together.
would you be able to combine the code for me? I'm not sure how to put it all together.
Post your page_load code, I will add my code into it
ASKER
Thank you rockiroads,
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent ().Name;
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
lblDomainUser.Text = authUserName.Split('\\')[1 ];
lblLastUpdated.Value = System.DateTime.Now.ToStri ng();
lblStudentError.Text = String.Empty;
}
protected void Page_Load(object sender, EventArgs e)
{
string authUserName = null;
string aspUserName = null;
authUserName = User.Identity.Name;
aspUserName = WindowsIdentity.GetCurrent
lblLoginUser.Value = aspUserName.Split('\\')[1]
lblDomainUser.Text = authUserName.Split('\\')[1
lblLastUpdated.Value = System.DateTime.Now.ToStri
lblStudentError.Text = String.Empty;
}
ok, I thought you might of done more actually
Can u try this. On your web page add these controls (you should be able to paste this in the source)
Can u try this. On your web page add these controls (you should be able to paste this in the source)
<p>
<h2>User Name</h2>
Windows Identity Username : <asp:Label ID="lblLoginUser" runat="server"></asp:Label>
<br />
System Forms Username : <asp:Label ID="lblWindowsUser" runat="server"></asp:Label>
<br />
Domain Name : <asp:Label ID="lblDomainName" runat="server"></asp:Label>
<br />
Domain Username : <asp:Label ID="lblDomainUser" runat="server"></asp:Label>
<br />
Full Name <asp:Label ID="lblFullName" runat="server" Text="FullName"></asp:Label>
<br />
<h2>Full Name</h2>
User Principal : <asp:Label ID="lblUserPrincipalName" runat="server" Text="UserPrincipal"></asp:Label>
<br />
Directoy Name : <asp:Label ID="lblDirName" runat="server" Text="DirName"></asp:Label>
<br />
WinNT : <asp:Label ID="lblWinNTName" runat="server" Text="WinNT"></asp:Label>
<br />
<h2>Misc</h2>
Last Updated : <asp:Label ID="lblLastUpdated" runat="server"></asp:Label>
<br />
Student Error : <asp:Label ID="lblStudentError" runat="server"></asp:Label>
</p>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok, I created another page with the same Page_Load code and namespaces along with your HTML markup. I ran the page and received the following error below.
Server Error in '/2010 PSSA' Application.
-------------------------- ---------- ---------- ---------- ---------- ---------- ----
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'System.Web.UI.WebControls .Label' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'System.Web.UI.WebControls .Label' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 25: authUserName = User.Identity.Name;
Line 26: aspUserName = WindowsIdentity.GetCurrent ().Name;
Line 27: lblLoginUser.Value = aspUserName.Split('\\')[1] ;
Line 28:
Line 29: lblDomainUser.Text = authUserName.Split('\\')[1 ];
Source File: c:\inetpub\wwwroot\2010 PSSA\secure\Default.aspx.c s Line: 27
Server Error in '/2010 PSSA' Application.
--------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'System.Web.UI.WebControls
Source Error:
Line 25: authUserName = User.Identity.Name;
Line 26: aspUserName = WindowsIdentity.GetCurrent
Line 27: lblLoginUser.Value = aspUserName.Split('\\')[1]
Line 28:
Line 29: lblDomainUser.Text = authUserName.Split('\\')[1
Source File: c:\inetpub\wwwroot\2010 PSSA\secure\Default.aspx.c
the code you posted you have
lblLoginUser.Value = aspUserName.Split('\\')[1] ;
change to
lblLoginUser.Text = aspUserName.Split('\\')[1] ;
lblLoginUser.Value = aspUserName.Split('\\')[1]
change to
lblLoginUser.Text = aspUserName.Split('\\')[1]
ASKER
Hi rockiroads,
this is the error message i receive when running my code:
Server Error in '/2010 PSSA' Application.
-------------------------- ---------- ---------- ---------- ---------- ---------- ----
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)
Source Error:
Line 32:
Line 33: lblLoginUser.Text = userName;
Line 34: lblWindowsUser.Text = System.Windows.Forms.Syste mInformati on.UserNam e;
Line 35: lblDomainName.Text = domainName;
Line 36: lblDomainUser.Text = domainAndUserName;
Source File: c:\inetpub\wwwroot\2010 PSSA\Default.aspx.cs Line: 34
this is the error message i receive when running my code:
Server Error in '/2010 PSSA' Application.
--------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)
Source Error:
Line 32:
Line 33: lblLoginUser.Text = userName;
Line 34: lblWindowsUser.Text = System.Windows.Forms.Syste
Line 35: lblDomainName.Text = domainName;
Line 36: lblDomainUser.Text = domainAndUserName;
Source File: c:\inetpub\wwwroot\2010 PSSA\Default.aspx.cs Line: 34
Comment out or remove live 34
this line lblWindowsUser.Text = System.Windows.Forms.Syste mInformati on.UserNam e;
so given the username, you set your textbox accordingly