locked
on Click Button event not firing repository RRS feed

  • Question

  • User-1901014284 posted

    Hi,

    I am tying to set permissions within a Panel using check boxes.

    HTML code:

    <h3>Permissions</h3>
                <asp:panel runat="server" id="rolesContainer">
                </asp:panel>

    Here is the code I am using to populate the "rolesContainer" panel. When running and breaking down the code the fields are populated correctly and check boxes are visible to check and uncheck as required.

    C# Code:

     roles = RoleRepository.GetAll();
    
                string sql;
                SqlCommand cmd;
    
                foreach ( var role in roles)
                {
                    Label myLabel = new Label();
                    
                    myLabel.Text = role.description.ToString();
                    myLabel.ID = "Label" + role.ID.ToString();
    
                    CheckBox chkbx = new CheckBox();
                    chkbx.ID = "CheckBox_Role_" + role.ID.ToString();
                    chkbx.Text = "";
                    
                    rolesContainer.Controls.Add(chkbx); 
                    rolesContainer.Controls.Add(myLabel);
                    rolesContainer.Controls.Add(new LiteralControl("<br />"));
                }
    

    The on button click event fires the below code to insert details into my DB 

    protected void Submit_OnClick(object sender, EventArgs e)
    {
    int user = 0;
    long userId = 0;
    
    string constr = ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
    roles = RoleRepository.GetAll();
    
    using (SqlCommand cmd = new SqlCommand("SP"))
    {
    using (SqlDataAdapter sda = new SqlDataAdapter())
    {
    string hashed = BCrypt.HashPassword(Passwordtxt.Text.Trim(), BCrypt.GenerateSalt(12));
    
    cmd.CommandType = CommandType.StoredProcedure;
    
    cmd.Parameters.AddWithValue("@1", 1textbox.Text.Trim());
    
    cmd.Connection = con;
    
    con.Open();
    user = Convert.ToInt32(cmd.ExecuteScalar());
    con.Close();
    
    
    string message = string.Empty;
    switch (user)
    {
    case -1:
    message = "Username already exists.\\nPlease choose a different username.";
    break;
    case -2:
    message = "Supplied email address has already been used.";
    break;
    default:
    message = "Registration successful. Activation email has been sent.";
    SendActivationEmail(user); <--Sends email-->
    break;
    }
    
    if (userId > 0)
    {
    foreach (var role in roles)
    {
    if (Request.Form["ctl00$Main$CheckBox_Role_" + role.ID.ToString()] == "on")
    {
    PortalUserRoleRepository.AddUserRole((int)userId, role.ID);
    }
    }
    }
    
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    
    FillPortalUserGridView();
    }
    }
    }
    }

    The below section does not trigger on the click event, the userId field is populated but the repository does not open.

    if (userId > 0)
    {
    foreach (var role in roles)
    {
    if (Request.Form["ctl00$Main$CheckBox_Role_" + role.ID.ToString()] == "on")
    {
    PortalUserRoleRepository.AddUserRole((int)userId, role.ID);
    }
    }
    }

    This is my UserRepository .cs file:

    using Dapper;
    using Dapper.Contrib.Extensions;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    
    namespace Portal.Models
    { 
            [Table("UserRoles")]
            public class UserRole
            {
                [Key]
                public int userId { get; set; }
                public long roleID { get; set; }
                public string name { get; set; }
            }
    
            public static class PortalUserRoleRepository
            {
                private static SqlConnection _db = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString);
    
                public static List<UserRole> GetAll()
                {
                    return _db.Query<UserRole>("SELECT * FROM UserRoles").ToList();
                }
    
                public static List<UserRole> GetByUser(int userId)
                {
                    string sql = @"
            		SELECT 
            			* 
            		FROM 
            			UserRoles AS ur
            		LEFT JOIN
            			Roles AS r on (r.ID = ur.roleId)
            		WHERE 
            			userId = @userId
            	";
                    return _db.Query<UserRole>(sql, new { userId }).ToList();
                }
    
                public static UserRole GetOne(int id)
                {
                    return _db.Query<UserRole>("SELECT * FROM UserRoles WHERE ID = @ID", new { id }).SingleOrDefault();
                }
    
    
                public static long Insert(UserRole userRole)
                {
                    return _db.Insert(userRole);
                }
    
                public static long AddUserRole(int userId, int roleID)
                {
                    //return _db.Query("INSERT INTO UserRoles (userId, roleId) VALUES (@userID, @roleID)", new {userID, roleID});
    
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO UserRoles (userId, roleId) VALUES (@userID, @roleID)", _db))
                    {
                        cmd.Parameters.AddWithValue("@userID", userId);
                        cmd.Parameters.AddWithValue("@roleID", roleID);
                        _db.Open();
    
                        cmd.ExecuteScalar();
    
                        if (_db.State == System.Data.ConnectionState.Open)
                            _db.Close();
    
                        return 1;
                    }
                }
    
                public static bool deleteRolesByUser(int userId)
                {
                    var affectedrows = _db.Execute("DELETE FROM UserRoles WHERE userId = @userId", new { userId = userId });
    
                    return affectedrows > 0;
                }
            }
        }
    

    I cannot see why the PortalUserRoleRepository.AddUserRole will not trigger on the button click even after breaking down my code so I am not sure if I have structured my code incorrectly?

    any help would be greatly appreciated.

    Kind regards

    Jonny

    Monday, June 10, 2019 3:10 PM

