My problem is not my stored procedure but the fact that somewhere in my code it wont allow me to change the role in the database. Although i know it is written correctly could someone please have a good look at my code as iam really frustrated atm.
Thankyou in advanced..
DAO -
public void EditRole(Account account, RoleEnum role)
{
using (SqlConnection connection = ConnectionDao.GetConnection())
{
SqlCommand cmd = new SqlCommand("sp_Accounts_EditRoleByUsername", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#role", role);
cmd.Parameters.Add(new SqlParameter("#username", account.Username));
cmd.ExecuteNonQuery();
}
Manager -
public static ResultEnum RoleChange(Account account, RoleEnum role)
{
ResultEnum result = ResultEnum.Success;
try
{
AccountDao dao = new AccountDao();
dao.EditRole(account, role);
}
catch (Exception)
{
result = ResultEnum.Error;
}
return result;
}
The page -
public partial class ManageRolesPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Result<List<Account>> result = AccountManager.GetAll();
if (result.ResultEnum == ResultEnum.Success)
{
ddlUser.DataSource = result.Data;
ddlUser.DataTextField = "Username";
ddlUser.DataValueField = "AccountId";
ddlUser.DataBind();
}
else
{
lblInfo.Text = "database error";
}
}
}
protected void btnPermission_Click(object sender, EventArgs e)
{
Account account = new Account
{
Username = ddlUser.SelectedValue
};
RoleEnum role;
if (rdlRole.SelectedValue == "Admin")
{
role = RoleEnum.Admin;
}
else
{
role = RoleEnum.User;
}
ResultEnum result = AccountManager.RoleChange(account, role);
switch (result)
{
case ResultEnum.Success:
lblInfo.Text = "User: " + ddlUser.SelectedItem + " Has been edited to " + role;
break;
case ResultEnum.Error:
lblInfo.Text = "Error";
break;
}
}
The problem is you are using selected value of dropdown as username
Account account = new Account
{
Username = ddlUser.SelectedValue
};
where as when you are binding it with datasource, The value field is AccountId
ddlUser.DataValueField = "AccountId";
So in your function AccountId is actually passing as UserName of that user. So that makes your query with unusual result.
Related
I got stuck after couple of hours of research. I'm trying to make a basic Universal Windows App with login form - after clicking a button, credentials in textboxes are checked with remote MySQL database. If valid, app shoud navigate to another specified page. If not, error message is displayed.
I can't find error in my code below. After clicking the button Windows' blue circle spins and after couple of seconds returns to VS2017. No errors and warnings. State.ToString() returns 'Open' so I do have a connection with DB. What I'm doing wrong?
public sealed partial class MainPage : Page
{
const string connString = "server=my_server;pwd=pass;uid=user_id;database=mydb;persistsecurityinfo=True";
MySqlConnection conn = new MySqlConnection(connString);
public MainPage()
{
this.InitializeComponent();
}
private void DbConnection()
{
try
{
conn.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool DataValidation(string user, string pass)
{
DbConnection();
MySqlCommand cmd = new MySqlCommand("SELECT Username, Password FROM Users WHERE Username=#user AND Password=#pass;");
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassTextBox.Text;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("No emty fields allowed. Try again...");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Invalid e-mail or password. Try again...";
}
}
}
Complete working solution:
using MySql.Data.MySqlClient;
namespace Project
{
public sealed partial class MainPage : Page
{
const string connString = "server=server_name;user id=uid;pwd=password;persistsecurityinfo=True;database=db_name";
public MainPage()
{
this.InitializeComponent();
}
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connString))
using (MySqlCommand cmd = new MySqlCommand("SELECT " +
"Username, Password " +
"FROM users " +
"WHERE Username=#user AND Password=#pass;", conn))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
cmd.Connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassBox.Password;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("Your text");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Your text";
}
}
}
}
I was able to redirect the user to the default url(Default.aspx) page after every successful login. Now i want to make sure that the staff who is not an administrator to try to access login(Unauthorized.aspx) into default page. I'm using two asp.net page(Default.apsx and Unauthorized.aspx). But the problem is when i use mary tan who is administrator redirect to another page(Unauthorized.apsx) instead going to default url page. Here is my error:
Staff and Admin:
click image
Output:
view output
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" slidingExpiration="true" timeout="20"></forms>
</authentication>
Login.aspx.cs coding:
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
string staffName = null;
string staffId = null;
string role = null;
protected void Page_Load(object sender, EventArgs e)
{
}
public bool CheckValidUser(string Username, string Password)
{
bool valid = false;
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
string sql = "SELECT * from Staff WHERE Username=#Username AND Password=#Pwd And Role=N'A' OR Role=N'S'";
try
{
conn = new SqlConnection(connectionString);
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Pwd", Password);
conn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
staffName = dr["StaffName"].ToString();
staffId = dr["StaffId"].ToString();
role = dr["Role"].ToString();
valid = true;
}
else
{
lblOutput.Text = "There is an error logging in. Please check username or password.";
}
dr.Close();
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
return valid;
}
protected void tbLogin_Click(object sender, EventArgs e)
{
bool validUser = CheckValidUser(tbUsername.Text, tbPassword.Text);
if (validUser)
{
Session["StaffName"] = staffName;
FormsAuthentication.SetAuthCookie(staffName, false);
FormsAuthentication.RedirectFromLoginPage(staffName, false);
Session["StaffId"] = staffId;
FormsAuthentication.SetAuthCookie(staffId, false);
FormsAuthentication.RedirectFromLoginPage(staffId, false);
Session["Role"] = role;
FormsAuthentication.SetAuthCookie(role, true);
Response.Redirect("~/Unauthorized.aspx");
}
else
{
lblOutput.Text = "Invalid User. Please try again.";
}
}
}
The problem is during your login code, you are always redirecting valid users to the Unauthorized page
Response.Redirect("~/Unauthorized.aspx");
I'd just throw in a if statement here to redirect to the correct page if the user is in a certain role (and make sure that page is locked down using the ASP.NET Identity Roles system)
I have a login as my first screen when you open the applications. I have 10 more pages after you logged in. All I want is the name of that person who logged-in in all pages across like, (Welcome, User!). I have no idea on how to do this
here is my code:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
txtUsername.IsEnabled = true;
txtPassword.IsEnabled = true;
txtMessage.Text = "";
txtMessage.IsEnabled = false;
try
{
SqlConnection oConnection = new SqlConnection(_ConnectionString);
SqlCommand oCommand = new SqlCommand("Select * from register where Username = '" + txtUsername.Text + "' AND Password = '" + txtPassword.Password + "'", oConnection);
if (oConnection.State == ConnectionState.Closed)
oConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlDataReader reader = oCommand.ExecuteReader();
string Username = null;
if (reader.HasRows)
{
username = txtUsername.Text;
oConnection.Close();
NavigationService _Nav = NavigationService.GetNavigationService(this);
_Nav.Navigate(new Uri("Menuxaml.xaml", UriKind.RelativeOrAbsolute));
}
else if (txtUsername.Text.Trim().Length == 0)
Errormessage.Text = "Please enter your Username";
else if (txtPassword.Password.Trim().Length == 0)
Errormessage.Text = "Please enter your Password";
else
{
Errormessage.Text = "Invalid Username or Password!";
txtPassword.Password = "";
txtUsername.Text = "";
}
oConnection.Close();
}
}
If you need the username in all the 10 pages, I would suggest you to add this in Application resources and access this from all over the application.
Let me show you how to do this.
Application.Current.Resources.Add("UserName",txtUsername.Text);
and then on your second page use this resource to set your label.
lbl.Content = Application.Current.Resources["UserName"];
You can pass the value to the second page either by the constructor or public method exposed by the second page.
Here's the detail:
Page1:
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Page2 p = new Page2(2);
this.NavigationService.Navigate(p);
}
}
Page2:
public partial class Page2 : Page
{
int valueFromPage1;
public Page2()
{
InitializeComponent();
}
public Page2(int val):this()
{
valueFromPage1 = val;
this.Loaded += new RoutedEventHandler(Page2_Loaded);
}
void Page2_Loaded(object sender, RoutedEventArgs e)
{
lbl.Content = "Value passed from page1 is: " + valueFromPage1;
}
}
Let me know if you have any further problem.
If you want to use the same structure then
page.NavigationService.Navigate(new Uri("/Views/Page.xaml?parameter=test", UriKind.Relative));
Destination page:
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("parameter", out parameter))
{
this.label.Text = parameter;
}
hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx
Im trying to create a login form for a website using ms access database. I'm using visual studio 2010 c# and access 2013. For some reason I can't get it to log in. I'm really new to this so any help is appreciated.
DataLayer:
public class DataConnector
{
protected OleDbDataAdapter DataAdapter1 = new OleDbDataAdapter();
public string ErrorMessage = "";
public DataConnector(string ConnectionString)
{
OleDbConnection Connection1 = new OleDbConnection(ConnectionString);
this.DataAdapter1.SelectCommand = new OleDbCommand("", Connection1);
this.DataAdapter1.InsertCommand = new OleDbCommand("", Connection1);
}
public DataTable DataSelect(string query)
{
DataTable dt = new DataTable();
try
{
DataAdapter1.SelectCommand.CommandText = query;
DataAdapter1.SelectCommand.Connection.Open();
DataAdapter1.Fill(dt);
DataAdapter1.SelectCommand.Connection.Close();
ErrorMessage = "";
}
catch(Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.SelectCommand.Connection.Close();
}
return dt;
}
public int DataInsert(string query)
{
int Result = 0;
try
{
DataAdapter1.InsertCommand.CommandText = query;
DataAdapter1.InsertCommand.Connection.Open();
Result = DataAdapter1.InsertCommand.ExecuteNonQuery();
DataAdapter1.InsertCommand.Connection.Close();
ErrorMessage = "";
return Result;
}
catch (Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.InsertCommand.Connection.Close();
return 0;
}
}
public int DataUpdate(string query)
{
return DataInsert(query);
}
public int DataDelete(string query)
{
return DataInsert(query);
}
}
Default.aspx.cs:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
DataLayer.DataConnector dat = new DataLayer.DataConnector("Provider=Microsoft.ACE.OLEDB.12.O;"+"Data Source='"+Server.MapPath("site_database.accdb")+"'; Persist Security Info=False;");
DataTable dt = dat.DataSelect("select UserID from tbl_login where Username = '" + txtUsername.Text + "' and Password = '"+ txtPassword.Text +"' ");
if (dt.Rows.Count > 0)
{
Response.Redirect("members_area.aspx");
}
else
lblerror.Text = "Login failed";
}
}
I'm not getting any errors and I just can't figure it out. When I try to log in it just stays on the default.aspx page.
Part of the problem could very well be that PASSWORD is a reserved word in Access SQL, so if you want to use it as a field name in a query you should surround it in square brackets, e.g.
... WHERE Username = ... AND [Password] = ...
Note also that you really should be using a parameterized query in case Little Bobby Tables tries to log in.