?
Solved

I need a way to programmaticly retrieve a sid when given a users full nt login by querying AD.

Posted on 2008-06-09
4
Medium Priority
?
206 Views
Last Modified: 2013-12-04
I have a database that is populated with user names "domain\user"

I need a way to query AD and select a users SID based on their login name.

I am then going to take the SID given by AD and write that information back to the database.

0
Comment
Question by:davidrickey
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 5

Accepted Solution

by:
virtuatech earned 750 total points
ID: 21745664
0
 

Author Comment

by:davidrickey
ID: 21752198
That would be great if i could access the program through vb.  Since you posted I have been trying to find a way to execute the psgetsid application and return the value back to my application for the database update.

Is there an easy way to interface psgetsid with my application?
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 750 total points
ID: 21753341
Why not using 'LookupAccountName()' (http://msdn.microsoft.com/en-us/library/aa379159(VS.85).aspx) to query the SID? See http://support.microsoft.com/kb/286182 ("How To Use Microsoft Visual Basic to Convert a Raw SID into a String SID") for an an example on how to use that function.
0
 

Author Comment

by:davidrickey
ID: 21753860
jkr,
Before your last post I found this on the internet.  Slightly modified, I was able to use it to do exactly what I needed.  Thanks for responding.
private void button1_Click(object sender, EventArgs e)
        {
            SqlDataReader dr;
            string qry = "select ntaccount from tiuser where  (sid = '' or sid is null) and (not ntaccount is null and not ntaccount = '') order by ntaccount";
            SqlConnection con = new SqlConnection("ConnectionString");
 
            SqlCommand cmd = new SqlCommand(qry, con);
 
            try
            {
                con.Open();
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    writeData(GetSid(dr.GetString(0)), dr.GetString(0));
                }
            }
            catch { }
 
        }
 
        private string GetSid(string strLogin)
        {
            string str = "";
            // Parse the string to check if domain name is present.
            int idx = strLogin.IndexOf('\\');
            if (idx == -1)
            {
                idx = strLogin.IndexOf('@');
            }
 
            string strDomain;
            string strName;
 
            if (idx != -1)
            {
                strDomain = strLogin.Substring(0, idx);
                strName = strLogin.Substring(idx + 1);
            }
            else
            {
                strDomain = Environment.MachineName;
                strName = strLogin;
            }
 
 
            DirectoryEntry obDirEntry = null;
            try
            {
                Int64 iBigVal = 5;
                Byte[] bigArr = BitConverter.GetBytes(iBigVal);
                obDirEntry = new DirectoryEntry("WinNT://" +
                                      strDomain + "/" + strName);
                System.DirectoryServices.PropertyCollection
                                   coll = obDirEntry.Properties;
                object obVal = coll["objectSid"].Value;
                if (null != obVal)
                {
                    str = this.ConvertByteToStringSid((Byte[])obVal);
                }
 
            }
            catch (Exception ex)
            {
                str = "";
                //Trace.Write(ex.Message);
            }
            return str;
        }
 
        private string ConvertByteToStringSid(Byte[] sidBytes)
        {
            StringBuilder strSid = new StringBuilder();
            strSid.Append("S-");
            try
            {
                // Add SID revision.
                strSid.Append(sidBytes[0].ToString());
                // Next six bytes are SID authority value.
                if (sidBytes[6] != 0 || sidBytes[5] != 0)
                {
                    string strAuth = String.Format
                        ("0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}",
                        (Int16)sidBytes[1],
                        (Int16)sidBytes[2],
                        (Int16)sidBytes[3],
                        (Int16)sidBytes[4],
                        (Int16)sidBytes[5],
                        (Int16)sidBytes[6]);
                    strSid.Append("-");
                    strSid.Append(strAuth);
                }
                else
                {
                    Int64 iVal = (Int32)(sidBytes[1]) +
                        (Int32)(sidBytes[2] << 8) +
                        (Int32)(sidBytes[3] << 16) +
                        (Int32)(sidBytes[4] << 24);
                    strSid.Append("-");
                    strSid.Append(iVal.ToString());
                }
 
                // Get sub authority count...
                int iSubCount = Convert.ToInt32(sidBytes[7]);
                int idxAuth = 0;
                for (int i = 0; i < iSubCount; i++)
                {
                    idxAuth = 8 + i * 4;
                    UInt32 iSubAuth = BitConverter.ToUInt32(sidBytes, idxAuth);
                    strSid.Append("-");
                    strSid.Append(iSubAuth.ToString());
                }
            }
            catch (Exception ex)
            {
                //Trace.Warn(ex.Message);
                return "";
            }
            return strSid.ToString();
        }
 
        private void writeData(string SID, string user)
        {
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection con = new SqlConnection("ConnectionString");
            string qry = "UPDATE TIUSER SET SID = '" + SID + "' WHERE (NTACCOUNT = '" + user + "')";
            da.UpdateCommand = new SqlCommand(qry, con);
 
            try
            {
                con.Open();
                da.UpdateCommand.ExecuteNonQuery();
 
            }
            catch{}
            con.Close();
        
        }

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

770 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