Hi my name is vishal for past 6 days i have been breaking my head on how to get id(user_id or manager_id) of currently logged in user in my application in c# windows forms with sql server 2008.
So i have a application named:Mini Project which has a login form named:frmLogin.Given below is my c# code of frmLogin:

namespace Mini_Project
{
    public partial class frmLogin : Form
    {
    public frmLogin()
        {
            InitializeComponent();
        }
        private void frmLogin_Load(object sender, EventArgs e)
        {

        }
        private bool ManagerUser(string username, string password)
        {
            bool success = false;
            SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select @count = Count(*) from [dbo].[ManagerDetail2] where username=@username and password=@password and LoginAttempts< 3", conn);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@manager_id", Module.MUser_ID);
            cmd.Parameters.Add("@count", SqlDbType.Int).Direction = ParameterDirection.Output;
            conn.Open();
            cmd.ExecuteNonQuery();
            if (Convert.ToInt32(cmd.Parameters["@count"].Value)>0)
            {

                success = true;
                cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                success = false;
                cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            conn.Close();
            return success;
        }
        private bool ValidateUser(string username, string password)
        {
            bool success = false;
            SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select @count = Count(*) from [dbo].[UserDetail2] where username=@username and password=@password and LoginAttempts< 3", conn);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@user_id", Module.User_ID);
            cmd.Parameters.Add("@count", SqlDbType.Int).Direction = ParameterDirection.Output;
            conn.Open();
            cmd.ExecuteNonQuery();
            if (Convert.ToInt32(cmd.Parameters["@count"].Value)>0)
            {

                success = true;
                cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                success = false;
                cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                cmd.ExecuteNonQuery();
            }
            conn.Close();
            return success;
        }
         private void btnLogin_Click(object sender, EventArgs e)
        {
            if ((txtPassword.Text == "password") && (txtUsername.Text.ToLower() == "admin"))
            {
                Module.AUser_ID=1;
                MDIParent1 h = new MDIParent1();
                h.Show();
                this.Close();
            }
            else
            {
                string username = txtUsername.Text;
                string password = txtPassword.Text;
                bool validUser = ValidateUser(username, password);
                bool validmanager = ManagerUser(username, password);
                    if (validUser)
                    {
                        Module.User_ID = 1;
                        MDIParent1 m = new MDIParent1();
                        m.Show();
                        this.Close();
                    }
                     if (validmanager)
                    {
                        Module.MUser_ID = 1;
                        MDIParent1 g = new MDIParent1();
                        g.Show();
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Invalid user name or password. Please try tomorow ", "Task", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUsername.Focus();
                    }
                }
            }
            private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

The above code works with no problem at all!

As you can see i login in to application(Mini Project) using default username:admin and default password:password

Using default username:admin and default password:password i can add new users(Normal users) and managers into my application(Mini Project).

Given below is my c# code of how i add normal users into my application. So i have form for adding normal user named:frmUser.Given below is my c# code of frmUser:

namespace Mini_Project
{
    public partial class frmUser : Form
    {
    public frmUser()
        {
            InitializeComponent();
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
        SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            int autoGenId = -1;
            cmd = new SqlCommand("Insert into [dbo].[UserDetail2](user_first_name,user_last_name,user_dob,user_sex,email,username,password,status,row_upd_date,created_by,LoginAttempts)" + "Values(@user_first_name,@user_last_name,@user_dob,@user_sex,@email,@username,@password,@status,GetDate(),@created_by,@LoginAttempts); Select @autoGenId=SCOPE_IDENTITY();", conn);
            cmd.Parameters.AddWithValue("@user_first_name", txtFName.Text);
            cmd.Parameters.AddWithValue("@user_last_name", txtLName.Text);
            cmd.Parameters.AddWithValue("@user_dob", dtDOB.Value);
            if (cboSex.SelectedIndex == 0)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Male");
            }
            else if (cboSex.SelectedIndex == 1)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Female");
            }
            else if (cboSex.SelectedIndex == 2)
            {
                cmd.Parameters.AddWithValue("@user_sex", "Transgender");
            }
            cmd.Parameters.AddWithValue("@email", txtEmailID.Text);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            cmd.Parameters.AddWithValue("@Created_by",Module.MUser_ID);
            cmd.Parameters.AddWithValue("@LoginAttempts", 0);
            cmd.Parameters.Add("@autoGenId", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            autoGenId = Convert.ToInt32(cmd.Parameters["@autoGenId"].Value);
            cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
            cmd.ExecuteNonQuery();
            ((MDIParent1)this.MdiParent).updateUserActivities(autoGenId, 1, txtFName.Text + "User detail was added successfully");
            MessageBox.Show("User Detail was added successfully", "Task", MessageBoxButtons.OK, MessageBoxIcon.Information);
            conn.Close();
            this.Close();
            }

The above code works OK as i dont get any compilation or run-time errors.

Given below is my structure of my table:UserDetail2 in sql server 2008:

ColumnName                             DataType                      AllowNulls
user_id(auto-increment primary key)      Int                             No
user_first_name                        nvarchar(50)                      Yes
user_last_name                         nvarchar(50)                      Yes
user_dob                                 date                            Yes
user_sex                               nvarchar(20)                      Yes
email                                  nvarchar(80)                      Yes
username                               nvarchar(25)                      Yes
password                               nvarchar(15)                      Yes
status                                    bit                            Yes
row_upd_date                            datetime                         Yes
created_by                                Int                            Yes
LoginAttempts                             Int                            Yes

Given below is my c# code of how i add managers into my application. So i have form for adding managers named:frmManager.Given below is my c# code of frmManager:

namespace Mini_Project
{
    public partial class frmManager : Form
    {
    public frmManager()
        {
            InitializeComponent();
        }
        private void btnCreate_Click(object sender, EventArgs e)
        {
        SqlConnection conn = new SqlConnection("Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=Task;Integrated Security=true");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
             int bGenId = -1;
            cmd = new SqlCommand("Insert into [dbo].[ManagerDetail2](manager_first_name,manager_last_name,manager_dob,manager_sex,email,username,password,status,created_by,LoginAttempts,row_upd_date)" + "Values(@manager_first_name,@manager_last_name,@manager_dob,@manager_sex,@email,@username,@password,@status,@created_by,@LoginAttempts,GetDate()); Select @autoGenId=SCOPE_IDENTITY();", conn);
            cmd.Parameters.AddWithValue("@manager_first_name", txtFName.Text);
            cmd.Parameters.AddWithValue("@manager_last_name", txtLName.Text);
            cmd.Parameters.AddWithValue("@manager_dob", dtDOB.Value);
            if (cboSex.SelectedIndex == 0)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Male");
            }
            else if (cboSex.SelectedIndex == 1)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Female");
            }
            else if (cboSex.SelectedIndex == 2)
            {
                cmd.Parameters.AddWithValue("@manager_sex", "Transgender");
            }
            cmd.Parameters.AddWithValue("@email", txtEmailID.Text);
            cmd.Parameters.AddWithValue("@username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@status", 1);
            cmd.Parameters.AddWithValue("@Created_by", 1);
            cmd.Parameters.AddWithValue("@LoginAttempts", 0);
            cmd.Parameters.Add("@autoGenId", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            bGenId = Convert.ToInt32(cmd.Parameters["@autoGenId"].Value);
            cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
         cmd.ExecuteNonQuery();
          ((MDIParent1)this.MdiParent).updateUserActivities(bGenId, 2, txtFName.Text.ToString() + "Manager detail was added successfully");
            MessageBox.Show("Manager Detail was added successfully", "Task", MessageBoxButtons.OK, MessageBoxIcon.Information);
            conn.Close();
            this.Close();
            }
            private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

The above code works OK as i dont get any compilation or run-time errors.

Given below is my structure of my table:ManagerDetail2 in sql server 2008:

ColumnName                               DataType                       AllowNulls
manager_id(auto-increment primary key)     Int                              No
manager_first_name                      nvarchar(50)                       Yes
manager_last_name                       nvarchar(50)                       Yes
manager_dob                                date                            Yes
manager_sex                             nvarchar(20)                       Yes
email                                   nvarchar(80)                       Yes
username                                nvarchar(25)                       Yes
password                                nvarchar(15)                       Yes
status                                     bit                             Yes
created_by                                 Int                             Yes
LoginAttempts                              Int                             Yes
row_upd_date                              datetime                         Yes

So i can log into application(Mini Project) using default username:admin and default password:password,or i can also log into my application(Mini Project) using username and password from my tables(either from UserDetail2 or ManagerDetail2).
What i want is how to get user_id or manager_id from currently logged in user/manager to a global variable in my application(Mini Project) through login form(frmLogin)? Can anyone help me please! Can anyone help me/guide me to get my required result!? Can anyone tell me what modifications must i need to do in my c# code and where? Any help/guidance in solving of this problem would be greatly appreciated!

Hello Vishal, there's lot's of ways of doing what you want, but the main change I think you have to do is in ValidateUser and ManagerUser. Those two methods should return the Id of the user/manager, then you can already store then.
So, use this select instead:

Select @UserId = IsNull(user_id, -1) from [dbo].[UserDetail2] where username=@username and password=@password and LoginAttempts< 3

Then, if ValidadeUser returns something greater then 0, the user exists, otherwise, it doesn't.

Exemple:

MyMiniSession.CurrentUserId = ValidateUser(user, pass);
MyMiniSession.CurrentManagerId = ValidateManager(user, pass);

if ( MyMiniSession.IsUser ) { ... }
else if ( MyMiniSession.IsManager ) {... }
else { ... }

MyMiniSession class

public class MyMiniSession
{
    public static int CurrentUserId = 0;
    public static int CurrentManagerId = 0;

    public static bool IsUser
    {
        get { return CurrentUserId > 0; }
    }
    public static bool IsManager
    {
        get { return CurrentManagerId > 0; }
    }
    public static bool IsAdmin
    {
        get { return !(IsUser || IsManager); }
    }
}

Hope it helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.