"Use of unassigned variable" error - c#

I am developing this website in ASP.NET and using C#. I am Getting the error that :Use of unassigned variable usn. The database is also not empty.
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
cn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Vijaylaxmi\Desktop\TrainReserveold\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
cn.Open();
cm.Connection = cn;
String usn;
cm.CommandText = "Select UserName from User where UserName='" + TextBox1.Text + "'";
dr = cm.ExecuteReader();
while (dr.Read())
{
usn = dr.GetString(0);
}
if (String.Compare(usn, TextBox1.Text) != 0)
{
Response.Write("Invalid user name... try again");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox1.Focus();
}
Response.Write("user valid now");
}

Several problems I see here. In specific response to your question, you want to replace this:
dr = cm.ExecuteReader();
while(dr.Read())
{
usn = dr.GetString(0);
}
with this:
usn = cm.ExecuteScalar().ToString();
Be sure to check for DBNull first, just in case.
More generally, you want to
a) Parameterize your SQL (or, better, use a stored proc) instead of using raw input. This will protect you from SQL Injection attacks.
b) Not include your connection string directly in code. Put it in a config file. Most certainly don't post it on the internet.

assing the usn string up top as
string usn = string.empty; then go from there
//create a Stored Procedure and put your Select Statement in there.. to avoid Sql Injection
cmd.CommandText = "name of your stored proc";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
I would also read my sql connectiong string from a web.config or app.config depending on the type of application you are running.

change your cm.CommandText = "Select UserName from User where UserName=
to
cm.CommandText = string.Format("Select UserName from User where UserName= '{0}'",Textbox1.Text);

Related

Checking if username is available in database

I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}

How do i fix invalid column name in sql

I'm a beginner in SQL and c#. I'm trying to create a system that will lead the user to eligibility form if they have not done it before, but an error that says invalid column name keeps popping.
string query = "select * from Eligibility where Name = " + textBox1.Text;
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label6.Text = (dr["name"].ToString());
}
sql.Dispose();
if (label6.Text == textBox1.Text)
{
this.Hide();
UserHomeView uhv = new UserHomeView();
uhv.Show();
}
else
{
this.Hide();
Eligibility eli = new Eligibility();
eli.Show();
}
You missed the single quotation
string query = "select * from Eligibility where Name = '" + textBox1.Text + "'";
Even so, there is some serious problem with the above code. This can cause a serious sql injection problem for you Check wikipedia entry on this
It's better to use the add parameters function which will sanitize the input and make it safe for you to execute the query.
The best solution would be something like this
string query = "select * from Eligibility where Name = #Name";
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = textBox1.Text;
This way, your query will be injection safe.
Just to build on what others have said:
Once you're comfy with doing things this way check out Stored Procedures.
Stored Procedures lets you save the query in the database and all you do on the c# side is call the Stored Procedure and add the required parameters.
These tend to be a better way of doing this as you can then learn about how to restrict access to your database for only certain users and also it means the Query itself is in an environment that will check for mistakes as well.
This is a good article as an introduction to them:
http://www.sqlservertutorial.net/sql-server-stored-procedures/
You can use Parameters of SqlCommand, like this:
string query = "select * from Eligibility where Name = #Name";
sql.Open();
SqlCommand cmd = new SqlCommand(query, sql);
cmd.Parameters.Add("#Name", SqlDbType.Text);
cmd.Parameters["#Name"].Value = textBox1.Text;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label6.Text = (dr["name"].ToString());
}
sql.Dispose();
if (label6.Text == textBox1.Text)
{
this.Hide();
UserHomeView uhv = new UserHomeView();
uhv.Show();
}
else
{
this.Hide();
Eligibility eli = new Eligibility();
eli.Show();
}

Visual Studio Login Page with local SQL server database

I'm creating a visual studio project that uses a local SQL server database as a data source, which is up and running correctly.
I need to create a login form for the project.
The form has a username textbox and a password textbox which the user will populate with their details, and then hit the 'login' button, which needs to execute the select sql statement.
Any references on how to do this?
The code I have tried is below.
It's throwing a NullReferenceException at the line that says "SqlDataReader dr = cmd.ExecuteReader();"
How do I Solve the nullreferenceexception?
Thank you!
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MARKO-PC\\SQLEXPRESS;Initial Catalog=IS2B_G8_FundMeDB;Integrated Security=True";
con.Open();
String sql = "Select * from APPLICANT where applicant_ID_passport =#user AND password = #password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("#user", txtUserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login Failed");
}
}
catch (SqlException sqle)
{
MessageBox.Show("Sql Exception");
}
}
Try this
string struser = txtUserName.Text;
string strpwd = txtPassword.Text;
String sql = "Select * from APPLICANT where applicant_ID_passport=" + struser + " AND password = " + strpwd +"";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
You need to do some research into using ADO.Net, specifically the SQLCommand class.
However I would refrain from using inline sql statements like above as this opens you up to SQL injection. Rather use paramaterised queries, stored procedures or LINQ to SQL.

Creating a sql connection in c#

