Need to find ID number from database using string in c# - c#

I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}

Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp

As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";

Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";

Related

C# ODBC mysql (null output)

can anyone help me? i am getting null output. though data exists in database.
string retrivenp = "select emp_email from E_details where emp_ID ='" + c_c +
"'AND emp_name = '" + s_s + "'AND emp_address = '" + n_n +
"'AND Date_joining = '" + Calendar1.SelectedDate + "'";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.ToString();
Label1.Text = url_path.ToString();
}
}
}
i think the string with many quotes is the problem when it will be executed it may give the wrong query
use command parameters it's better
string retrivenp = "select emp_email from E_details where emp_ID = ? AND emp_name = ? AND emp_address = ? AND Date_joining = ?";
using (OdbcCommand comm1 = new OdbcCommand(retrivenp,con))
{
comm1.Parameters.Add("#p1", OleDbType.Int).Value = c_c;
comm1.Parameters.Add("#p2", OleDbType.Text).Value = s_s;
comm1.Parameters.Add("#p3", OleDbType.Text).Value = n_n;
comm1.Parameters.Add("#p4", OleDbType.Date).Value = Calendar1.SelectedDate;
using (OdbcDataReader read = comm1.ExecuteReader())
{
while(read.Read())
{
url_path = read.GetString(0);
Label1.Text = url_path.ToString();
}
read.Close();
}
}

How to do if/else statement for fileUpload

