Conversion failed when converting the varchar value to data type - sql-server-2008-r2

i search a lot but didn't find what i want this question is ask by many users here but i didn't find my solution so i ask this question.
i have page in which i have Assign and withdraw button which
is used to Assign and withdraw device id for the selected group
id (group id fetch from dropdownlist) from one list-box to another
that part is completed
Now when i add another device id for the same group id i need to
append that updated record and show it in listbox2.
here is my code:
string queryString1 = "select device_id from device_group_master where group_id='" + ddlGroupName.SelectedValue.ToString() +"'";
SqlDataAdapter newdataAdapter = new SqlDataAdapter(queryString1, con);
SqlCommandBuilder newcommandBuilder = new SqlCommandBuilder(newdataAdapter);
newdataAdapter.Fill(ds1, "table");
if (ds1.Tables["table"].Rows.Count != 0)
{
if (ds1.Tables["table"].Rows[0][0].ToString() == "0")
{
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + device.ToString() + "', NOT_EXCLUDE_DEVICE_ID='" + enable + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
else
{
string append;
append = ds1.Tables["table"].Rows[0][0].ToString();
append += ","+ device;
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + append.ToString() + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
}

Related

Query always returns false in Sqlite Android

I want to check the username and password with sqlite table,In my case query always returns false...
This is my Query...
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
if (c!=null)
{
return true;
}
else{
return false;
}
}
Checking whether or not the Cursor is null is basically useless as a valid Cursor will be returned by rawQuery. That is no data to extract will result in an empty Cursor with no rows, whilst if data has been extracted the Cursor will have 1 or more rows.
You should check whether or not the Cursor is empty by using the Cursor getCount() method which will return 0 if there are no rows or the number of rows. Alternately you could use some of the Cursor's move methods which will return true/false depending upon whether the move can be performed. e.g if (c.moveToFirst) { ... //row(s) exist} else { ... //no rows exists }.
You should also close the Cursor before returning. So perhaps use :-
public boolean validateUser(String u_name, String p_word){
Cursor c = getReadableDatabase().rawQuery(
"SELECT FNAME,PASSWORD FROM " + TABLE_NAME + " WHERE "
+ fname + "='" + u_name+"'AND "+ password +"='"+ p_word+"'" , null);
int count = c.getCount(); // get the number of rows
c.close(); // Close the Cursor
return count > 0; // return result (no data found = false, else true)
Many would recommend not using rawQuery but rather the convenience Cursor query method. This could be :-
public boolean validateUser(String u_name, String p_word) {
String[] columns = new String[]{
FNAME,
PASSWORD
};
String whereclause = FNAME + "=? AND " + PASSWORD + "=?";
String[] whereargs = new String[]{
u_name,
p_word
};
Cursor c = this.getWritableDatabase().query(
TABLE_NAME,
columns,
whereclause,
whereargs,
null,null,null
);
int count = c.getCount();
c.close();
return count > 0;
}
Note the above code is in-principle code and hasn't been tested so it may contain typing errors.
The above code assumes that the method is within the Database Helper class (i.e. a subclass of SQLiteOpenHelper).
The assumption has been made that FNAME and PASSWORD are the correct String variables to be used for the column names as opposed to fname and password
Assumptions have been made due to the limited code made available.

How to create a derby user

I tried to set the DB schema name by schema.xml but it caused a schema name duplication in the generated SQL statement for ID generators. (Duplicate schema name in sequece generation)
I read the schema is defined by the passed user at connection time. Now I would like to set the schema by this way.
But I don't know how can I create a new Derby user and link it with the desired schema. Can somebody help me?
Environment: NetBeans, Glassfish, Derby
I have found this:
CALL SYSCS_UTIL.SYSCS_CREATE_USER('username', 'password')
But Derby answers:
Error code -1, SQL state 42Y03: 'SYSCS_UTIL.SYSCS_CREATE_USER' is not recognized as a function or procedure.
Why? I have connected to the db as the default admin user.
Or if I try to dispatch this command from a GUI tool, Derby says:
[Error Code: 0, SQL State: 42Y07] : Schema 'SYSCS_UTIL' does not exist
To Create user in Derby :
I am using Command Line Interface and I have already set my System environment variable to Derby.
Otherwise you can write these command into your CLI
java -jar %DERBY_HOME%\lib\derbyrun.jar ij
and hit Enter key to run ij tool, and you will see a prompt like this:
ij>
Now type the following command to create a user (replace sam by the desired username and sampass by the desired password):
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.user.sam','sampass');
Now hit enter. This should give a message like this:
0 rows inserted/updated/deleted.
here is a solution (heavily commented):
String setProperty = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(";
String getProperty = "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(";
String requireAuth = "'derby.connection.requireAuthentication'";
String sqlAuthorization = "'derby.database.sqlAuthorization'";
String defaultConnMode = "'derby.database.defaultConnectionMode'";
String fullAccessUsers = "'derby.database.fullAccessUsers'";
String readOnlyAccessUsers = "'derby.database.readOnlyAccessUsers'";
String provider = "'derby.authentication.provider'";
String propertiesOnly = "'derby.database.propertiesOnly'";
System.out.println("Turning on authentication and SQL authorization.");
Statement s = conn.createStatement();
// Set requireAuthentication
s.executeUpdate(setProperty + requireAuth + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.connection.requireAuthentication','true'
// Set sqlAuthorization
s.executeUpdate(setProperty + sqlAuthorization + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.sqlAuthentication','true'
// Retrieve and display property values
ResultSet rs = s.executeQuery(getProperty + requireAuth + ")");
rs.next();
System.out.println("Value of requireAuthentication is " + rs.getString(1));
rs = s.executeQuery(getProperty + sqlAuthorization + ")");
rs.next();
System.out.println("Value of sqlAuthorization is " + rs.getString(1));
// Set authentication scheme to Derby builtin
s.executeUpdate(setProperty + provider + ", 'BUILTIN')");
// Create some sample users
s.executeUpdate(setProperty + "'derby.user." + txtUname.getText() + "', '" + txtPw1.getText() + "')" );
// Define noAccess as default connection mode
s.executeUpdate(setProperty + defaultConnMode + ", 'noAccess')");
// Confirm default connection mode
rs = s.executeQuery(getProperty + defaultConnMode + ")");
rs.next();
System.out.println("Value of defaultConnectionMode is " + rs.getString(1));
// Define read-write users
s.executeUpdate(setProperty + fullAccessUsers + ", '" + txtUname.getText() + "')");
// Define read-only user
// s.executeUpdate(setProperty + readOnlyAccessUsers + ", 'guest')");
// Confirm full-access users
rs = s.executeQuery(getProperty + fullAccessUsers + ")");
rs.next();
System.out.println("Value of fullAccessUsers is " + rs.getString(1));
// Confirm read-only users
rs = s.executeQuery(getProperty + readOnlyAccessUsers + ")");
rs.next();
System.out.println("Value of readOnlyAccessUsers is " + rs.getString(1));
// We would set the following property to TRUE only when we were
// ready to deploy. Setting it to FALSE means that we can always
// override using system properties if we accidentally paint
// ourselves into a corner.
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" + "'derby.database.propertiesOnly', 'false')");
s.close();
Let me know if that works (or not) for you.

Google maps downloadUrl does not return 200

My code is based on the example of google code:
https://developers.google.com/maps/articles/phpsqlinfo_v3
and was working fine.
I need to change a former 'gid' (Integer) field to 'id' (String) to get saved to the database and used to display a new labeled symbol on the map.
The strange thing is, that the url, that is build in the code to call the addrow.php file is OK. When I capture this string with alert(url), and I manually use this string, the new data is added to the database.
In my script, the call seems to fail (responseCode == 200 && data.length <=1), since no data is written to the database and the alert from the 'else-clause' is displayed as short pop-up.
Here's the code I use in my project (to save data from a form):
//save new marker to Postgis-database and add new markerwithlabel on the fly
function saveData(){
var gender = escape(document.getElementById("gender").value);
var hoehe = InZahl(document.getElementById("hoehe").value);
var breite = InZahl(document.getElementById("breite").value);
var id = escape(document.getElementById("id").value);
var vital = document.getElementById("vital").value;
var typ = document.getElementById("typ").value;
var ein_mehr = document.getElementById("ein_mehr").value;
var st_durchm = document.getElementById("st_durchm").value;
var frucht = document.getElementById("frucht").value;
var anmerk = document.getElementById("anmerk").value;
var latlng = marker.getPosition();
var url = "./mapdata/addrow.php?gender=" + gender +
"&hoehe=" + hoehe + "&lat=" + latlng.lat() + "&lng=" + latlng.lng() +
"&breite=" + breite + "&id=" + id + "&typ=" + typ + "&ein_mehr=" +ein_mehr + "&st_durchm=" + st_durchm +
"&frucht=" + frucht +
"&vital=" + vital + "&anmerk=" + anmerk;
downloadUrl(url, function (data, responseCode) {
if (responseCode == 200 && data.length <=1) {
infowindow.close();
marker.setDraggable(false);
marker.setIcon('./images/mm_purple.png');
marker.labelContent = id;
marker.setMap(map);
downloadUrl("./mapdata/getxml_get_last.php", function (data1) {
var xml = parseXml(data1);
var ms = xml.documentElement.getElementsByTagName("m");
var gid = ms[0].getAttribute("gid");
var html_n = "<div id='InfoWindow'><p style='font-weight:bold;'>" + id + "</p> \n\<p>Höhe:" + hoehe + " Breite: "+ breite +
"<br />\n\Typ: "+typ+" Stämme: "+ein_mehr+" St-Durchm: "+ st_durchm + "<br />\n\Vitalität: "+vital+" Fruchtbehang: "+frucht+
"<p/>\n\<p style='text-align:right;'><a href='sm_juniperus.php?operation=ssearch&ResetFilter=0&SearchField=gid&FilterType=%3D&FilterText="+ gid +
"' target='_blank'> Daten editieren </a></p></div>";
infowindow.setContent(html_n);
bindInfoWindow(marker, map, infowindow, html_n);
(function(i, marker, gid) {
var origIcon = marker.getIcon();
new LongPress(marker, 1000);
google.maps.event.addListener(marker, 'longpress', function(e) {
marker.setDraggable(true);
marker.setIcon(mmcross);
});
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker, gid);
marker.setIcon(origIcon);
});
})(i,marker,gid);
//add new marker to markerCluster-Array and to markerArray
markerCluster.addMarker(marker,false);
markerArray.push(marker);
i++;
}); // End add new marker
}
else {
alert("Your data couldn't be saved!");
}
}); // End downloadUrl
}; // END saveData()
As I said, my code worked fine, but after 3 evenings passed to solve this, I thought it would be time to ask for help.
If anybody has an idea, where the mistake lies, I would apreciate any hint.
Just to confirm, you're aware that you by doing
if (responseCode == 200 && data.length <=1) {
you are saying 'if the request is successful and the data it returns is only one character or below in length'? I am unsure if this is intended or not, because this way the code inside the if statement is only ran if the response is successful but contains only 1 or 0 characters.

Create Alias using barclaycard payment epdq - unknown order/1/s/

Below is the code used for creating the Alias which does not work and throw an error
"unknown order/1/s/". The same code works for payment if I remove the code for Alias.
Not sure what am I missing?
I could log into the epdq barclaycard account and see the error which is "unknown order/1/s/". I can also create Alias manually through the epdq account, but just cant get to the orderstandard.asp page without error (when alias hidden fields and code used).
I would be glad if someone could help me.
<body>
<form id="OrderForm" action="https://payments.epdq.co.uk/ncol/prod/orderstandard.asp" method="post" runat="server">
<div>
<asp:HiddenField ID="AMOUNT" runat="server" />
<asp:HiddenField ID="CN" runat="server" />
...
<asp:HiddenField ID="ALIAS" runat="server" />
<asp:HiddenField ID="ALIASUSAGE" runat="server" />
<asp:HiddenField ID="ALIASOPERATION" runat="server" />
<asp:HiddenField ID="SHASign" runat="server" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text; //for Encoding
using System.Security.Cryptography; //for SHA1
public partial class _DefaultAliasTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//-- Set Values (these would be pulled from DB or a previous page). -- //
bool isAlias = true;
//- Customer/Order Details - //
string strUserTitle = "Mr"; // Customer details
string strUserFirstname = "Edward";
string strUserSurname = "Shopper";
string strBillHouseNumber = "123"; // Address Details
string strAd1 = "Penny Lane";
string strAd2 = "Central Areas";
string strBillTown = "Middlehampton"; // Bill Town
string strBillCountry = "England"; // Bill Country
string strPcde = "NN4 7SG"; // Postcode
string strContactTel = "01604 567 890"; // Contact Telephone number
string strShopperEmail = "test#test.com"; // shopper Email
string strShopperLocale = "en_GB"; // shopper locale
string strCurrencyCode = "GBP"; // CurrecncyCode
string strAddressline1n2 = strBillHouseNumber + " " + strAd1 + ", " + strAd2; // Concatenated Address eg 123 Penny Lane Central Areas
string strCustomerName = strUserTitle + " " + strUserFirstname + " " + strUserSurname; // Concatenated Customer Name eg Mr Edward Shopper
string strPaymentAmount = "100"; // This is 1 pound (100p)
string strOrderDataRaw = "HDTV - AVTV3000"; // Order description
string strOrderID = "ORD1234556Y"; // Order Id - **needs to be unique**
//- integration user details - //
string strPW = "xxxxxx!?"; // Update with the details you entered into back office
string strPSPID = "epdqxxxxxxx"; // update with the details of the PSPID you were supplied with
//- payment design options - '//
string strTXTCOLOR = "#005588"; // Page Text Colour
string strTBLTXTCOLOR = "#005588"; // Table Text Colour
string strFONTTYPE = "Helvetica, Arial"; // fonttype
string strBUTTONTXTCOLOR = "#005588"; // Button Text Colour
string strBGCOLOR = "#d1ecf3"; // Page Background Colour
string strTBLBGCOLOR = "#ffffff"; // Table BG Colour
string strBUTTONBGCOLOR = "#cccccc"; // Button Colour
string strTITLE = "Testing - Secure Payment Page"; // Title
string strLOGO = "https://www.site.com/logo.png"; // logo location
string strPMLISTTYPE = "1"; // Payment Method List type
string strALIAS = System.Guid.NewGuid().ToString();
string strALIASUSAGE = "usage"; // ALIAS USAGE
string strALIASOPERATION = "BYMERCHANT"; // ALIAS Operation
//= create string to hash (digest) using values of options/details above. MUST be in field alphabetical order!
string plainDigest =
"AMOUNT=" + strPaymentAmount + strPW +
"BGCOLOR=" + strBGCOLOR + strPW +
"BUTTONBGCOLOR=" + strBUTTONBGCOLOR + strPW +
"BUTTONTXTCOLOR=" + strBUTTONTXTCOLOR + strPW +
"CN=" + strCustomerName + strPW +
"COM=" + strOrderDataRaw + strPW +
"CURRENCY=" + strCurrencyCode + strPW +
"EMAIL=" + strShopperEmail + strPW +
"FONTTYPE=" + strFONTTYPE + strPW +
"LANGUAGE=" + strShopperLocale + strPW +
"LOGO=" + strLOGO + strPW +
"ORDERID=" + strOrderID + strPW +
"OWNERADDRESS=" + strAddressline1n2 + strPW +
"OWNERCTY=" + strBillCountry + strPW +
"OWNERTELNO=" + strContactTel + strPW +
"OWNERTOWN=" + strBillTown + strPW +
"OWNERZIP=" + strPcde + strPW +
"PMLISTTYPE=" + strPMLISTTYPE + strPW +
"PSPID=" + strPSPID + strPW +
"TBLBGCOLOR=" + strTBLBGCOLOR + strPW +
"TBLTXTCOLOR=" + strTBLTXTCOLOR + strPW +
"TITLE=" + strTITLE + strPW +
"TXTCOLOR=" + strTXTCOLOR + strPW +
"";
if (isAlias)
{
plainDigest =
plainDigest +
"ALIAS=" + strALIAS + strPW +
"ALIASUSAGE=" + strALIASUSAGE + strPW +
"ALIASOPERATION=" + strALIASOPERATION + strPW +
"";
}
//Payment
//-- insert payment details into hidden fields -- //
AMOUNT.Value = strPaymentAmount; // PaymentAmmount : (100 pence)
CN.Value = strCustomerName; // Customer Name
COM.Value = strOrderDataRaw; // OrderDataRaw (order description)
CURRENCY.Value = strCurrencyCode; // CurrecncyCode
EMAIL.Value = strShopperEmail; // shopper Email
FONTTYPE.Value = strFONTTYPE; // fonttype
LANGUAGE.Value = strShopperLocale; // shopper locale
LOGO.Value = strLOGO; // logo location
ORDERID.Value = strOrderID; // *this ORDER ID*
OWNERADDRESS.Value = strAddressline1n2; // AddressLine2
OWNERCTY.Value = strBillCountry; // Bill Country
OWNERTELNO.Value = strContactTel; // Contact Telephone number
OWNERTOWN.Value = strBillTown; // Bill Town
OWNERZIP.Value = strPcde; // Postcode
PMLISTTYPE.Value = strPMLISTTYPE; // Payment Method List type
PSPID.Value = strPSPID; // *Your PSPID*
BGCOLOR.Value = strBGCOLOR; // Page Background Colour
BUTTONBGCOLOR.Value = strBUTTONBGCOLOR; // Button Colour
BUTTONTXTCOLOR.Value = strBUTTONTXTCOLOR; // Button Text Colour
TBLBGCOLOR.Value = strTBLBGCOLOR; // Table BG Colour
TBLTXTCOLOR.Value = strTBLTXTCOLOR; // Table Text Colour
TITLE.Value = strTITLE; // Title
TXTCOLOR.Value = strTXTCOLOR; // Page Text Colour
if (isAlias)
{
ALIAS.Value = strALIAS;
ALIASUSAGE.Value = strALIASUSAGE;
ALIASOPERATION.Value = strALIASOPERATION;
}
SHASign.Value = SHA1HashData(plainDigest); // Hashed String of plain digest put into sha sign using SHA1HashData function
}
}
I found the answer to my question via customer service to Barclaycard epdq. I hope this helps others. For me the answer is the point selected in bold below.
Please see below details on how to rectify the error ‘unknown order/1/s/’:
This error indicates that ePDQ has been unable to decrypt the SHASIGN HTML Form value sent with the customer when you redirect them from your website to the ePDQ Hosted Payment Page.
The typical reasons for this error are:
• The SHA-IN Passphrase value configured in the ePDQ back office does not match the value you used to encrypt the transaction data used to create the SHASIGN parameter (please also ensure you are sending transactions to the correct ePDQ environment – TEST or PRODUCTION)
• You have not arranged the parameters in alphabetical order when calculating the SHASIGN in your server-side code
• You have not correctly declared some of the parameters – all parameters and values are case sensitive (all parameter names must be upper case)
• You have set a HASH ALGORITHM value that is different to the SHA method used in your server side script (for example, you have configured SHA-256 in the ePDQ Back Office Technical Information settings, but are using a SHA-1 method in your encryption process).
• You have passed additional parameter/value pairs in the HTML Form that have not been included in the SHA-IN calculation
For more information please refer to the Basic & Advanced e-Commerce integration guides located in the ePDQ Back Office under Support –> Integration & User Manuals.

