Exception thrown while running MySQL query from class - c#

Hie, I'm having a bit of a crisis trying to run an sql query from a C# class. It was working fine in the Login page it was in before and I changed very little of it when I moved it over.
SQL query in class:
namespace Masca
{
public class loginc
{
// Telling the class that the page 'Login' exists.
public Login login;
....
public void Login ()
{
// connection parameters
string sqlcon = "datasource=localhost;port=3306;username = root; password = root";
//Command to carry out -This is what the exception highlights when it's thrown.
string query = "SELECT * FROM logon.login where username = '" + login.username.Text + "' and password = '" + login.password.Password + "';";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlCommand cmd = new MySqlCommand (query,con);
MySqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
int count = 0;
while (rdr.Read())
{
count = count + 1;
}
if (count == 1)
{
//If the username and password match those in the database table, run the method 'login' in the login page cs.
login.login();
}
else
{
// if they don't match, run the method 'failLogin' in the login page cs.
login.failLogin();
}
}
In login.cs I have two textboxes and a button. One for the username and one for the password. The button is supposed to trigger the above code:
public void Logon_Click(object sender, RoutedEventArgs e)
{
loginc.Login();
}
Which it does fine. However I get the classic "Object reference not set to an instance of an object" exception thrown on the query. When I enter the actual credentials instead of '+ login.username.Text +' and '+ login.password.Password +' then the exception gets thrown on 'login.Login()'.
I don't understand why the loginc.cs class refuses to relate to the login.cs but the login.cs clearly has no problem triggering the method in class the same way. Anyone know where I'm going wrong?

I see no code where you instantiate Login login. You should really do that.
Login login = new Login();
or something alike.

Related

How to redirect htm page to another using Response.Redirect?

I am trying to redirect my login.htm to index.htm in c#. both files are inside the folder named 'default'. after logging in, if the credential is correct, I want to redirect the login page to index. using the code below, but there is an exception message Attempted to cancel thread.. Is there a way to fix this?? How you can help me. Thanks in advance.
[WebMethod]
public void LogMeIn(string user, string pass) {
try {
using (MySqlConnection dbConn = new MySqlConnection(connectionString())) {
if (dbConn.State == System.Data.ConnectionState.Open) dbConn.Close();
dbConn.Open();
MySqlCommand sqlCmd = new MySqlCommand("SELECT * FROM tbllogin WHERE userName = '" + user + "' AND passWord ='" + pass + "'", dbConn);
int rowCount = (int)sqlCmd.ExecuteScalar();
if (rowCount > 0) {
HttpContext.Current.Response.Redirect("../default/index.htm"); //redirect to new htm page
}
}
}
catch (Exception ex) {
Console.WriteLine("Error Message : " + ex.Message);
}
}
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath+"default/index.htm");
Or you can use this way.
HttpContext.Current.Response.Redirect is trying to send users to the wrong place
HttpContext.Current.Response.Redirect("~/default/index.htm");
There are some errors and unnecesary code in your code example:
There is no need to check if dbConn is already opened, because it was just created
The SELECT * caused an Exception when doing later an ExecuteScalar because the table has more than one column. You should change it to SELECT COUNT(*)
Because how Microsoft handles how the flow of the page is done, if you don't end the response when doing the Response.Redirect you may need to catch an ThreadAbortException. To end the response you could check Redirect(string url, bool endResponse) overload
That being said, you should do use parametrized queries, because unexpected or malicious input could cause you problems.

Invalid Object error while trying to perform a SQL query

I'm trying to make my first steps in databases used with WPF. The problem is that once I start the application, I get an error saying
Invalid Object - "tblUser"
where tblUser is the name of a table.
I made sure that table name is correct, tried creating another table to see whether it changes anything. All the permissions are granted to manipulate the table.
private void Submit_OnClick(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;");
try
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
String query = "SELECT COUNT(1) FROM tblUser WHERE Username = #Username AND Password = #Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username",txtUsername.Text);
sqlCmd.Parameters.AddWithValue("#Password", txtPassword.Text);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
MainWindow dashboard = new MainWindow();
dashboard.Show();
this.Close();
}
else
{
MessageBox.Show("Username or password does not exist");
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
finally
{
sqlCon.Close();
}
}
First I create a connection to the database. Next step is I would like to check whether connection is closed, if it is I'm opening it. Then it looks like something went wrong with the SQL query because it seems not to recognise tblUser and sees it as an invalid one.
tblUser is certainly not in the master database. The asterisks are not part of SQL. I am surprised that the error message doesn't complain about that at first

