Can't log into website - c#

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.

Related

Visual Studio Two Tiers Database (DAL)

Login.aspx
protected void btnLogin_Click(object sender, EventArgs e)
{
String tbNRIC = txtLogUsername.Text.ToString();
String tbPassword = txtLogPassword.Text.ToString();
PatientDAO fmTd = new PatientDAO();
fmTd.getPatientByNricPassword(tbNRIC, tbPassword);
if(?? > 0)
{
Response.Redirect("Home.aspx");
}
else
{
}
}
How to i response.redirect after checking if username and password match?
PatientDAO.cs
public int getPatientByNricPassword(String tbNRIC, String tbPassword)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
Patient mypatient = new Patient();
StringBuilder sqlStr = new StringBuilder();
int result = 0;
sqlStr.AppendLine("Select * from Login where");
sqlStr.AppendLine("tbNRIC = #paratbNRIC AND tbPassword = #paratbPassword");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
da = new SqlDataAdapter(sqlStr.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("#paratbNRIC", tbNRIC);
da.SelectCommand.Parameters.AddWithValue("#paratbPassword", tbPassword);
DataTable dt = new DataTable();
da.Fill(dt);
}
catch (SqlException ex)
{
logManager log = new logManager();
log.addLog("PatientDAO.getPatientByNricPassword", sqlStr.ToString(), ex);
mypatient = null;
}
return result;
}
How do i pass the result to Login.aspx?
Patient.cs
public class Patient
{
public string tbNRIC { get; set; }
public string tbPassword { get; set; }
}
How to check from PatientDAO to see if Username and Password Match and Login.aspx Response.Redirect.
There are some issues with the code I can see.
First in method getPatientByNricPassword it seems you are returning result variable, but this has not been assigned. Probably you want to return the count of records in that case.
Second, you have not initialized PatientDAO fmTd = new PatientDAO(); with the credential details.
Initialize the values appropriately -
PatientDAO fmTd = new PatientDAO();
fmTd.tbNRIC = tbNRIC; // which is txtLogUsername.Text
fmTd.tbPassword = tbPassword ; //which is txtLogPassword.Text
Note that you do not need to put ToString() as text property is already string.
Third, you should have variable for example recordCount to store result of dal method, which you can further check in if condition like this -
var recordCount = fmTd.getPatientByNricPassword(tbNRIC, tbPassword);
if(recordCount > 0)
{
Response.Redirect("Home.aspx");
}

How can we set catch exception in a label?

