Fixing my code to prevent sql injection - postgresql

I made a login with authentication in DotNet windows forms app and I'm trying to do my best to guard the database from SQL injection attacks, but it seems like there was a wrong logic in my code. Any help would be appreciated.
/* -UNSAFE command-
sql = #"SELECT employee_no FROM public.tb_userlogin where
username ='" + Convert.ToString(userText.Text) + "' AND password ='" + Convert.ToString(passText.Text) + "'";
*/
conn.Open();
sql = "SELECT employee_no FROM public.tb_userlogin where username = _username AND Decoypass = _password";
EmpNo = code.Converter_string(sql).ToString();
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_username", userText.Text);
cmd.Parameters.AddWithValue("_password", passText.Text);
if (userText.Text == String.Empty || passText.Text == String.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
if (EmpNo != "0")//log in successfully
{
this.Hide();
new ClientCrudFrm().Show();
}
else
{
MessageBox.Show("Please check your username or password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
if (conTable.Rows.Count == 1)
{
MessageBox.Show("login successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message,
"Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
}
`
This is the full code inside the login button:
private void BtnLogin_Click(object sender, EventArgs e) //user login authentication
{
bool userValidated = validateUserInput(userText.Text);
bool passValidated = validateUserInput(passText.Text);
if (userValidated && passValidated)
{
getConnection();
}
try
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost;Database=UserLogin;Username=postgres;Password=adminAdmin1");
NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter();
//NpgsqlDataAdapter conDataAdapter = new NpgsqlDataAdapter("select * from public.tb_userlogin where username='" + userText.Text + "'and password='" + passText.Text + "'", conn);
DataTable conTable = new DataTable();
conDataAdapter.Fill(conTable);
/* -UNSAFE command-
sql = #"SELECT employee_no FROM public.tb_userlogin where
username ='" + Convert.ToString(userText.Text) + "' AND password ='" + Convert.ToString(passText.Text) + "'";
*/
string username = userText.Text;
string password = passText.Text;
conn.Open();
conDataAdapter.SelectCommand = cmd;
cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand("SELECT * FROM public.tb_userlogin where username = $username AND password = $password", conn);
EmpNo = code.Converter_string(sql).ToString();
cmd.Parameters.AddWithValue("$username", userText.Text);
cmd.Parameters.AddWithValue("$username", passText.Text);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (userText.Text == String.Empty || passText.Text == String.Empty)
{
MessageBox.Show("Field cannot be empty!");
}
if (EmpNo != "0")//log in successfully
{
this.Hide();
new ClientCrudFrm().Show();
}
else
{
MessageBox.Show("Please check your username or password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
if (conTable.Rows.Count == 1)
{
MessageBox.Show("login successfully");
}
else
{
MessageBox.Show("Error");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message,
"Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
}
}
with the updated code above, here saying a new error when I log in:
"The SelectCommand property has not been initialized before calling Fill"

From: the Npgsql documentation, use $1, $2, etc. as the placeholders for your parameters, something like this:
sql = "SELECT employee_no"
+ "FROM public.tb_userlogin"
+ "where username = $1"
+ "AND Decoypass = $2"
;

Related

Analysis Services - TMSL - Execute from C#

I looking for a way to execute (what I think is called) TMSL against a Microsoft Analysis Services. I am trying to Process one single table, from a Dot.Net C# application. The JOSN I need to send to the Analysis Service looks something like this:
{
"refresh": {
"type": "full",
"objects": [
{
"database": "BaseName",
"table": "TableName"
}
]
}
}
how do I do? are there something like ado.net that can do the job?
Peter
I found that this works:
StringBuilder qry = new StringBuilder();
qry.Clear();
qry.AppendLine(" ");
qry.AppendLine("{ ");
qry.AppendLine(" \"refresh\": { ");
qry.AppendLine(" \"type\": \"full\", ");
qry.AppendLine(" \"objects\": [ ");
bool AddTegn = false;
foreach (string TableName in TableNames)
{
if (AddTegn)
{
qry.AppendLine(" , ");
}
AddTegn = true;
qry.AppendLine(" { ");
qry.AppendLine(" \"database\": \"" + DataBaseName + "\", ");
qry.AppendLine(" \"table\": \"" + TableName + "\" ");
qry.AppendLine(" } ");
}
qry.AppendLine(" ] ");
qry.AppendLine(" } ");
qry.AppendLine("} ");
AdomdConnection con = "[Connection String]";
con.Open();
AdomdCommand cmd = con.CreateCommand(); //new AdomdCommand(qry.ToString(), con);
cmd.CommandText = qry.ToString();
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
try
{
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (con != null)
{
con.Close();
}
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
con.Dispose();
}
}

How can update contact in existing contact update to postal address

This is my code to existing contact to change the postal address code
ops = new ArrayList<ContentProviderOperation>();
rawContactID = ops.size();
///Insert code are working/////
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,addr)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtcity.getText().toString())
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtpostcode.getText().toString())
enter code here
`enter code here` .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtcountry.getText().toString()).build());
//// I am trying this update record code but not working///
btn_upcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, addr)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, scity)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, scode)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,scountry)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I am update the record coding to btn_upcontacts listner but not working,Please Help me
I am trying the many code use are but not working
I have a simply edit the text andd update to the exsiting contact the postal address without the sqllite datbase
Advance in Thanks
int _contact_id = 10110; // your Conatct id
Uri rawContactUri = null;
Cursor rawContactCursor = null;
try {
// if some fields not available use rawContactUri as ID
rawContactUri = null;
rawContactCursor = context.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts._ID},
ContactsContract.RawContacts.CONTACT_ID + " = " + _contact_id,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rawContactCursor != null) {
rawContactCursor.close();
}
}
Boolean noAddress = true;
Cursor currAddr = null;
try {
Uri URI_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE + " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[]{
String.valueOf(_contact_id),
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
currAddr = context.getContentResolver().query(URI_ADDRESS, null, SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
if (currAddr.getCount() > 0) {
currAddr.moveToFirst();
while (!currAddr.isAfterLast()) {
noAddress = false;
currAddr.moveToNext();
}
} else {
noAddress = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (currAddr != null) {
currAddr.close();
}
}
if (noAddress) {
// address is not available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ContentValues adrsValues = new ContentValues();
adrsValues.put(ContactsContract.Data.RAW_CONTACT_ID, ContentUris.parseId(rawContactUri));
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, "1");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name);
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "");
adrsValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, adrsValues);
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
} else {
// address is already available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where1, AryStructuredAdd1)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "")
.build());
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
}

Select results truncated without error message

I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)

Ado.net Update Command is successful but database is not updated

The following code executes successfully and the return value of cmd.ExecuteNonQuery returns 1 indicating the row was successfully updated but the database is not truly updated. How could that be? I'm using sqlserver2008.
public string updatePost(string id, string head, string body)
{
connection = new SqlConnection(connString);
string cmdStr = "update News set Header = '"+head+"' , [Text] = '"+body+"' where Id = "+int.Parse(id)+"";
string msg = String.Empty;
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdStr, connection);
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:"+id+"' was successfully updated. Rows effected:"+effected+"";
}
catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
finally
{
connection.Close();
}
return msg;
}
Try this, this fixes some problems (like sql-injection), perhaps also your update issue:
public string UpdatePost(string id, string head, string body)
{
string msg = "";
string cmdStr = "update News set Header = #header, [Text] = #body where Id = #id";
using (var con = new SqlConnection(connString))
{
try
{
con.Open();
using (var cmd = new SqlCommand(cmdStr, con))
{
cmd.Parameters.AddWithValue("#header", head);
cmd.Parameters.AddWithValue("#body", body);
cmd.Parameters.AddWithValue("#id", int.Parse(id));
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:" + id + "' was successfully updated. Rows effected:" + effected + "";
}
} catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
}
return msg;
}

excel data uploading is not working in sql database

This is pradeep
This is the code of the excel uploading to sql database
protected void btnupload_Click ( object sender, EventArgs e )
{
//string name = ddloutlet.SelectedValue.ToString ();
//cal
try
{
System.IO.FileInfo file = new System.IO.FileInfo(fileupload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length), file.Extension.Length);
fname = fname + DateTime.Now.ToString("_ddMMyyyy_HHmmss") + file.Extension;
fileupload1.PostedFile.SaveAs(Server.MapPath("locations/") + fname);
string filexetion = file.Extension;
if ( filexetion == ".xlsx" )
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
}
else if ( filexetion == ".xls" )
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes; \"";
}
OleDbConnection connection = new OleDbConnection(excelConnectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
SqlConnection conn = new SqlConnection(strconnection);
conn.Open();
try
{
if (dr.Read() == true)
{
while (dr.Read())
{
string locationname = dr["Location Name"].ToString();
string status = dr["Status"].ToString();
if (locationname != "" && status != "")
{
string query = " select locationname from tbllocations where locationname='" + locationname + "' and outletid='" + Session["outlet_id"].ToString() + "'";
// conn.Open();
SqlCommand cmdquery = new SqlCommand(query, conn);
SqlDataReader drreader;
drreader = cmdquery.ExecuteReader();
if (drreader.Read())
{
c = true;
ssss = ssss + locationname + ",";
// ss = ssss.Split(',');
}
else
{
drreader.Close();
string qryprduct = "insert into tbllocations(locationname,status,outletid,cityid)values('" + locationname + "','" + status + "','" + Session["outlet_id"].ToString() + "','" + Session["cityid"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(qryprduct, conn);
conn.Close();
conn.Open();
cmd1.ExecuteNonQuery();
lblerror1.Visible = true;
lblerror1.Text = "Locations uploaded Sucess";
//conn.Close();
}
drreader.Close();
}
}
// connection.Close (); conn.Close ();
}
else
{
lblerror1.Text = "There is a empty excel sheet file,plz check";
lblerror1.Visible = true;
}
}
catch (Exception ex)
{
lblerror1.Visible = true;
lblerror1.Text = "Plz check the excel file formate";
}
finally
{
connection.Close(); conn.Close();
bind();
if (c == true)
{
lblerror1.Visible = true;
lblerror1.Text = "In excel this loactions are already exist. Please check,";
//for (int i = 0; i < ss.Length; i++)
//{
lblerror3.Visible = true;
lblerror3.Text = ssss;
//}
}
}
}
catch
{
}
}
The above code uploading is working but in excel 1st record is not uploading ,please tell me the what is the problem and give me suggestion please.
excel data is
Location Name Status
test1 1
test2 1
test3 1
test4 0
test5 1
test6 0
test7 1
test8 0
test9 1
test10 1
Thanks
Pradeep
You need to remove the
if (dr.Read() == true)
because it is immediately followed by a
while (dr.Read())
Each of these will read a record and the first one will skip the first row of the file