Login Button to read sql database and confirm values entered into textboxes with values in said sql database throws error

I am a noob attempting to create a login page where the user enters their username and password that is already in the sqldatabase connected to the textboxes/button/form. The below code is my best attempt at doing so, but upon debugging it throws catch despite the textbox values entered being registered in the sql database. If any additional information is needed please ask.
private bool compareStoD(string teststring1, string teststring2)
{
return String.Compare(teststring1, teststring2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(#"Data Source=DESKTOP-P3JSE1C;Initial Catalog=logins;Integrated Security=True");
connection.Open();
SqlCommand checker = new SqlCommand("SELECT COUNT (*) from users WHERE username='" + textBox1.Text + "'AND pssword='" + textBox3.Text + "'", connection);
SqlDataReader reader = checker.ExecuteReader();
string usernameText = textBox1.Text;
string psswordText = textBox3.Text;
while (reader.Read())
{
if (this.compareStoD(reader["username"].ToString(), textBox1.Text) && // replace textbox1.Text with text string usernameText
this.compareStoD(reader["pssword"].ToString(), textBox3.Text)) //replace textbox3.Text with text string psswordText
{
main wen = new main();
wen.Show();
}
}
reader.Close();
connection.Close();
}
catch
{
MessageBox.Show("Incorrect password or username.");
}
}
It is most likely throwing an exception because your query is asking for the count but then you are reading columns username and password which do not exist in the reader. This is your query:
SELECT COUNT (*)
Change that to this:
SELECT username, password ...
Also, unless you want every savvy user to access your application, use SqlParameter to avoid SQL Injection
Another Suggestion
I am not sure what main is, my assumption it is some window, but I would not show it where you are showing right now. Try to close the reader as soon as possible and then show the window if the user is authenticated like this.
bool userIsAuthenticated = false;
if (reader.Read())
{
// if a row was returned, it must be the row for the user you queried
userIsAuthenticated = true;
}
reader.Close();
connection.Close();
// Now that the reader is closed, you can show the window so the reader does not stay
// open during the duration of the main window
if (userIsAuthenticated)
{
main wen = new main();
wen.Show();
}
Select count returns the count not the row, if you want the row itself change to select username, password instead of select count(*) . See this link
There is over work being done by your code. You are querying the database by comparing the username and password values from UI to the values in the table. And once and if values are retrieved from the database you are again comparing value from UI to the values coming from the database. This is unnecessary.
The query will return the values only if values match in the database so you don't need to compare them again. So method compareStoD is not required at all.
The button1_Click can be changed as following to make it simpler.
private void button1_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(#"Data Source=DESKTOP-P3JSE1C;Initial Catalog=logins;Integrated Security=True");
connection.Open();
SqlCommand checker = new SqlCommand("SELECT COUNT (*) from users WHERE username=#userName AND pssword = #password", connection);
checker.Parameters.Add(new SqlParameter("#userName", textBox1.Text));
checker.Parameters.Add(new SqlParameter("#password", textBox3.Text));
var count = Convert.ToInt32(checker.ExecuteScalar());
connection.Close();
if(count > 0)
{
main wen = new main();
wen.Show();
}
else
{
MessageBox.Show("Incorrect password or username.");
}
}
catch
{
MessageBox.Show("Incorrect password or username.");
}
}
Also one good practice while supplying values from Textbox, you should use Textbox.Text.Trim() which helps in eliminating the spaces at the beginning and end. These spaces can create a problem in later stage.

