Tuesday, August 21, 2012

Quick C# Code to get the Current Windows User in a WebApp and do Something (like a lookup against a Database) with it.

I (not actually that recently anymore) changed positions from IT to development, and since it will probably be years before I'm an expert, I haven’t had much to post, lest I get another “Duh” comment.  I have no pride, so I’m going to start posting what I’m sure are ridiculously basic snippets in case they're helpful.

This isn’t particularly advanced.  I wanted to capture the windows username of the current user minus the domain, and look it up against an employee database to find employee info.  Basic, but can be cannibalized for a lot of basic operations on a username.

Things not to do:  For a WebApp, don’t get  WindowsIdentity.GetCurrent().Name;  this will appear to work while you’re debugging, but once it’s running, it will pull the User Account of the application pool.   I haven’t been able/didn’t try to test kerberos/pass-through authentication with it, but I’m guessing in that case the app id would return the current user id – still seems like a lot more work than getting it at the front door.

Things I don’t understand:  So many things, but in particular… How come Microsoft recommend using “using” specifically excluding IDisposable.Dispose and try…catch, but when I run code analysis it complains

Warning    7    CA2000 : Microsoft.Reliability : In method 'mymethod' call System.IDisposable.Dispose on object 'connectionobject' before all references to it are out of scope.

Weirdness notwithstanding, In the example below, I'm calling a stored procedure to look up employeeid in a database table, but any operation could be substituted.

using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Security.Principal;

      protected string GetEmployeeIDfromUname()  //returns a string, if you don't want to return anything use protected void
{
//Do not get the string below unless you want to know who the application is running as
                   //String empuname = WindowsIdentity.GetCurrent().Name; 
                   //Get Windows UserName of current user
string strEmpUname = HttpContext.Current.User.Identity.Name.ToString();
string strEmpUname parsed = strEmpUname.Substring(strEmpUname.LastIndexOf('\\') + 1); //Parse username to remove the domain name (remove everything up to and including the \)
string strEmployeeID; //variable to hold the return value;

//This section can be replaced by whatever action you want to do.
                      using (SqlConnection connectionEmpID = new SqlConnection("Your Connection String")) //Instantiate the connection and build the command as executable code and parameters 
{
SqlCommand cmdEmpID = new SqlCommand();
cmdEmpID = new SqlCommand("YourProc", connectionEmpID);
cmdEmpID.CommandType = CommandType.StoredProcedure;
//Pass the parsed username to the procedure
cmdEmpID.Parameters.Add("LOGINNAME", SqlDbType.VarChar).Value = strEmpUnameParsed ;
SqlParameter empidret = cmdEmpID.Parameters.Add("@EMPIDRET", SqlDbType.Int);
//define the output (Employee Number)
empidret.Direction = ParameterDirection.Output;
cmdEmpID.Connection.Open();
cmdEmpID.ExecuteNonQuery();
strEmployeeID = cmdEmpID.Parameters["@EMPIDRET"].Value.ToString();
}

return strEmployeeID;
}

No comments:

Post a Comment