Null reference on SQL connection object - c#

I am new to C#. I have created the login screen.I this one am not able to check the username and password.This is my code.Can anyone help me please.Thanks in advance.Please don't hesitate to copy the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Voting_Editor_Tool
{
public partial class Form1 : Form
{
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string username = txtusername.Text;
string password = txtpassword.Text;
if (ValidateUserNamePassword(username, password))
{
// move to next form or do whatever you need to do after a successfull login
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
public bool ValidateUserNamePassword(string _username, string _password)
{
// string connectionString = "Data Source=[servername];Initial Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];";
using (SqlConnection cn= new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("#username", _username);
sqlParams.AddWithValue("#password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.
// this means that the user's input is valid
return true;
}
else
{
return false;
}
dr.Close();
cn.Close();
}
}
}
}

Remove your using clause and put that piece of code into Try.. catch block. Catch the exception object and read its stacktrace. Check the connection string carefully for any typo mistakes. This should give you much more details to debug than generic error like "Object reference not set to an instance of an object"

You have a semi-colon at the end of your using statement, therefore terminating the using. Remove the semi-colon and it will work.

Related

Using table.Rows.count in c# i don't think my database is connected

I am trying to make my own login screen and registration and I got to the part where I want to know if the user exists. For some reason I create my user in my database and it keeps saying "no" when my user already exists.
I don't see what the problem is because I followed this youtube video and I understand the code so I really don't know why it doesn't work. I think my database is not connected because I am using a different port on xamp and I tried typing localhost:3306 but that didn't work, I get an error, so I tried localhost but now I think it's not connected
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Krunsj_V1
{
public partial class Officiallogin : Form
{
public Officiallogin()
{
InitializeComponent();
}
public Officiallogin(bool doNotMakeInvisibile)
{
InitializeComponent();
}
private void bunifuCustomLabel1_Click(object sender, EventArgs e)
{
this.Hide();
Register Register = new Register();
Register.ShowDialog();
}
private void btnLogin_Click(object sender, EventArgs e)
{
DB db = new DB();
String username = txtUsername.Text;
String password = txtPassword.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = #usn and 'password' = #pass", db.GetConnection());
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = username;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = password;
adapter.SelectCommand = command;
adapter.Fill(table);
// check if there user exists or not
if (table.Rows.Count > 0)
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}
//Application.Exit();
//Mainwindow main = new Mainwindow(true);
//main.Visibility = System.Windows.Visibility.Visible;
//main.ShowDialog();
}
private void txtPassword_OnValueChanged(object sender, EventArgs e)
{
//txtPassword.isPassword = true;
}
//////////////////////////////
// close button properties //
//////////////////////////////
private void lblclose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void lblclose_MouseEnter(object sender, EventArgs e)
{
lblclose.ForeColor = Color.Black;
}
private void lblclose_MouseLeave(object sender, EventArgs e)
{
lblclose.ForeColor = Color.Purple;
}
}
}
The problem is in this SQL statement:
WHERE `username` = #usn and 'password' = #pass
'password' is a string literal, so you are asking if the user's parameterized password is the literal string "password".
To quote a column name in MySQL, use backticks:
WHERE `username` = #usn and `password` = #pass
Or drop them entirely, since username and password aren't reserved words in MySQL:
WHERE username = #usn and password = #pass
Finally, this code implies that you're storing the users' plain text passwords directly in the database. This is a huge security vulnerability and should never be done. Research password hashing (e.g., at https://auth0.com/blog/hashing-passwords-one-way-road-to-security/) or use an off-the-shelf login system instead of trying to build your own.

Insert into database c# connection string error

i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.

Connecting c#.net To phpmyadmin database(MysqL)

I have .NET program written in C# that connects to my website's phpmyadmin which is in cpanel. My problem is that when I'm at the office I can connect to my phpmyadmin server, but when i'm, for example in my house, I can not connect to the server.
I've already included my ISP (www.whatismyip.com/www.speedtest.net) IP in my remoteMySQL in cpanel, but for some reason it only works at the office. Do you think that maybe it is because they are the one hosting the website that I'm connecting to?
My Connection is something like this:
string connection = "SERVER=MyWebsite.com; Database=databse_pcc; Uid=mywebuser; Pwd=password;";
con9.Open();
MySqlCommand cmd9 = new MySqlCommand("Select * from biometrics_tbl LIMIT 1", con9);
cmd9.CommandType = CommandType.Text;
cmd9.Connection = con9;
MySqlDataReader rdr9 = cmd9.ExecuteReader();
while (rdr9.Read())
{
MessageBox.Show(rdr9.GetString(2));
}
con9.Close();
Note this style of connection is working only at the office :(
First off, you're connecting to a database server, namely MySQL not PHPMyAdmin which is a web client for MySQL.
Second assuming what you've said is correct and you have in fact allowed your IP to login to the MySQL database using the login provided, you'll still need to make sure your company allows remote MySQL connections (not likely if they value security).
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1: Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form1()
{
InitializeComponent();
}
bool _regiter()
{
int retval = 0;
try
{
string SQLS = string.Empty;
SQLS += "INSERT tb_user SET ";
SQLS += "fullname='" + textBox1.Text + "'";
SQLS += ",user='" + textBox2.Text + "'";
SQLS += ",password='" + textBox3.Text + "'";
conn.Open();
using (MySqlCommand com = new MySqlCommand(SQLS, conn))
{
retval = com.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { conn.Close(); }
return retval > 0;
}
private void button1_Click(object sender, EventArgs e)
{
_regiter();
MessageBox.Show("Register Success");
Form2 oRegisterrr = new Form2();
oRegisterrr.ShowDialog();
this.Close();
}
}
}
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form2 : Form
{
MySqlConnection conn = new MySqlConnection(#"Data Source = localhost;port=3306;Initial Catalog=loginandregister; User Id=root;password=''");
public Form2()
{
InitializeComponent();
}
private void LoginProcess()
{
if (login(textBox1.Text, textBox2.Text))
{
MessageBox.Show("Welcome " + textBox1.Text);
this.Hide();
//Form_Menu oFormMenu = new Form_Menu();
// oFormMenu.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Login Fail");
}
}
private Boolean login(string sUsername, string sPassword)
{
string SQL = "SELECT user,password FROM tb_user";
conn.Open();
MySqlCommand cmd = new MySqlCommand(SQL, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((sUsername == reader.GetString(0)) && (sPassword == reader.GetString(1)))
{
conn.Close();
return true;
}
}
conn.Close();
return false;
}
private void button1_Click(object sender, EventArgs e)
{
LoginProcess();
}
}
}

can't display "wrong pw"

I have this simple login page below ,
if I enter correct ID + pw -> success (which I want)
if I enter wrong ID -> wrong login (which I want)
But if I enter correct ID + wrong ID , I Want it to say wrong password.
How can I do it?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
if (TextBox1.Text == dr.GetString(0) || TextBox2.Text == dr.GetString(1))
{
Session["x"] = TextBox1.Text;
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong login";
}
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
while this doesn't answer your question, I see a MAJOR security flaw with your logic. I think no matter what failure your users encounter, invalid username or invalid password, you should always display the same "invalid login" message.
If you have someone who is attempting to break into the system, once you validate that a user account exists (invalid password) they can then begin to crack that specific account's password using brute force.
Just something to think about.
You are putting your logic wrongly here. the logic will be
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (TextBox1.Text.Trim() == dr.GetString(0) || TextBox2.Text.Trim()== dr.GetString(1))
{
if (TextBox2.Text.Trim()== dr.GetString(1))
{
Session["x"] = TextBox1.Text.Trim();
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong password";
}
}
else
{
Label2.Text = "wrong login";
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
You read the firstname and the lastname from the database, but then check for the password against the lastname. I doubt that this field contains a valid password
A part from this logic error, you should use a WHERE clause in your statement to check if the user is present or not in the database.
protected void Button1_Click(object sender, EventArgs e)
{
// Command with parameters that check if a user with the supplied credentials exists
// If the user exists then just one record is returned from the datatable....
string cmdText = "SELECT FirstName,LastName " +
"FROM Employees " +
"WHERE username=#uname and pass=#pwd";
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text);
using(SqlDataReader reader = cmd.ExecuteReader())
{
// If the Read returns true then a user with the supplied credentials exists
// Only one record is returned, not the whole table and you don't need to
// compare every record against the text in the input boxes
if(reader.Read())
{
Session["x"] = reader.GetString(0);
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "Invalid credentials";
}
}
}
}
Another point to keep in mind is the following. In the database you should not have a password in clear text. The correct way to store password is to store an hashed string corresponding to the password and then applying the hashing function to the user input and check for same hashed string in the database

Arithmetic operation resulted in an overflow error c#

Hello i'm using c# to build an application to connect to remote mysql server.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MessageBox.Show("Authed!");
}
else
{
MessageBox.Show("Auth Failure.");
}
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=myhostname;user=myusername;password=mypassword;database=mydatabase;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test WHERE username = '" + username + "' AND password = '" + password + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
}
}
It shows the following error:
"OverflowException was unhandled
Arithmetic operation resulted in an overflow "
I'm not using any arithmetic operations here. Any help ???
Check the test table in mysql server.
Make sure that all fields have valid values in the username and password columns.
UPDATE
try to include the option "Use Pipe=false;",with your connection string.Then it will opens the connection just fine.
I hope this will help to you.

Categories

Resources