0

I have some code which collect all users from Active Directory and INSERTs them into my database. After I have inserted all users which don't already exist in my database I want to count how many new users I added to the database.

So far want I create is this which is function to Execute store procedure

 public void ExcStrPrc(string Username, string DisplayName, bool isEnable, bool PassNevExp)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("ADProcTemp", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", Username.ToString().Trim());
            cmd.Parameters.AddWithValue("@DisplayName", DisplayName.ToString().Trim());
            cmd.Parameters.AddWithValue("@isEnabled", Convert.ToInt32(isEnable));
            cmd.Parameters.AddWithValue("@PassNevExp", Convert.ToInt32(PassNevExp));
            conn.Open();
            int k = cmd.ExecuteNonQuery();
            if (k != 0)
            {
                Console.WriteLine("Record Inserted Succesfully into the Database");

            }           
            conn.Close();
        }

And here is my main program

        public static List<Korisnik> VratiKorisnike()
        {
            List<Korisnik> lstADUsers = new List<Korisnik>();
            string sDomainName = "saostest";
            string DomainPath = "LDAP://" + sDomainName;
            string fileLoc = @"C:\output.txt";

            DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
            DirectorySearcher search = new DirectorySearcher(searchRoot);

            search.Filter = "(&(objectClass=user)(objectCategory=person))";
            search.PropertiesToLoad.Add("samaccountname"); // Username
            search.PropertiesToLoad.Add("displayname"); // display name
            search.PropertiesToLoad.Add("userAccountControl");  // isEnabled
            search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires


            DataTable resultsTable = new DataTable();
            resultsTable.Columns.Add("samaccountname");
            resultsTable.Columns.Add("displayname");
            resultsTable.Columns.Add("Neaktivan");
            resultsTable.Columns.Add("dontexpirepassword");

            SearchResult result;
            SearchResultCollection resultCol = search.FindAll();


            if (resultCol != null)
            {
                for (int counter = 0; counter < resultCol.Count; counter++)
                {
                    string UserNameEmailString = string.Empty;

                    result = resultCol[counter];

                    if (result.Properties.Contains("samaccountname")
                        && result.Properties.Contains("displayname"))
                    {
                        int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
                        string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);

                        int isEnable;
                        int Dont_Expire_Password;


                        if ((userAccountControl & 2) > 0)
                        {
                            isEnable = 0;
                        }
                        else
                        {
                            isEnable = 1;
                        }



                        if ((userAccountControl & 65536) > 0)
                        {
                            Dont_Expire_Password = 1;
                        }
                        else
                        {
                            Dont_Expire_Password = 0;
                        }


                        Korisnik korisnik = new Korisnik();
                        korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
                        korisnik.DisplayName = result.Properties["displayname"][0].ToString();
                        korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);


                        DataRow dr = resultsTable.NewRow();
                        dr["samaccountname"] = korisnik.Username.ToString();
                        dr["displayname"] = korisnik.DisplayName.ToString();
                        dr["neaktivan"] = Math.Abs(isEnable);
                        dr["dontexpirepassword"] = Dont_Expire_Password;    

                        resultsTable.Rows.Add(dr);

                        // Poziva se store procedura
                        Program p = new Program();
                        p.ExcStrPrc(korisnik.Username.ToString().Trim(), korisnik.DisplayName.ToString().Trim(), Convert.ToBoolean(isEnable), Convert.ToBoolean(Dont_Expire_Password));

                        //Ukupan broj dodanih novih usera 
                        string connectionString = @"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
                        System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
                        sqlConnection.Open();
                        System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
                        sqlCommand.Connection = sqlConnection;

                        int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
                        Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);

                        lstADUsers.Add(korisnik);    
                    }
                }
                var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
                var res = json;

                Console.WriteLine("Ispis uspjesno obavljen");
                Console.ReadLine();
                File.WriteAllText(fileLoc, json);    
            }
            return lstADUsers;
        }
    }
}

Right here I add these logic

string connectionString = @"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = DesignSaoOsig1; Integrated Security = True";
                    System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
                    sqlConnection.Open();
                    System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM [dbo].[tblZaposleni_AD]");
                    sqlCommand.Connection = sqlConnection;

                    int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
                    Console.WriteLine("Ukupan broj dodanih novi usera:", sqlCommand);

But here is problem which I didn't get any result (number)? Anyone how can help me to solve this problem?

Stored Procedure

CREATE PROCEDURE ADProcTemp
@Username varchar(250),
@DisplayName varchar(70),
@isEnabled tinyint,
@PassNevExp tinyint
AS
set nocount on
BEGIN
    IF NOT EXISTS (SELECT TOP 1 PrezimeIme FROM [dbo].[tblZaposleni_AD] with (NOLOCK) WHERE NetworkLogin = @Username)                   
BEGIN
    IF(@isEnabled = 1)
   INSERT INTO [dbo].[tblZaposleni_AD](NetworkLogin,PrezimeIme,Status,PassNevExp)
   VALUES (@Username, @DisplayName, @isEnabled,@PassNevExp)
END
ELSE    
BEGIN
  UPDATE [dbo].[tblZaposleni_AD]  
  SET Status = @isEnabled
  WHERE NetworkLogin = @Username AND Status <> @isEnabled

END
END
Dale K
  • 25,246
  • 15
  • 42
  • 71
  • Can you show us please your stored procedure as well? – Peter Csala Apr 29 '20 at 06:51
  • Sure. Sorry, I forget it to add –  Apr 29 '20 at 06:52
  • @PeterCsala I added –  Apr 29 '20 at 06:53
  • With `SET NOCOUNT ON` you basically turns off that feature that returns the affected rows. You have to explicitly return the affected rows count from your Stored Procedure. You can either rely on the @@ROWCOUNT (https://stackoverflow.com/questions/1103260/return-number-of-rows-affected-by-update-statements) or rely on the OUTPUT INSERTED (https://stackoverflow.com/questions/4619343/sql-server-list-of-insert-identities) – Peter Csala Apr 29 '20 at 07:02
  • Is there any another way ? –  Apr 29 '20 at 07:09
  • In your stored procedure you have everything you need to answer to that question: How many new user has been inserted?. If you want to do this outside of the database then you will be in trouble. Let's suppose you do the following: query the users, upsert users, query the users again and finally compare the before and after user base. Most probably you are not the only one who is writing into the database. So anyone can insert / delete or update a user between the first and second queries. – Peter Csala Apr 29 '20 at 07:35

1 Answers1

0

First in your stored procedure you need to remove SET NOCOUNT ON in order to allow the sp to return the number of row affected.

Then in your c# code instead of

int RecordCount = Convert.ToInt32(sqlCommand.ExecuteScalar());

You need to call this

int RecordCount = Convert.ToInt32(sqlCommand.ExecuteNonQuery());

From the MSDN doc :

ExecuteScalar

Returns

Object

The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.

ExecuteNonQuery

Returns

Int32

The number of rows affected.

Alex Leo
  • 2,781
  • 2
  • 13
  • 29