Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

How to get id or user id value of currently logged in user to a global variable in c# windows forms with sql server 2008

$
0
0

Hi my name is vishal for past 10 days i have been breaking my head on how to get/extract id(user id) of currently logged in user of application to a global variable in c# windows forms with sql server 2008?

So i have a application named:Mini Project which has a login form named:frmLogin,also has a mdi parent form named:MDIParent1.

Given below is my c# code of login form(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");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select manager_id,manager_first_name from [dbo].[ManagerDetail2] where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' and LoginAttempts< 3", conn);
            SqlDataReader rd = cmd.ExecuteReader();
           while(rd.Read())
            {
                success=true;
                Module.Instance.Manager = Convert.ToInt32(rd[0].ToString());
                Module.Instance.GlobalManager = rd[1].ToString();
            }
            rd.Close();
            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");
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd = new SqlCommand("Select * from [dbo].[UserDetail2] where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' and LoginAttempts< 3", conn);
            SqlDataReader rd = cmd.ExecuteReader();
           while(rd.Read())
            {
                success=true;
                Module.Instance.User = Convert.ToInt32(rd[0].ToString());
                Module.Instance.GlobalUser = rd[1].ToString();
            }
            rd.Close();
            conn.Close();
            return success;
        }
private void btnLogin_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;
            if ((txtPassword.Text == "password") && (txtUsername.Text.ToLower() == "admin"))
            {
                Module.Instance.Admin = 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)
                {
                    cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                    Module.Instance.User = 1;
                    MDIParent1 m = new MDIParent1();
                    m.Show();
                    this.Close();
                }
                     if (validmanager)
                    {
                        cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=0 where username='" + txtUsername.Text + "'", conn);
                        cmd.ExecuteNonQuery();
                        Module.Instance.Manager = 1;
                        MDIParent1 g = new MDIParent1();
                        g.Show();
                        this.Close();
                    }    
                    else
                    {
                        cmd = new SqlCommand("Update [dbo].[UserDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                    cmd = new SqlCommand("Update [dbo].[ManagerDetail2] set LoginAttempts=LoginAttempts+1 where username='" + txtUsername.Text + "'", conn);
                    cmd.ExecuteNonQuery();
                        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 OK to some extent!

I also have a class named:Module. Given below is my c# code of class(Module):

namespace Mini_Project
{
    public sealed class Module
    {
        private static readonly Module _instance = new Module();

        public static Module Instance
        {
            get { return _instance; }
        }
        public int Admin { get; set; }
        public int User { get; set; }
        public int Manager { get; set; }
        public string GlobalUser { get; set; }
        public string GlobalManager { get; set; }
        public string GlobalAdmin { get; set; }
    }
}


As you can see i use default username:admin and default password:password as i enter/login into application(Mini Project) as aadmin and create manager for tasks. Given below is my c# code of form named:frmManager through which i create amanager for tasks and insert values into table named:ManagerDetail2 in sql server 2008:

namespace Mini_Project
{
    public partial class frmManager : Form
    {
public int bGenId = -1;
        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;
            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();
        }

The above code works! with no problem at all! Given below is structure of my table named: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(60)                                 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 using username and password from table:ManagerDetail2,i enter/login into application(Mini Project) as amanager,(each manager has different manager_id as field:manager_id is auto-increment primary key of data type:Int in table:ManagerDetail2). As a manager i enter into application,creates/add new users to application,users who will come under that manager only who has created them.

Given below is c# code of form(frmUser) through which a manager creates/add a new user to application and also insert values into table named:UserDetail2 in sql server 2008:

namespace Mini_Project
{
    public partial class frmUser : Form
    {
public int autoGenId = -1;
        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;
            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.Instance.Manager);
            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 to some extent!

Given below is 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(60)                     Yes

username                                                      nvarchar(25)                     Yes

password                                                      nvarchar(15)                      Yes

status                                                                  bit                                Yes

created_by                                                          Int                                Yes

LoginAttempts                                                     Int                                Yes

row_upd_date                                                datetime                           Yes

Given below is my c# code of mdi parent form:MDIParent1:

namespace Mini_Project
{
    public partial class MDIParent1 : Form
    {
        private int childFormNumber = 0;
        public MDIParent1()
        {
            InitializeComponent();
            if (Module.Instance.Admin == 1)
            {
                addNewTaskToolStripMenuItem.Enabled = true;
                addUserToolStripMenuItem1.Enabled = true;
                addManagerToolStripMenuItem.Enabled = true;
                addTaskToolStripMenuItem.Enabled = true;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = false;
                tasksToolStripMenuItem.Enabled = true;
                optionsToolStripMenuItem.Enabled = true;
                pendingTaksToolStripMenuItem.Enabled = true;
                completedTasksToolStripMenuItem.Enabled = true;
            }
if (Module.Instance.Manager==1)
            {
                addUserToolStripMenuItem1.Enabled = false;
                addManagerToolStripMenuItem.Enabled = true;
                addNewTaskToolStripMenuItem.Enabled = false;
                addTaskToolStripMenuItem.Enabled = true;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = false;
                tasksToolStripMenuItem.Enabled = true;
                optionsToolStripMenuItem.Enabled = true;
                pendingTaksToolStripMenuItem.Enabled = true;
                completedTasksToolStripMenuItem.Enabled = true;
            }
            if (Module.Instance.User == 1)
            {
                addManagerToolStripMenuItem.Enabled = false;
                addUserToolStripMenuItem1.Enabled = false;
                addNewTaskToolStripMenuItem.Enabled = false;
                addTaskToolStripMenuItem.Enabled = false;
                exitToolStripMenuItem.Enabled = true;
                checkInUserToolStripMenuItem.Enabled = true;
                tasksToolStripMenuItem.Enabled = false;
                optionsToolStripMenuItem.Enabled = false;
                pendingTaksToolStripMenuItem.Enabled = false;
                completedTasksToolStripMenuItem.Enabled = false;
            }
        }
public SqlConnectionStringBuilder connBuilder;
        public SqlConnection conn;
        private void MDIParent1_Load(object sender, EventArgs e)
        {
            connBuilder = new SqlConnectionStringBuilder();
            connBuilder.InitialCatalog = "DRRS";
            connBuilder.DataSource = "NPD-4\\SQLEXPRESS";
            connBuilder.IntegratedSecurity = true;
            connBuilder.AsynchronousProcessing = true;
            conn = new SqlConnection(connBuilder.ToString());
            conn.Open();  
        }

The above c# code works Fine!

So what i want is when a manager(using username andpassword from table:ManagerDetail2),also having different/uniquemanager_id enters/login into application through login form(frmLogin),creates/add new user to application through form(frmUser) and insert values into table:UserDetail2, i want value of currently logged in manager(manager_id ) to be passed as value to field:created_by in table:UserDetail2 through c# code. That is want i want.

So my question is how to get value/id(manager_id) of currently logged inmanager of application to a global variable/pass value/id(manager_id) of currently logged in manager to field:created_by of table:UserDetail2 upon creation of new user by that particular manager?

Can anyone help me Please! Can anyone tell me/guide me what modifications must i need to do in my c# code and where to achieve my required result? Can anyone help me Please! Any help/guidance in solving of this problem would be greatly appreciated!


vishal


Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>