how to prevent data overloading at different sessions using asp.net

I wrote some code for search page as follows
I declared variables in above page load as follows
static String strsql = "";
in page load
if(!isPostback)
{
if(session["username"] != null)
{
loadprofiles(); // calling loadprofiles method
bindlist();//loading gridview data
}
}
now loadprofiles method wrote as follows
protected void loadprofiles()
{
strsql = "select * from admintable where userid = '"+session["username"].Tostring()+"'";
}
now bindlist method is as follows
private void bindlist()
{
SqlCommand comm1 = new SqlCommand(strsql, connection);
//and some code for binding data to gridview
}
the problem is while two different users are login into this page from two different computers the user getting the data from second login persions
please help me to solve this problem...
thanks in advance
I was having Session issue for multiple tabs in a single browser.
In Default.aspx/Index.aspx write below code to generate a Unique session Id's.
if (Page.IsPostBack == false) //If page loads for the first time
{
ViewState["_PageID"] = Guid.NewGuid();
}
To store any variable in session Use the following lines:
Session[ViewState["_PageID"].ToString() + "username"] = "testuserName";
To access anything stored based on the Session Id:
string userNameInSession = Session[ViewState["_PageID"].ToString() + "username"] as string;
You cannot declare strsql as static since it will store value for all users - user1 will have access to the user2 strsql value. You have to remember that static is a member of a type, not an instance - it will be accessible for all users until AppDomain is unloaded.
In my opinion you shouldn't store SQL query in a variable(it seems unnecessary since session is accessible everywhere in your code).
I'd change your code to the
private void bindlist()
{
SqlCommand comm1 = new SqlCommand("select * from admintable where userid = '"+session["username"].Tostring()+"'", connection);
//and some code for binding data to gridview
}
EDIT:
Since you want to reuse query, you can return it from loadprofiles() method like follows:
protected string loadprofiles()
{
strsql = "select * from admintable where userid = '"+session["username"].Tostring()+"'";
// Do your logic there...
return strsql;
}
and use it:
if(!isPostback)
{
if(session["username"] != null)
{
var strsql = loadprofiles(); // calling loadprofiles method
bindlist(strsql);//loading gridview data
}
}
I believe you get the point.

How to display full name instead of username using session?

I am new to web development and .NET too. I have a website written in ASP.NET using C#. How should I display full name of the current user instead of username using sessions? Please help me. Here is the code.
Code behind login page:-
Session["username"] = txt_un.Text.Trim().ToString();
Code behind userprofile page:-
string str = "select fullname from userprofile where username=#username";
Label4.Text = Session["username"].ToString();
The problem is that fullname is not present on the login page. It is present in userprofile page. How to display fullname on the userprofile page after user click on login button?User is using his registration_id as username. But I don't want to display registration_id,I want to display fullname of the user.Pls give me answer in detail. Thank you in advance.
You need to get first name, Whenever you login in your app with this select query and ExecuteScalar.
string str = "select fullname from userprofile where username=#username";
Then You need to store the first name into a session
Session[firstName]=Query return value
And finally you can give
if(Session[firstName]!=null)
{
Label4.Text=Session[firstName].ToString()
}
I really don't understand clearly what you need but somehow you need user's full name to show some where using username,
Here one simple function that will return you the full name.
I assume you know how to connect your webpage to the SQL Server and all the functions
public string GetFullName(string username)
{
string query = "select fullname from userprofile where username ='" + staffID + "'";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
try
{
while (reader.Read())
{
return reader["fullname"].ToString();
}
}
catch (Exception ex)
{
HttpContext.Current.Session["Error_Message_Session"] = ex;
HttpContext.Current.Response.Redirect("Error.aspx", false);
}
finally
{
conn.Close();
}
return "-";
}
The function that i used here is from my own project, this is how i get the full name by his username, similarly i had the same problem so i did this, just a simple static function

Categories

Resources