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;
}
Related
I am able to get access token for SharePoint from accounts.accesscontrol.windows.net while I am running my application on a machine which is allowed to connect to external URL.
But when I am running my application on an environment where I can only go via a proxy server, its giving me 401: Permission denied (connect failed) even through I have added the proxy code. I am given a ProxyServer URL and port; its of type http.
Please find my code for direct hit below. This is working absolutely fine in open env:
private String getToken(String tenant_id,String client_id, String client_secret, String domain)
{
String resultToken=null;
try {
// AccessToken url
String wsURL = "https://accounts.accesscontrol.windows.net/"+ tenant_id+"/tokens/OAuth/2";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Set header
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
String jsonParam = "grant_type=client_credentials"
+ "&client_id="+client_id+"#"+tenant_id
+ "&client_secret="+client_secret
+ "&resource=00000003-0000-0ff1-ce00-000000000000/" +domain+".com#"+tenant_id;
System.out.println("TokenRequestString : " + jsonParam);
// Send Request
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(jsonParam);
wr.flush();
wr.close();
// Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String responseString = "";
String outputString = "";
// Write response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
// Extracting accessToken from string, here response
// (outputString)is a Json format string
if (outputString.indexOf("access_token\":\"") > -1) {
int i1 = outputString.indexOf("access_token\":\"");
String str1 = outputString.substring(i1 + 15);
int i2 = str1.indexOf("\"}");
String str2 = str1.substring(0, i2);
accessToken = str2;
}
} catch (Exception e) {
accessToken = "Error: " + e.getMessage();
}
return accessToken;
}
Below is my code where I am trying to achieve the same thing through proxy server. This is throwing Permission Denied (401)
private String getToken(String tenant_id,String client_id, String client_secret, String domain)
{
String resultToken=null;
try {
// AccessToken url
String wsURL = "https://accounts.accesscontrol.windows.net/"+ tenant_id+"/tokens/OAuth/2";
URL url = new URL(wsURL);
// via Proxy
Proxy webProxy
= new Proxy(Proxy.Type.HTTP, new InetSocketAddress("internet.xyz.com", 83);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(webProxy);
// Set header
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
String jsonParam = "grant_type=client_credentials"
+ "&client_id="+client_id+"#"+tenant_id
+ "&client_secret="+client_secret
+ "&resource=00000003-0000-0ff1-ce00-000000000000/" +domain+".com#"+tenant_id;
System.out.println("TokenRequestString : " + jsonParam);
// Send Request
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(jsonParam);
wr.flush();
wr.close();
// Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String responseString = "";
String outputString = "";
// Write response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
// Extracting accessToken from string, here response
// (outputString)is a Json format string
if (outputString.indexOf("access_token\":\"") > -1) {
int i1 = outputString.indexOf("access_token\":\"");
String str1 = outputString.substring(i1 + 15);
int i2 = str1.indexOf("\"}");
String str2 = str1.substring(0, i2);
accessToken = str2;
}
} catch (Exception e) {
accessToken = "Error: " + e.getMessage();
}
return accessToken;
}
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"
;
I'm new to this. The example of android is from
GetStartedFirebase
Below are the steps:
1) I install the android to my phone
2) I followed this example to create my web api
https//learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-aspnet-backend-gcm-android-push-to-user-google-notification
3) i comment out the AuthenticationTestHandler class
4)i call the below code from fiddle
The DeviceRegistration object
{
"Platform": "gcm",
"Handle": "regid i get from android",
"Tags": [
"1",
"2"
]
}
// This creates or updates a registration (with provided channelURI) at the specified id
public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
{
RegistrationDescription registration = null;
switch (deviceUpdate.Platform)
{
case "mpns":
registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
break;
case "wns":
registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
break;
case "apns":
registration = new AppleRegistrationDescription(deviceUpdate.Handle);
break;
case "gcm":
registration = new GcmRegistrationDescription(deviceUpdate.Handle);
break;
default:
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
registration.RegistrationId = id;
var username = "test";
string[] userTag = new string[1];
userTag[0] = "username:" + username;
registration.Tags = new HashSet<string>(userTag);
try
{
await hub.CreateOrUpdateRegistrationAsync(registration);
}
catch (MessagingException e)
{
ReturnGoneIfHubResponseIsGone(e);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
5) Then i call to send the push notification
http://localhost:4486/api/Notifications?pns=gcm&to_tag=test
public async Task<HttpResponseMessage> Post(string pns, [FromBody]string message, string to_tag)
{
var user = "test";
message = "msg";
string[] userTag = new string[1];
userTag[0] = "username:" + to_tag;
Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
HttpStatusCode ret = HttpStatusCode.InternalServerError;
switch (pns.ToLower())
{
case "wns":
// Windows 8.1 / Windows Phone 8.1
var toast = #"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
"From " + user + ": " + message + "</text></binding></visual></toast>";
outcome = await Notifications.Instance.Hub.SendWindowsNativeNotificationAsync(toast, userTag);
break;
case "apns":
// iOS
var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + message + "\"}}";
outcome = await Notifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, userTag);
break;
case "gcm":
// Android
var notif = "{ \"data\" : {\"message\":\"" + "From " + user + ": " + message + "\"}}";
outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif, userTag);
break;
}
if (outcome != null)
{
if (!((outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Abandoned) ||
(outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Unknown)))
{
ret = HttpStatusCode.OK;
}
}
return Request.CreateResponse(ret);
}
No error returned but i do not receive any notification.
I try to remove usertag as below:
outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif);
I am able to receive the notification.
Why the tag doesn't work ?
Any help appreciated.
var allRegistrations = await Notifications.Instance.Hub.GetAllRegistrationsAsync(0);
Check your tag in allRegistrations. If it is there then it should work.
You can check test notification from http://pushtry.com
I'm confused - JSON from Fiddler shows that the registration has "1" and "2" tags, but everywhere in the code you are using "username:test" tag. Can you get this registration from the hub and make sure that it has correct tags?
You can use GetRegistrationAsync<TRegistrationDescription>(String) [1], GetRegistrationsByChannelAsync(String, Int32) [2] or GetAllRegistrationsAsync(Int32) [3] methods to get the registration.
[1] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationAsync__1_System_String_
[2] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationsByChannelAsync_System_String_System_Int32_
[3] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetAllRegistrationsAsync_System_Int32_
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)
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