Heyy all. I am trying to do an if/else statement for my fileupload function on my Edit Profile page in my ASP.net webpage.
Here is my code:
protected void btnContinue_Click(object sender, EventArgs e)
{
//Declaration of variable to update Profile Image
string imageName, newContact;
imageName = FileUpload1.FileName.ToString();
newContact = tbMobile.Text.ToString();
username = (String)Session["NonAdmin"];
MySqlConnection mcon = new MySqlConnection("server=182.50.133.91;user id=Jonathan;password=jon123;persistsecurityinfo=True;database=ajactrac_;allowuservariables=True");
MySqlDataAdapter sda = new MySqlDataAdapter("select * from pointofcontact where Username = '" + username.ToString() + "'", mcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
MySqlCommand command = mcon.CreateCommand();
MySqlCommand command1 = mcon.CreateCommand();
MySqlCommand command2 = mcon.CreateCommand();
MySqlCommand command3 = mcon.CreateCommand();
MySqlCommand command4 = mcon.CreateCommand();
MySqlCommand command5 = mcon.CreateCommand();
MySqlCommand command6 = mcon.CreateCommand();
MySqlCommand command7 = mcon.CreateCommand();
command.CommandText = "update pointofcontact set Password = ?pwd where Username = '" + username.ToString() + "'";
command1.CommandText = "update pointofcontact set FirstName = ?firstname where Username = '" + username.ToString() + "'";
command2.CommandText = "update pointofcontact set LastName = ?lastname where Username = '" + username.ToString() + "'";
command3.CommandText = "update pointofcontact set ContactNumber = ?contact where Username = '" + username.ToString() + "'";
command4.CommandText = "update pointofcontact set EmailAddress = ?email where Username = '" + username.ToString() + "'";
command5.CommandText = "update pointofcontact set Address = ?address where Username = '" + username.ToString() + "'";
command6.CommandText = "update pointofcontact set BackupContactNumber = ?backupnumber where Username = '" + username.ToString() + "'";
command7.CommandText = "update pointofcontact set ProfilePic = ?newimage where Username = '" + username.ToString() + "'";
mcon.Open();
if (tbNewPassword.Text == "")
{
command.Parameters.AddWithValue("?pwd", tbOldPassword.Text.Trim());
}
else
{
command.Parameters.AddWithValue("?pwd", tbNewPassword.Text.Trim());
}
if(tbNewFirstName.Text == "")
{
command1.Parameters.AddWithValue("?firstname", tbFirstName.Text.Trim());
}
else
{
command1.Parameters.AddWithValue("?firstname", tbNewFirstName.Text.Trim());
}
if(tbNewLastName.Text == "")
{
command2.Parameters.AddWithValue("?lastname", tbLastName.Text.Trim());
}
else
{
command2.Parameters.AddWithValue("?lastname", tbNewLastName.Text.Trim());
}
if(tbNewContact.Text == "")
{
command3.Parameters.AddWithValue("?contact", tbMobile.Text.Trim());
}
else
{
command3.Parameters.AddWithValue("?contact", tbNewContact.Text.Trim());
}
if(tbNewEmail.Text == "")
{
command4.Parameters.AddWithValue("?email", tbEmail.Text.Trim());
}
else
{
command4.Parameters.AddWithValue("?email", tbNewEmail.Text.Trim());
}
if(tbNewAddress.Text == "")
{
command5.Parameters.AddWithValue("?address", tbAddress.Text.Trim());
}
else
{
command5.Parameters.AddWithValue("?address", tbNewAddress.Text.Trim());
}
if(tbNewBackupContact.Text == "")
{
command6.Parameters.AddWithValue("?backupnumber", tbBackupContact.Text.Trim());
}
else
{
command6.Parameters.AddWithValue("?backupnumber", tbNewBackupContact.Text.Trim());
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + imageName);
command7.Parameters.AddWithValue("?newimage", imageName);
command.ExecuteNonQuery();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command4.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
command7.ExecuteNonQuery();
mcon.Close();
string javaScript = "<script language=JavaScript>\n" + "alert('Profile Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
else
{
string javaScript = "<script language=JavaScript>\n" + "alert('Some Error Occured! Profile Not Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
tbNewPassword.Text = "";
}
I had planned to use the if else statement for my fileupload function such that if the user has not uploaded a new picture, he/she would be still able to update their profile.
Currently when I try to edit a user's profile, this error message comes out.
Before uploading files to any directory, it is good to have this statement before saving file.
if (!Directory.Exists(Server.MapPath("~/Images")))
Directory.CreateDirectory("~/Images");
add above statement before this line
FileUpload1.PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Images", imageName)));

How to achieve a search for a certain year & amount using C#

Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.

Data gets Truncated from database

I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.

How to return more than a string from a webservice?

I have made webservice in asp.net using C# and MySQL. I want to return multiple values from this service. I am using the following code:
[WebMethod]
public string RegisterUserViaFacebook(string fbid, string fbmailid,string devicetype)
{
string success = "Already Registered";
string id="", name="";
if (!ExistsFBID(fbid))
{
name = GenerateUserName();
string password = generatePassword(10);
string insertUser = "Insert into tbl_userinfo(UserName,Password,Facebook_ID,Facebook_EmailID,DeviceType) values";
insertUser += "( '" + name + "' ,'" + password + "','" + fbid + "','" + fbmailid + "','" + devicetype + "' )";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(insertUser, con);
success = cmd.ExecuteNonQuery().ToString();
con.Close();
string getID = "SELECT UserID from tbl_userinfo where UserName='" + name + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand(getID, con);
id = cmd1.ExecuteScalar().ToString();
con.Close();
if (Convert.ToInt16(success) > 0)
{
SendMail(fbmailid, name, password);
success = "New User" ;
}
else
success = "Error in Insertion";
}
else
{
string getID1 = "SELECT UserID, UserName from tbl_userinfo where Facebook_ID='" + fbid + "' ";
con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd2 = new MySqlCommand(getID1, con);
MySqlDataReader info = cmd2.ExecuteReader();
while (info.Read())
{
id = info.GetString(0);
name = info.GetString(1);
}
con.Close();
}
string jsonString = JsonConvert.SerializeObject(success);
String finalString = "{\"USER IS\":";
finalString += jsonString;
finalString += "}";
string jsonString1 = JsonConvert.SerializeObject(id);
String finalString1 =finalString + "{\"ID IS\":";
finalString1 += jsonString1;
finalString1 += "}" ;
string jsonString2 = JsonConvert.SerializeObject(name);
String finalString2 = finalString1 + "{\"NAME IS\":";
finalString2 += jsonString2;
finalString2 += "}";
return finalString2;
}
But it returns all values in single string. I want to return the values individually as Succeess, ID and Name.
How can I do this?
Create a simple class to hold Succeess, id and name and return an serialized instance of it.
public class RegistrationResult
{
public string Success { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
You could do this:
var result = new RegistrationResult { Success = success, Name = name, Id = id} ;
return JsonConvert.SerializeObject(success);
You probably want to return a singel object in the JSON.
return "{user: "+JsonConvert.SerializeObject(success)+", id: "+JsonConvert.SerializeObject(id)+", name: "+JsonConvert.SerializeObject(name)+"}";
The answer by Oded is fine too. It's a bit more clear, but also needs an extra class.

Categories

Resources