My Class
public string Countryadd(string country, string id)
{
string data = "0";
try
{
string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
SqlDataReader dr = conn.query(qry1);
if (dr.Read())
{
return data = "1";
}
else
{
string qry = "insert into Country values('" + id + "','" + country + "')";
conn.nonquery(qry);
return data = "3";
}
}
catch (Exception ex)
{
string x = ex.Message();
}
return data;
}
this string value how can we set in a label
My button_click function is
protected void Button1_Click(object sender, EventArgs e)
{
string str = mas.Countryadd(txtcountry.Text, txtid.Text);
if (str == "1")
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else if (str == "3")
{
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
else
{
Label1.Text = str;
}
}
It's not the prettiest of code. Returning a string as a kind of status code is generally bad practice, because you don't know the range of possible values which can be returned, and what they mean. At the very least consider integer or even enum (which is named).
That being said, I would handle the check and the insert in separate methods, and catch the exception in the click event handler - let a single method have a single responsibility:
private void AddCountry(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = string.Format("INSERT INTO Country (Id, Country) VALUES ('{0}', '{1}')", id, country);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}
}
private bool Exists(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = "SELECT Count(*) FROM Country WHERE Country='" + country + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
int count = (int)cmd.ExecuteScalar();
return count >= 1;
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (Exists(txtcountry.Text, txtid.Text))
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else
{
AddCountry(txtcountry.Text, txtid.Text);
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Catch(Exception e)
{
Label.Text= e.Message;
}

Handling multiple buttons in same asp.net page

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

Why is this ignoring the where clause?

Why is the where clause being ignored in this code? It seems to be ignoring the where clause on the update which means every records has been written over. How can i fix this? Any help would be greatly appreciated.
namespace ResitAssignment2
{
public partial class HomeCareVisitEddit : Form
{
public HomeCareVisitEddit()
{
InitializeComponent();
}
private void SubmitHCVA_Click(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqltext;
sqltext = #"update HomeCareVisit set
PatientNo=#PatientNo,
FurtherVisitRequired=#FurtherVisitRequired,
AdvisoryNotes=#AdvisoryNotes,
Prescription=#Prescription,
TreatmentProvided=#TreatmentProvided,
ActualVisitDateTime=#ActualVisitDateTime,
Priority=#Priority,
ScheduledDateTime=#ScheduledDateTime,
TreatmentInstructions=#TreatmentInstructions,
MedicalStaffID=#MedicalStaffID
WHERE
VisitRefNo=VisitRefNo";
SqlCommand command = new SqlCommand(sqltext, a);
try
{
using (a)
{
command.Parameters.AddWithValue("#PatientNo", PatientNo.Text);
command.Parameters.AddWithValue("#FurtherVisitRequired", FurtherVisitRequired.Text);
command.Parameters.AddWithValue("#AdvisoryNotes", AdvisoryNotes.Text);
command.Parameters.AddWithValue("#Prescription", Prescription.Text);
command.Parameters.AddWithValue("#TreatmentProvided", TreatmentProvided.Text);
command.Parameters.AddWithValue("#ActualVisitDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ActualVisitDateTime.Text);
};
command.Parameters.AddWithValue("#Priority", Priority.Text);
command.Parameters.AddWithValue("#ScheduledDateTime",SqlDbType.DateTime );
{
DateTime.Parse(ScheduledDateTime.Text);
};
command.Parameters.AddWithValue("#TreatmentInstructions", TreatmentInstructions.Text);
command.Parameters.AddWithValue("#MedicalStaffID", MedicalStaffID.Text);
command.Parameters.AddWithValue("#VisitRefNo", VisitRefNo.Text);
command.ExecuteNonQuery();
MessageBox.Show("Record altered");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
a.Close();
}
private void HomeCareVisitEddit_Load(object sender, EventArgs e)
{
SqlConnection a = Database.GetConnection();
a.Open();
string sqlText = "select * from HomeCareVisit where VisitRefNo =" + VisitRefNo;
SqlCommand command = new SqlCommand(sqlText, a);
SqlDataReader HomeCareVisitData = command.ExecuteReader();
while (HomeCareVisitData.Read())
{
//DateTime actual = DateTime.Parse("ActualVisitDateTime");
//DateTime scheduled = DateTime.Parse("ActualVisitDateTieme");
PatientNo.Text = HomeCareVisitData["PatientNo"].ToString();
FurtherVisitRequired.Text = HomeCareVisitData["FurtherVisitRequired"].ToString();
AdvisoryNotes.Text = HomeCareVisitData["AdvisoryNotes"].ToString();
Prescription.Text = HomeCareVisitData["Prescription"].ToString();
TreatmentProvided.Text = HomeCareVisitData["TreatmentProvided"].ToString();
ActualVisitDateTime.Text = HomeCareVisitData["ActualVisitDateTime"].ToString();
Priority.Text = HomeCareVisitData["Priority"].ToString();
ScheduledDateTime.Text = HomeCareVisitData["ScheduledDateTime"].ToString();
TreatmentInstructions.Text = HomeCareVisitData["TreatmentInstructions"].ToString();
MedicalStaffID.Text = HomeCareVisitData["MedicalStaffID"].ToString();
}
a.Close();
}
}
}
WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=#VisitRefNo";.
WHERE VisitRefNo=VisitRefNo
Should be
WHERE VisitRefNo=#VisitRefNo

C# programming issue using sql?

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.

Categories

Resources