Solved

Retireve Windows User

Posted on 2010-09-13
50
804 Views
Last Modified: 2012-05-10
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
0
Comment
Question by:asp_net2
  • 24
  • 15
  • 8
  • +2
50 Comments
 
LVL 65

Expert Comment

by:rockiroads
ID: 33666005
you can try getCurrent from WindowsIdentity http://www.spiration.co.uk/post/1367/Get%20Windows%20username%20of%20current%20user%20-%20C%23

so given the username, you set your textbox accordingly
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33666070
You can also try this

LoginUser.text = System.Windows.Forms.SystemInformation.UserName;
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33666102
Ok, when I add this line I have a "red line" under ('')  that says " Empty character literal ".

lblLoginUser.Text = WindowsIdentity.GetCurrent().Name.Split('')[1];
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33666115

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;



        }

Open in new window

0
 
LVL 12

Expert Comment

by:starlite551
ID: 33666124
If you are looking for windows forms example heres the code :
string userName = SystemInformation.UserName;

string domainName = SystemInformation.UserDomainName;

Open in new window

0
 
LVL 16

Expert Comment

by:kris_per
ID: 33666132

Use single quote in Split method:

LoginUser.Text = aspUserName.Split('\\')[1];

0
 
LVL 12

Expert Comment

by:starlite551
ID: 33666188
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 ;)
0
 
LVL 35

Expert Comment

by:YZlat
ID: 33666264
protected void Page_Load(object sender, EventArgs e)
    {
        Label3.Visible = false;

        string authUserName;
        string aspUserName= Environment.UserName;
        LoginUser.Text = aspUserName;


        lbllastupdated.value = DateTime.Now.ToShortDateString();


    }
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33666275
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.SystemInformation.UserName;
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33671793
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.ToString();
    }
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33671910
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.ToString();
    }


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.NullReferenceException: 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\secure\index.aspx.cs    Line: 23
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33672279

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().Name;



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();

    }

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33672412
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?
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33672558

> 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;

        }

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33674334
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.SystemInformation.UserName will return just the name.

Regarding getting full name, you could try using DirectoryServices. You need to add a project reference to System.DirectoryServices.AccountManagement 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.






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;

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33678434
Hi rockiroads,

>> By the way did this not work for you then? System.Windows.Forms.SystemInformation.UserName 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.InteropServices.COMException: An operations error occurred.


Source Error:

Line 38:         lblLastUpdated.Value = System.DateTime.Now.ToString();
Line 39:
Line 40:         fullName = UserPrincipal.Current.GivenName + " " + UserPrincipal.Current.Surname;
Line 41:         displayName = UserPrincipal.Current.DisplayName;
Line 42:


Source File: c:\Inetpub\wwwroot\PSSA\secure\index.aspx.cs    Line: 40
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33679068
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.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33679124
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
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33679126
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.
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33681285

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;" in the top of the .cs file. (I hope you would have figured that already; but just in case).

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;

        }

    }

}

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33682048
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.AccountManagement;
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.ToString();

        //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.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;
    }
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33682472

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..
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33682693
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.ToString();

        //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.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;
    }
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33683324
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.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33688070
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.SystemInformation.UserName

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?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 65

Expert Comment

by:rockiroads
ID: 33688155
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.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33688525
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
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33701933
Hello rockiroads,

I have been connected to my network which is also connected to AD.

0
 
LVL 16

Expert Comment

by:kris_per
ID: 33702124

@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?
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33702283
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
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33702527
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.
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33702774

First you have to decide which of the following to use:

WindowsIdentity.GetCurrent().Name
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().Name OR User.Identity.Name.
=> 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.

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33702786
I will use whatever you think is best to use.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33702974
Is this vb.net or c# I am assuming it is vb.net but some solutions given in c#
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33702988
my bad, I just re-read initial question - u want c#
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703029
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
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;

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703035
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;
        }

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703044
Forgot to mention the name spaces I used




using System.Security.Principal;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Configuration;

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703075
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

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;
    }

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703077
The code was created and tested on asp.net and c#
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33703202
Hi rockiroads,

would you be able to combine the code for me? I'm not sure how to put it all together.
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703300
Post your page_load code, I will add my code into it

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33703310
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.ToString();

        lblStudentError.Text = String.Empty;
    }
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703633
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)

<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>

Open in new window

0
 
LVL 65

Accepted Solution

by:
rockiroads earned 500 total points
ID: 33703658
The modify your page load to set these labels and include the 3 extra functions

If you are connected to your network, I would expect UserPrincipal and kris's WinNT method to work.
Ignore the directory entry cos of the password requirement but you can try it entering your password.


using System;
using System.Security.Principal;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string wiName = null;
        string domainName = null;
        string domainAndUserName = null;
        string userName = null;
        string fullName = null;
        string displayName = null;
        int i;

        domainAndUserName = WindowsIdentity.GetCurrent().Name;
        i = domainAndUserName.LastIndexOf("\\");
        userName = domainAndUserName.Substring(i + 1); // Store text after \
        domainName = domainAndUserName.Substring(0, i); // Store text before \

        lblLoginUser.Text = userName;
        lblWindowsUser.Text = System.Windows.Forms.SystemInformation.UserName;
        lblDomainName.Text = domainName;
        lblDomainUser.Text = domainAndUserName;

        lblStudentError.Text = String.Empty; 
        lblLastUpdated.Text = System.DateTime.Now.ToString();

        try
        {
           // fullName = UserPrincipal.Current.GivenName + " " + UserPrincipal.Current.Surname;
            lblUserPrincipalName.Text = UserPrincipal.Current.DisplayName;
        }
        catch (Exception ex)
        {
            lblUserPrincipalName.Text = ex.Message;
        }

        try
        {
            lblDirName.Text = GetNameUsingDirectoryEntry(userName, "password");
        }
        catch (Exception ex)
        {
            lblDirName.Text = ex.Message;
        }

        try
        {
            lblWinNTName.Text = GetNameUsingWinNT(domainName, userName);
        }
        catch (Exception ex)
        {
            lblWinNTName.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;
    }

    public string GetNameUsingWinNT(string domainName, string Username)
    {
        string fullName;
        DirectoryEntry de = null;

        try
        {
            de = new System.DirectoryServices.DirectoryEntry("WinNT://" + domainName + "/" + Username);
            fullName = de.Properties["FullName"].Value.ToString(); 
        }
        catch (Exception ex)
        {
            fullName = Username + ":" + ex.Message;
        }

        return fullName;
    }
}

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 33703662
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.cs    Line: 27
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33703781
the code you posted you have

lblLoginUser.Value = aspUserName.Split('\\')[1];

change to

lblLoginUser.Text = aspUserName.Split('\\')[1];
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33715639
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.SystemInformation.UserName;
Line 35:         lblDomainName.Text = domainName;
Line 36:         lblDomainUser.Text = domainAndUserName;
 
Source File: c:\inetpub\wwwroot\2010 PSSA\Default.aspx.cs    Line: 34
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33717332
Comment out or remove live 34
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33717335
this line lblWindowsUser.Text = System.Windows.Forms.SystemInformation.UserName;
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now