Mohammed Al-Ali
Mohammed Al-Ali

Reputation: 75

How to fix this error in inserting method to insert the user who is not in the database to it?

I am using an ASP.NET wizard control for editing the role of the user after showing its information. The wizard consists of three steps:

Hello everybody,

Since I am developing an intranet web application for the company, the Admin doesn't need to know if the user is on the database or not. So I want the system automatically to check in the background if the user is on the database or not. If he is in the database, the role will be edited for him immediately. If he is not in the database, his information will be added to the system with giving him a role.

protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
        //If one of the items is selected AND a username exists in the Username session object update the user role
        string username = TextBox1.Text;

        if (!String.IsNullOrEmpty(radio1.SelectedValue) && !String.IsNullOrEmpty(username))
        {
            string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";

            string insertUserCommand = "INSERT INTO employee (Name, Username, JobTitle, BadgeNo, EmpOrgType, DivisionCode) values (@Name, @Username, @JobTitle, @BadgeNo, @EmpOrgType, @DivisionCode)";
            string cmdText = "SELECT Count(*) FROM employee WHERE Username = '" + username + "'";

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                // Open DB connection.
                using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                {
                    if ((int)cmd.ExecuteScalar() == 0){
                        //An object from ObjectUser class to get the user information from the secure system and insert them to the database
                        ObjectUser user = new ObjectUser(username,true);

                        SqlCommand cmd2 = new SqlCommand(insertUserCommand, conn);
                        cmd2.Parameters.AddWithValue("@Name", user.Name);
                        cmd2.Parameters.AddWithValue("@Username", username);
                        cmd2.Parameters.AddWithValue("@JobTitle", user.GetProperty("EMP_TITLE"));
                        cmd2.Parameters.AddWithValue("@BadgeNo", user.GetProperty("EMP_BADGE_NUMBER"));
                        cmd2.Parameters.AddWithValue("@EmpOrgType", user.GetProperty("EMP_EMPTYPE"));
                        cmd2.Parameters.AddWithValue("@DivisionCode", user.Org.Division.SapCode);
                    }

                }
            }

            string deleteCommand = "DELETE FROM UserRole where Username=@Username";
            string insertCommand = "INSERT INTO UserRole (RoleID,Username) values(@RoleID,@Username)";
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                //using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                using (SqlCommand cmd = new SqlCommand(deleteCommand, conn))
                {
                    cmd.Parameters.AddWithValue("@Username", username);
                    cmd.ExecuteNonQuery();
                    //Now the insert
                    cmd.CommandText = insertCommand;
                    cmd.Parameters.Clear(); //need this because still has params from del comm
                    cmd.Parameters.AddWithValue("@RoleID", radio1.SelectedValue);
                    cmd.Parameters.AddWithValue("@Username", username);
                    cmd.ExecuteNonQuery();
                    //infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
                    //cmd.ExecuteScalar();
                    //infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
                }
            }

            Wizard1.Visible = false;
            wizard.InnerHtml = @"The task has been done successfully. <br /> <a href='UserManagement.aspx'>Edit Another User</a>";
        }


    }

Now for the user who is not in the database, when I chose a role for him and click Finish button, it should be added to the database but in my case I got an error in the bottom of the browser which says (Error on page), when I clicked on it, I got the following details:

Sys.WebForms.PageRequestMangerServerErrorException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserRole_employee". The confilct occurred in database "psspdb" table "dbo.employee", column 'Username'. The statement has been terminated.

I don't how to fix it. Any help please?

FYI, the design of the database is like this:

employee table:

Username, Name, JobTitle...

UserRole table:

UserRoleID, Useranme, RoleID

Roles table:

RoleID, RoleName

The first attribute is the primary key for each table.

BTW, As you see in my question above, I am using something called insertUserCommand. This command should be enough to add the user information to the database. So I should not have this conflict. Sorry for asking a lot but I am beginner in this area. Could you please tell me what I should do with code?

Upvotes: 1

Views: 210

Answers (2)

shubhangi Motling
shubhangi Motling

Reputation: 292

You are not executing insertUserCommand.After adding parameter that means after
cmd2.Parameters.AddWithValue("@DivisionCode", user.Org.Division.SapCode);
write cmd2.ExecuteNonQuery().
As you are not executing it this entry will not add to table

Upvotes: 1

shubhangi Motling
shubhangi Motling

Reputation: 292

Error because of you are adding username in Userrole table which is not present in employee table.Make sure before you add username in Userrole table that record must be in employee table,otherwise foreignkey constraint will violet.

Upvotes: 1

Related Questions