Data not coming in SqlDataReader - asp.net

Well I am not able to figure out the error.No data is coming in variable SqlDataReader.The data retrieved by variable SqlDataReader is stored in Label2.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=(local);Database=records;User Id=sasfddsf;Password=12345");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = '" + Label1.Text.ToString() + "'", con);
var SqlDataReader = cmd.ExecuteReader();
while (SqlDataReader.Read())
{
Label2.Text += Convert.ToString(SqlDataReader["name"]) + Convert.ToString(SqlDataReader["referenceName"]);
}
SqlDataReader.Close();
}
catch (Exception e1)
{
Label2.Text = "Error: " + e1.Message;
}
finally
{
con.Close();
}
}
}

Try this
SqlCommand cmd = new SqlCommand("select id,name,referencename from records where name = #TextBoxName", con);
com.Parameters.AddWithValue("#TextBoxName",Label1.Text.ToString());
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Label2.Text += Convert.ToString(rdr["name"]) + Convert.ToString(rdr["referenceName"]);
}
rdr.Close();

Related

How to compare a password against a hashed password with Scrypt.NET?

I was trying to use scrypt in asp.net for hashing the passwords from users, in the database, after sign up, but when I try to login, I don't know exactly how to compare the password for user with the hash from database.
Can anyone help me figure it out how to compare a password against a hashed password?
For SIGN-UP I used:
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;
using System.Configuration;
using System.Drawing;
using System.Security.Cryptography;
using Scrypt;
namespace WebApplication1
{
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btSignup_Click(object sender, EventArgs e)
{
if (tbUname.Text != "" & tbPass.Text != "" && tbName.Text != "" && tbEmail.Text != "" && tbCPass.Text != "")
{
if (tbPass.Text == tbCPass.Text)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
ScryptEncoder encoder = new ScryptEncoder();
string hashsedPassword = encoder.Encode(tbPass.Text);
SqlCommand cmd = new SqlCommand("insert into Users values('" + tbUname.Text + "','" + hashsedPassword + "','" + tbEmail.Text + "','" + tbName.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Registration Succesfull";
lblMsg.ForeColor = Color.Green;
Response.Redirect("~/SignIn.aspx");
}
}
else { lblMsg.Text = "Passwords do not match"; }
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "All Fields are Mandatory";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.CommandText = "select * from [Users]where Username=#Uname";
cm1.Parameters.AddWithValue("#Uname", tbUname.Text);
cm1.Connection = con1;
SqlDataReader rd = cm1.ExecuteReader();
if (rd.HasRows)
{
Label1.Visible = true;
Label1.Text = "Username already exists !";
Label1.ForeColor = System.Drawing.Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "Username is available !";
Label1.ForeColor = System.Drawing.Color.Green;
}
}
}
}
And LOGIN:
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;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class SignIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS)) {
SqlCommand cmd= new SqlCommand("select * from Users where Username='"+ Username.Text+"' and Password='"+Password.Text+"'" , con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
Session["USERNAME "] = Username.Text;
Response.Redirect("~/UserHome.aspx"); }
else {
lblError.Text = "Invalid Username or Password !";
}
}
}
}
}
Scrypt.NET handles the comparison of the typed in password and the existing hash for you. The documentation page shows:
ScryptEncoder encoder = new ScryptEncoder();
bool areEquals = encoder.Compare("mypassword", hashedPassword);
In your case that means that you cannot use the password in the SQL query to get a specific user. You would have to use only the given Username to find the correct row in the Users table.
SqlCommand cmd = new SqlCommand("select * from Users where Username=#Username" , con);
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 255, Username.Text);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0) {
ScryptEncoder encoder = new ScryptEncoder();
foreach(DataRow row in dt.Rows)
{
if (encoder.Compare(Password.Text, (string)row["Password"]))
{
Session["USERNAME "] = Username.Text;
Response.Redirect("~/UserHome.aspx");
return;
}
}
} else {
lblError.Text = "Invalid Username or Password !";
}
Always use parametrized SQL queries. Otherwise, you're open to SQL injection attacks.