I'm new to this site and also to programming. I am currently creating an inventory system via a point of sale. It uses modal and non-modal forms. My problem is tho, I'm working on the change password dialog which has to be connected to the database in order to overwrite the password field. The database i used is microsoft sql server management studio express. Here is what I have so far with the necessary comments. Please note that on the 'design' form, I have a combobox which is bounded to the database. Where did I go wrong?
private void ChangePwdButton_Click(object sender, EventArgs e)
{
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Gerald- dean Martin\Documents\SQL Server Management Studio Express\Projects\BodyMates.mdf;Integrated Security=True;User Instance=True";
sqlconn.Open();
string oldpwd = txtOldPwd.Text;
string newpwd = txtNewPwd.Text;
string confirmNewPwd = txtConfirmNewPwd.Text;
string sqlquery = "UPDATE [Employee] SET Pwd=#newpass where EmployeeCode=#empcode";
SqlCommand cmd = new SqlCommand(sqlquery, sqlconn);
cmd.Parameters.AddWithValue("#newpass", txtConfirmNewPwd.Text);
cmd.Parameters.AddWithValue("#empcode", comboEmpCode.SelectedValue);
//cmd.Parameters.AddWithValue("#pwd", txtNewPwd.Text);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(txtOldPwd.Text == dr["pwd"].ToString() && (txtNewPwd.Text == txtConfirmNewPwd.Text))
{
if (comboEmpCode.SelectedIndex == 0)
{
string query = "UPDATE [Employee] SET Pwd = '" + txtConfirmNewPwd.Text + "'";
}
}
// if ((txtNewPwd.Text == dr["newpwd"].ToString()) & (txtConfirmNewPwd.Text == (dr["confirmNewPwd"].ToString()))) { }
}
// MessageBox.Show("Password was changed Successfully!", "Password Change", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You can use ExecuteNonQuery like cmd.ExecuteNonQuery(); It returns int value. Use it like this;
int i = cmd.ExecuteNonQuery();
And also ExecuteReader() works like this;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
You can read returning data's column. Like first column reader[0], second column reader[1] etc.
But before all this information, if you are new to programming, you can find a lot of book proposal and useful informations on Stackoverflow. Check these articles;
What is the single most influential book every programmer should read?
https://stackoverflow.com/questions/477748/what-are-the-best-c-sharp-books
https://stackoverflow.com/questions/2018/best-book-for-a-new-database-developer

How can I get a username and password from my database in C#?

I have the following code in my btn_click event:
Sqlconnection con = new Sqlconnection("server=.;database=bss;user id=ab;pwd=ab");
con.open();
SqlCommand cmd = new Sqlcommand("select * from login where username='"
+ txt4name.Text + "' and pwd='" + txt4pwd.Text + "'", con);
SqlDataReader reader = cmd.execute Reader();
Where login is the table and username and pwd are its fields. After this code all the values are stored in the reader object. I want to store username and pwd in the separate variables.
How can I accomplish this?
In general, when accessing your DB, you should be using something similar to this instead to eliminate SQL injection vulnerabilities:
using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=#username AND PASSWORD=HASHBYTES('SHA1', #password)", myConnection))
{
myCommand.Parameters.AddWithValue("#username", user);
myCommand.Parameters.AddWithValue("#password", pass);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader())
...................
}
But more realistically to store credentials, you should be using something like the Membership system instead of rolling your own.
You're running a huge risk of sql injection with that. Use SQL Parameters for values into SqlCommands.
If you mean c# variables, and if you want to get them from db, just do this:
SqlDataReader reader = cmd.execute Reader();
if (reader.Read())
{
string username = reader["username"];
string pwd = reader["password"];
}
While you are at it, parameterize your query and prevent sql injection:
SqlCommand cmd = new Sqlcommand("select * from login where username=#username and pwd=#pwd", con);
cmd.Parameters.AddWithValue("#username", txt4name.Text);
cmd.Parameters.AddWithValue("#pwd", txt4pwd.Text);
Definitely heed the advice about SQL injection but here is the answer to your question:
String username;
String pwd;
int columnIndex = reader.GetOrdinal("username");
if (!dataReader.IsDBNull(columnIndex))
{
username = dataReader.GetString(columnIndex);
}
columnIndex = reader.GetOrdinal("pwd");
if (!dataReader.IsDBNull(columnIndex))
{
pwd = dataReader.GetString(columnIndex);
}
string userName = txt4name.Text;
string password = txt4pwd.Text;
Is that really what you want? Just to get that data into variables?
You really need to use parameterized SQL. There's an example here
Furthermore, your question doesn't really make sense; you want the username and password in seperate variables? they already are seperate in your example. If you are unable to assign them to strings I suggest following some tutorials.
Another approach is to load the reader results into a DataTable like so:
DataTable Result = new DataTable();
Result.Load(reader);
If your login table only contains two columns (userName and password) that are unique you end up with Result containing only one row with the information. You can then get the column values from each column:
string userName = Result.Rows[0].Field<string>("userName");
string password = Result.Rows[0].Field<string>("pwd");
private void but_login_Click(object sender, EventArgs e)
{
string cn = "Data Source=.;Initial Catalog=mvrdatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(cn);
con.Open();
SqlCommand cmd = new SqlCommand("select count (*) from logintable where username ='" + txt_uname.Text + "'and password='" + txt_pass.Text + "'", con);
int i = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (i == 1)
{
Form2 f2 = new Form2();
MessageBox.Show("User login successfully........");
this.Hide();
f2.Show();
}
else
{
MessageBox.Show("INCORRECT USERID AND PASSWORD", "Error");
}
}
You can usually find basic usage examples on MSDN, like this one for SqlDataReader.

Categories