I am facing the followingj problem: I have a database on Access 2010 with fields NIC,Active and Page, all are of number types. I want to create a login page that takes NIC (numeric) as an input from the user and then redirects them to specific page as per their NICs.
Different people will see different pages.. I am getting an error in ExecuteScalar command, maybe my query is not correct or maybe ExecuteScalar can't hold the query... I am getting data type mismatch error.
try
{
FirsstPage f = new FirsstPage();
SecondPage second = new SecondPage();
oledcon.Open();
string NIc = ( TextBox1.Text);
// string query = "select * from LogINTable where NIC='" + NIc + "'AND Active=0 AND page=1";
//string query = "select * from LogINTable where NIC='" + nic + "'AND Active=0";
string query = "SELECT * FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1";
//string query = "select
OleDbCommand comm = new OleDbCommand( query,oledcon);
string a = (string) comm.ExecuteScalar();
if (a != null)
{
Response.Redirect("FirsstPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" + NIc + "' ";
//OleDbCommand com = new OleDbCommand();
//int b = Convert.ToInt32( com.ExecuteScalar());
}
else
{
Response.Redirect("SecondPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" +NIc + "' ";
}
oledcon.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
oledcon.Close();
}
Problem is that you are using ExecuteScalar with wrong query.
string a = (string) comm.ExecuteScalar();
ExecuteScalar() will return single value as a result from query.
Please change your query to the query like blow which return single value from database in place of entire colomn
Select NIC FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1"
Source :http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
I hope it will help you.
Related
I'm using an asp:textarea control to allow the user to input text and then place that text into the body of an e-mail. in the code behind, what is the syntax for adding html tags inside this text area.
For example, For my email i want to have default text to populate the text area. Some of this text is being pulled from my sql server DB.
"Dear [UserName],
The reason your booking was cancelled is because [Reason]
Kind Regards,
[LoggedIn Admin]"
The example above is the template i want to set. The [] indicate where i want to populate from my db.
So far i have been able to enter in the UserName but i cant seem to get a tag to create a space to format the text properly.
The code below is what i have so far and the commented out lines are my attempts.
Id appreciate any help, Thanks
private void GetSelectedBooking()
{
//Database connection setup
string strConnString = ConfigurationManager.ConnectionStrings["BookingDb"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
//Populate form with Booking Details for logged in user
BookingId += Session["BookingId"];
try
{
con.Open();
SqlCommand comm = new SqlCommand();
//preparing a query which will select all properties matching the User that is logged in at that moment
comm.CommandText = (#"select bd.BookingId, ud.Name, bd.Date, bd.StartTime, bd.EndTime ,bd.MemberType, bd.PitchSection, bd.Description ,bd.AmountPaid , ud.Email
from dbo.BookingDetails bd
join UserDetail ud
on ud.UserId = bd.UserId
where BookingId ='" + Session["BookingId"] + "'");
comm.Connection = con;
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Booking.Text = BookingId;
to.Text = rd["Email"].ToString();
subject.Text = "Your Booking Has been Cancelled";
string Name = rd["Name"].ToString();
body.Text = "Dear " + Name.Trim() + "" +", reason";
//Literal ltrl = new Literal();
//ltrl.Text = "<BR />";
//body.Text = "Dear" + ltrl + Name + "reason";
//Literal ltrl2 = new Literal();
// body.Text = "<Description=" + rd["Name"].ToString() + "'><BR />View Address";
// e.Cell.Controls.Add(ltrl2);
// body.Text = "Dear " + "<BR />" + rd["Name"].ToString() + "' + reason";
// body.Text = "Dear " + "<BR /> " + rd["Name"].ToString() + "'";
}
}
rd.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
Your question is only about Asp.net Webforms and html.
In order to add a line break in a Textarea control, you should use \n.
You can use a multi line string if you want to. To render a multi line string in C#, you use the # sign, like this:
void Main()
{
var message = #"Dear [UserName],
The reason your booking was cancelled is because [Reason]
Kind Regards,
[LoggedIn Admin]";
var dictionary = new Dictionary<string, string>();
dictionary.Add("UserName", "johndoe");
dictionary.Add("Reason", "you already have another booking for the same day.");
dictionary.Add("LoggedIn Admin", "Booking Staff");
foreach (var entry in dictionary.Keys)
{
message = message.Replace(string.Format("[{0}]", entry), dictionary[entry]);
}
// You Should now assign the message variable to the textarea.text
// textarea.Text = message;
Console.WriteLine(message);
}
A better approach would be if you not build the text programmatically, but instead read it from a file or a database.
Hope this helps,
I went with this solution
https://social.msdn.microsoft.com/Forums/en-US/47af2197-26b4-4b9e-90e8-bfa9d5cd05b4/what-is-the-deference-between-r-n-and-rn-?forum=csharplanguage
it uses /r/n to create the new line i need. so now i have:
to.Text = rd["Email"].ToString();
subject.Text = "Your Booking Has been Cancelled";
string Name = rd["Name"].ToString();
body.Text = "Dear " + Name.Trim() + "" +", reason" + "\r\n" + "new line test" + "\r\n" + "hi" ;
This outputs:
Dear [UserName], reason
new line test
hi
this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();
string checkuserQuery = "select username from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand usercom = new SqlCommand(checkuserQuery, conn);
string user1 = string.Empty;
Object val = usercom.ExecuteScalar();
if (val != null)
{
user1 = val.ToString();
if (user1 == TextBox1.Text)
{
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand passcom = new SqlCommand(checkpasswordQuery, conn);
string password = passcom.ExecuteScalar().ToString();
if (password == TextBox2.Text)
{
Session["New"] = TextBox1.Text;
Label5.Text = "password is correct";
Response.Redirect("user.aspx");
}
else
{
Label5.Text = "password is not correct";
}
}
}
else
{
Label5.Text = "val is null";
}
}
ExecuteScalar() will return null if the query doesn't return a value.
Returns the first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty.
Source
This line will throw a null reference exception:
passcom.ExecuteScalar().ToString();
Building queries using string concatenation is error prone. More importantly, it is vulnerable to SQL injection. The code suggests that passwords are stored in the database in plain text.
SQL injection and plain text passwords are a serious concern for any application. Parameterize your queries (it is very easy with ADO.Net) and hash your passwords.
The lack of a match is probably caused by the following line:
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
Note the extra spaces added in the string concatenation. Whatever is in TextBox1 will be preceded/followed by whitespace, causing the match to fail.
the problem could be the space characters in the following (i have put a * where space
is incorrectly used)
where Username='*" + TextBox1.Text + "*' "
So the above will mean that your query is trying to get a user name that has
a space character in start and at the end, so just remove those spaces
another point is, such query should be used with parameters as it is prone to
SQL injection type of attacks
I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct
I have problem with my SqlCommand everything I open the page I get the error:
System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.
I cannot find the problem because 'Van' is only found once in the entire project, and in the title..
This is my code in the Page_Load:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
}
The database connectionstring is correct because it works for all my other pages.. i'm trying to get the department where an employee works so he/she can only view memo's from their own department.
You need to close the parentheses after the last name provided.
SELECT (SELECT Memo_ID, Dep_Name FROM Department
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )
Here is what it should look like:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
You need to quote the last name. You probably want to convert to a parameterized query too.
I'd have expected your WHERE clause to wrap the User.Identity.Name in quotes:
WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...
Could "van" be in the username?
This isn't a very secure query either - but SQL injection's another issue!