Can I send SSRS custom subscription e-mails?

I need to send some e-mails containing a SSRS report to a list of persons, representing the amount of work items they have left until a certain date.
What I would like to do is to send each person in the list, the customized report that reflects his progress, so my question is: can I send different reports to the persons in the list (like sending it's e-mail address as a parameter to the report), or can I only send the same report to all people in the list?
Thanks!
If you do not have enterprise (to utilize data driven subscription as #StephLocke mentioned), you can programmatically generate SSRS subscriptions using the SSRS web service.
Your code would look something like this (SubscriptionRequest is a custom class I use, its properties should be intuitive):
static void generateSubscription()
{
if (SubscriptionRequests.Count < 1) return;
NetworkCredential credentials = new NetworkCredential("user", "pass");
reports.ReportingService2005 rs = new reports.ReportingService2005();
rs.Credentials = credentials;
DateTime topDatetime = DateTime.Now;
topDatetime = topDatetime.AddMinutes(2);
foreach (SubscriptionRequest x in SubscriptionRequests)
{
reports.ExtensionSettings extensionSettings = new reports.ExtensionSettings();
List<reports.ParameterValue> extParameters = new List<reports.ParameterValue>();
List<reports.ParameterValue> parameters = new List<reports.ParameterValue>();
string description = "Email: ";
string eventType = "TimedSubscription";
extensionSettings.Extension = "Report Server Email";
string scheduleXml = "<ScheduleDefinition><StartDateTime>";
scheduleXml += topDatetime.ToShortDateString() + " " + topDatetime.ToShortTimeString();
scheduleXml += "</StartDateTime></ScheduleDefinition>";
parameters.Add(new reports.ParameterValue() { Name = "abc", Value = x.id });
extParameters.Add(new reports.ParameterValue() { Name = "RenderFormat", Value = x.renderFormat });
extParameters.Add(new reports.ParameterValue() { Name = "TO", Value = x.email });
extParameters.Add(new reports.ParameterValue() { Name = "ReplyTo", Value = x.replyTo });
extParameters.Add(new reports.ParameterValue() { Name = "IncludeReport", Value = "True" });
extParameters.Add(new reports.ParameterValue() { Name = "Subject", Value = "subject - " + " (" + x.id.ToString() + ")" });
extParameters.Add(new reports.ParameterValue() { Name = "Comment", Value = x.body });
extensionSettings.ParameterValues = extParameters.ToArray();
description += topDatetime.ToShortDateString() + " " + topDatetime.ToShortTimeString();
description += " (" + x.a + " - " + x.b + " - " + x.c + ")";
string _reportName = "/report";
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
topDatetime = topDatetime.AddSeconds(30);
}
}
More examples can be found here.
Yes you can use a data driven subscription to do this. Unfortunately this isn't available to every edition (2008+, enterprise only I believe) so you may not be able to use this functionality.
There are more details available: http://technet.microsoft.com/en-us/library/ms159150.aspx