how to store primary key in session with stored procedure - asp.net

I have login page for which I have used stored procedure. I am using session to store id of user which is primary key. When I enter wrong username and password it should redirect to some other page but it is giving me exception as "Object reference not set to an instance of an object." My code for login.aspx.cs is:
SqlCommand cmd1 = new SqlCommand("select artistId from artist where Username=#username and Artistpass=#password",con);
cmd1.Parameters.AddWithValue("#username", txtusr.Text);
cmd1.Parameters.AddWithValue("#password", txtpass.Text);
con.Close();
Session["username"] = txtusr.Text;
SqlParameter param = new SqlParameter("#username", txtusr.Text.Trim());
SqlParameter param1 = new SqlParameter("#password", txtpass.Text.Trim());
SqlCommand cmd = new SqlCommand("login", con);
cmd.Parameters.Add(param);
cmd.Parameters.Add(param1);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.Redirect("afterlogin.aspx");
}
else
{
MessageBox.Show("Login Unsuccessful");
}
con.Close();
if (con.State != ConnectionState.Open)
{
con.Open();
}
int id = (int)cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
plz help.

ExecuteScalar returns null if your where statement doesn't find a match for your user and password
So you cannot cast a null return value to an integer
object id = cmd1.ExecuteScalar();
Session["ID"] = id;
con.Close();
this, of course, means that you need to check the Session["ID"] variable in the redirected page to see it it is null

Related

How to select values in ASP.NET using SQL

I have a table in my database and two textbox and a button in my ASP.NET. I want to call database and select product name and code and if the entrance is correct I want to ok message, otherwise false!
Here is my code, but I did not get correct result.
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Code", txtCode.Text);
SqlDataReader dr = cmd.ExecuteReader();
scon.Close();
Label1.Text = "The Product is in our list.Thank you";
}
catch(Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Your query is modified as below
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.Add("#Name", SqlDbType.Varchar).Value = txtName.Text;--Update the datatype as per your table
cmd.Parameters.Add("#Code", SqlDbType.Varchar).Value = txtCode.Text;--Update the datatype as per your table
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
--If you want to check the whether your query has returned something or not then below statement should be ommitted. Else you can check for a specific value while reader is reading from the dataset.
while (dr.Read())
{
--The returned data may be an enumerable list or if you are checking for the rows the read statement may be ommitted.
--To get the data from the reader you can specify the column name.
--for example
--Label1.Text=dr["somecolumnname"].ToString();
Label1.Text = "The Product is in our list.Thank you";
}
}
else
{
Label1.Text = "The Product is not in our list.Sorry!";
}
scon.Close();
}
catch (Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Hope this answer will help you in resolving your query.

Table expects a parameter which already exists

ALTER PROCEDURE tableuser
-- Add the parameters for the stored procedure here
#userName varchar(50)
AS
IF EXISTS(SELECT 'True' FROM tbl_user WHERE userName = #userName)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into tbl_user(userName) VALUES(#username)
END
This is my code in sql server management studio and below is the C# code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("tableuser", conn);
conn.Open();
SqlParameter param = new SqlParameter();
cmd.Parameters.AddWithValue("#userName", uname.Text);
param.Value = uname.Text;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Response.Write("Username exists");
}
else
{
cmd.Parameters.AddWithValue("#userName", uname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("Successfully saved...!!!");
conn.Close();
}
}
}
The error comes is: Procedure or function 'tableuser' expects parameter '#userName', which was not supplied.
This should work:
conn.Open();
var cmd = new SqlCommand("tableuser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userName", uname.Text);
var rdr = cmd.ExecuteReader();
rdr.Read();
Response.Write(rdr.GetString(0));
conn.Close();

why does SELECT SCOPE_IDENTITY() returning null?

I am trying to get ID generated by last Insert function. I understand very little about Scope and Session. But by reading blogs and other sources, I understood that, I should use Scope_Identity() function. But I am getting null value. Here is my code :
public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
try
{
string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (#username,#gender,#age,#email,#partnerid,#usertype)";
SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#age", agegroup);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#partnerid", partnerID);
cmd.Parameters.AddWithValue("#usertype", userType);
if (cmd.ExecuteNonQuery() > 0)
{
query = "select scope_identity() as id";
cmd = new SqlCommand(query, _dbConnection.getCon());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);// dt is showing no value in it
return 1;// This should return ID
}
else {
return -1;
}
}
catch (Exception e) {
throw e;
}
}
How can I achieve this?
Try appending SELECT scope_identity() to your first query and then capture the identity using var identity = cmd.ExecuteScalar() instead of running cmd.ExecuteNonQuery().

How to check two different webforms having same value of textboxes

aspx
TextBox1.Text
World.aspx
TextBox1.Text
I want the pages Hello.aspx and World.aspx having same value of validation
please help me anybody have the idea about this
You need to save the value on the first page using cookies or database or something else.
Then retrieve the value in the second page and compare the values in the validation function or event.
using(SqlConnection cn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
string sql = string.Format(#"select email from customers where customer_id = '{0}'", customer_id);
cmd.CommandType = CommandType.Text;
//try and catch block would go here
cmd.CommandText = sql;
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
string email = rdr[0].ToString();
cn.Close();
}
}

sql stored procedure in asp.net not running

A little background on what I'm doing.
I have a button that has a click call which takes me to this code.
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
try
{
cnn.Open();
SqlCommand Comm = new SqlCommand(sqlString, cnn);
Comm.CommandType = CommandType.StoredProcedure;
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
// log here should anything go wrong with anything
// lblmessage.Text = "Error: " + ex.Message;
if (comm != null)
comm.Dispose();
if (cnn != null)
cnn.Close();
DataTable dt = new DataTable("ExceptionTable");
dt.Columns.Add("ExceptionMessage");
dt.Rows.Add(ex.Message);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
}
The code runs fine however nothing is written to database. here is do_share_files stored procedure.
ALTER PROCEDURE [dbo].[do_share_files]
--#device_id bigint, #user_id bigint, #file_name varchar(50),#full_up_path varchar(50), #upLength varchar(30)
--,#mime_type varchar(20), #filedate varchar(30)
AS
BEGIN
insert into [user_files] (device_id, user_id, original_name, original_path, up_path, content_type, up_dt)
values (17, 30, 'test.pg', 'test.pg', 'test.pg','test.pg', '2012-11-15 03:58:06.043')
END
I have static values for now since i'm just trying to get it to run to stored procedure.
I'm new to asp.net and don't know what i'm doing wrong. Any help would be appreciated.
Thanks!
You could start with this:
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
string sqlString = "do_share_files"; // it's a stored procedure
DataSet ds = new DataSet();
try
{
using (var cnn = new SqlConnection(masterConn))
{
SqlCommand comm = new SqlCommand(sqlString, cnn);
comm.CommandType = CommandType.StoredProcedure;
cnn.Open();
comm.ExecuteNonQuery ();
To summarize:
Comm and comm are different commands;
To run the proc, you need to call ExecuteNonQuery or other Execute method.
Your code has few mistakes
1. I cant understand why you are using this line twice
SqlCommand comm = new SqlCommand(sqlString, cnn);
2. You didnot execute the procedure which is the main problem
static public DataSet shareFiles(TransitoryRegObj argTransRegObj)
{
try
{
string sqlString = "do_share_files"; // it's a stored procedure
SqlConnection cnn = new SqlConnection(masterConn);
SqlCommand comm = new SqlCommand(sqlString, cnn);
DataSet ds = new DataSet();
cnn.Open();
Comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
comm.Dispose();
cnn.Close();
return ds;
}
catch (Exception ex)
{
//something here
}
}

Resources