All replies

  • User475983607 posted

    The code initializes UserId to 0 and UserId remains unchanged up to the condition statement. 

    protected void Submit_OnClick(object sender, EventArgs e)
    {
    int user = 0;
    long userId = 0;

    Monday, June 10, 2019 3:22 PM
  • User-1901014284 posted

    Thanks mgebhard,

    I have updated the code to now be te below

    long userId;

    but I still have the same issue, the issue seems to be with the role.ID as this is not populating once a checkbox is checked.

    Many thanks

    Jonny

    Wednesday, June 12, 2019 1:42 PM
  • User475983607 posted

    jonnygareth30

    Thanks mgebhard,

    I have updated the code to now be te below

    long userId;

    but I still have the same issue, the issue seems to be with the role.ID as this is not populating once a checkbox is checked.

    Many thanks

    Jonny

    That does not change anything.  The default value of long is zero.

    The original code never sets UserId to a different value.  The condition is never entered.

    if (userId > 0)
    {
    	foreach (var role in roles)
    	{
    		if (Request.Form["ctl00$Main$CheckBox_Role_" + role.ID.ToString()] == "on")
    		{
    			PortalUserRoleRepository.AddUserRole((int)userId, role.ID);
    		}
    	}
    }

    I recommend setting a break point and stepping through the code.  It should be obvious that UserId is 0 throughout the code snippet.

    Wednesday, June 12, 2019 2:04 PM
  • User-1901014284 posted

    Hi mgebhard,

    Thank you for your response again, I have run the system using Break Points, the below code is skipped when a break point was placed but the userId was populated with the userId that had been set.

    foreach (var role in roles)
                    {
                        if (Request.Form["ctl00$Main$CheckBox_Role_" + role.ID.ToString()] == "on")
                        {
                            PortalUserRoleRepository.AddUserRole((int)userId, role.ID);
                    

    I have also checked my UserRole class by breaking down the code and again the roleID is not populating but the userId has populated with the assigned ID.

    public static long AddUserRole(int userId, int roleID)
                {
                    //return _db.Query("INSERT INTO PortalUserRoles (userId, roleId) VALUES (@userID, @roleID)", new {userID, roleID});
    
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO PortalUserRoles (userId, roleId) VALUES (@userID, @roleID)", _db))
                    {
                        cmd.Parameters.AddWithValue("@userID", userId);
                        cmd.Parameters.AddWithValue("@roleID", roleID);
                        _db.Open();
    
                        cmd.ExecuteScalar();
    
                        if (_db.State == System.Data.ConnectionState.Open)
                            _db.Close();
    
                        return 1;
                    }
                }

    Wednesday, June 12, 2019 2:52 PM
  • User475983607 posted

    I simply do not know how to explain this any clearer.  The code never sets UserId!  Maybe you really want user?

    user = Convert.ToInt32(cmd.ExecuteScalar());
    if (user > 0)
    {
    	foreach (var role in roles)
    	{
    		if (Request.Form["ctl00$Main$CheckBox_Role_" + role.ID.ToString()] == "on")
    		{
    			PortalUserRoleRepository.AddUserRole(user, role.ID);
    		}
    	}
    }

    Wednesday, June 12, 2019 3:01 PM
  • User-1901014284 posted

    Hi mgebhard,

    Thank you for the response and my apologies, I had tried breaking down my code but done this incorrectly leading me to believe the userId had populated! It is the userId I would like to populate but I am unsure how to do this as the record has not yet been created in the database. The idea is to add permissions to the user in a separate table which only contains userId and roleId which should be triggered using the AddUserRole within the repository.

    Again my apologies for the delay and if this is a straight forward process.

    Many thanks in advance 

    Jonny

    Thursday, June 20, 2019 2:56 PM
  • User475983607 posted

    Hi mgebhard,

    Thank you for the response and my apologies, I had tried breaking down my code but done this incorrectly leading me to believe the userId had populated! It is the userId I would like to populate but I am unsure how to do this as the record has not yet been created in the database. The idea is to add permissions to the user in a separate table which only contains userId and roleId which should be triggered using the AddUserRole within the repository.

    Again my apologies for the delay and if this is a straight forward process.

    Many thanks in advance 

    Jonny

    The code has several issues which makes it difficult to figure the intent.  For example, there is a "using SqlDataAdapter" that is never used.  There is a "user" variable that gets the results of a stored procedure named "SP".  It's not clear that that procedure does.

    Please set a break point and single step through your code.

    Thursday, June 20, 2019 3:26 PM