update a database from dataset

as you see in this code i was update the dataset ds at Button1_Click and i want to update the changes made on that dataset to the database.
if i wrote it at the Button1_Click it is work but when i put exactly the same code at Unnamed1_Click it is not working and i dont know why!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Discount : System.Web.UI.Page
{
DataSet ds = new DataSet();
public void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con); // יצירת dataAdapter
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i][2]);
price -= price * int.Parse(discountrate.Text) / 100;
ds.Tables[0].Rows[i][2] = Convert.ToString(price);
}
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
//SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_");
//con.Open();
//SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
//SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
//tmpda.Update(ds);
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098"))
{
con.Open();
SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
tmpda.Update(ds);
}
}
}
You need to specify the update command for your SqlDataAdapter. Just insert the following code after your commandBuilder instace:
tmpda.UpdateCommand = builder.GetUpdateCommand();

ArgumentException when trying to open a SqlConnection

This code is for the button:
But every time i run it say's ArgumentException was unhandled by user code.
It's a site made to look up in at Database to see if there is enough ink.
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;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Toner Values('"+txtFname.Text+"','"+txtLname.Text+"','"+TxtCity.Text+"')",con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Indsætning succesfuld!!!";
TxtCity.Text = "";
txtFname.Text = "";
txtLname.Text = "";
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
}
My best guess is that TxtCity should be txtCity.
Try this:
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;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string query = "insert into Toner Values (#Fname, #Lname, #City)";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString);
SqlCommand cmd = new SqlCommand(query, con);
//Use parameterized query to prevent SQL injection
cmd.Parameters.Add("Fname", SqlDbType.VarChar, 50).Value = txtFname.Text;
cmd.Parameters.Add("Lname", SqlDbType.VarChar, 50).Value = txtLname.Text;
//C# is case-sensitive... is it txtCity or TxtCity?
cmd.Parameters.Add("City", SqlDbType.VarChar, 50).Value = TxtCity.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Indsætning succesfuld!!!";
TxtCity.Text = "";
txtFname.Text = "";
txtLname.Text = "";
}
}

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
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;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Asp.net how to correct the error

I'm designing in my web page and image are stored in my database (The project is Photostudio management system)
MY Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace photoshops
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != true )
{
constr = #"Data Source=DEVI\SQLEXPRESS;Initial Catalog =cat; Integrated
Security=SSPI";
cnn.ConnectionString = constr;
try
{
if (cnn.State != ConnectionState.Open)
cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "photoset";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#BillNo", TextBox1.Text);
cmd.Parameters.AddWithValue("#CustomerName", TextBox2.Text);
cmd.Parameters.AddWithValue("#Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#StartDate",Rdbsdate.SelectedDate );
cmd.Parameters.AddWithValue("#EndDate", Rdbddate.SelectedDate );
SqlParameter param0 = new SqlParameter("#Systemurl", SqlDbType.VarChar,
50);
cmd.Parameters.AddWithValue("#Numberofcopies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Amount", TextBox8.Text);
cmd.Parameters.AddWithValue("#Total", TextBox9.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new applicationException("!!!! An error an occured while
//inserting record."+ex.Message)
}
finally
{
da.Dispose();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Photo setting sucessfullY";
}
else
{
Msg.Text = "photosetting failled";
}
}
}
}
}
}
My ERROR
The record are not stored and image is not stored how to change in my code .
Well first of all, you're not saving the image, you're saving the path of your computer.
You need to save the byte array of the photo.
In short:
Upload its the upload control where you select the image
pic its the byte arrey where you upload the binary content of the photo
and then you only send it as a simple parameter cmd.Parameters.Add ("#pic", pic);
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new
SqlConnection (#"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (#pic, #text)", connection);
cmd.Parameters.Add ("#pic", pic);
cmd.Parameters.Add ("#text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
here are some tutorials, the first link it's very straightforward and the code its simple
http://www.codeproject.com/KB/web-image/PicManager.aspx
another, just in case:
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/
Principal resource: http://www.codeproject.com/KB/web-image/PicManager.aspx

Resources