I've got this line of SQL query to check the validity of a username password :
if exists (select * from Acc where username = :un and userpassword = HASHBYTES('SHA2_256', :pw)) select 1 else select 0
It works correctly when executed directly in SQL Server Management studio but when I bind values and query from Qt it won't work.
What am I doing wrong? I'd appreciate any help. I'll paste the complete code section in Qt below :
q->prepare("if exists (select * from Acc where username = :un and userpassword = HASHBYTES('SHA2_256', :pw)) select 1 else select 0");
q->bindValue(":un", un);
q->bindValue(":pw", pw);
if (q->exec())
{
q->next();
if (q->value(0).toInt() == 0)
{
QMessageBox::critical(this, "", "User not found", QMessageBox::Ok);
}
else
{
//execute form . . .
}
Related
I'm trying to run a report that execute some SQL queries in NAV 2015
If I run the report manually it's working perfectly, but when I set it into the Task Scheduler it give error as it has an automation that is trying to load in the client.
I've changed the CREATE parameters to (FALSE, FALSE) instead of (FALSE, TRUE) so it runs in Server instead of Client, but when I try to compile it will give this error:
Translation: Cannot create an automation object "sqlConnection" in NAV Server. You must create it in Client.
But if I create it in client CREATE(FALSE, TRUE) it will give error:
Translation: NAV Server was trying to return a Client call to create an automation object. Call returns from Client are not allowed in NAV Server.
This is the code: (Looping Company table)
IF (STRPOS(LOWERCASE(Company.Name), 'prueba') = 0) AND (STRPOS(LOWERCASE(Company.Name), 'test') = 0) AND (STRPOS(LOWERCASE(Company.Name), 'uat') = 0) AND (STRPOS(LOWERCASE(Company.Name), 'prova') = 0) THEN BEGIN
recWasteHeader.CHANGECOMPANY(Company.Name);
IF recWasteHeader.COUNT > 0 THEN BEGIN
recWasteLine.SETRANGE("Document Type", 4);
recWasteLine.SETRANGE("Business Type", 2);
recWasteLine.SETFILTER("Sub Contract No.", '<>%1', '*NUL*');
IF recWasteLine.FINDSET THEN BEGIN
IF ISCLEAR(sqlConnection) THEN
CREATE(sqlConnection, FALSE, FALSE);
sqlConnection.Open(ConnectionString);
IF ISCLEAR(sqlCommand) THEN
CREATE(sqlCommand, FALSE, FALSE);
sqlCommand.ActiveConnection := sqlConnection;
sqlCommand.CommandText := 'DELETE FROM [Noc Services Price] WHERE Empresa=' + q + Company.Name + q;
sqlCommand.CommandType := 1;
sqlCommand.Execute;
REPEAT
querydata := STRSUBSTNO(dataset, Company.Name, recWasteLine."Document No.", recWasteLine."Line No.", recWasteLine.Amount);
sqlCommand.CommandText := 'INSERT INTO [Noc Services Price] (Empresa, Contracte, [Linea contracte], [PREU ACTUAL]) VALUES ( ' + querydata + ');';
sqlCommand.Execute;
UNTIL recWasteLine.NEXT = 0;
sqlConnection.Close;
END;
END;
END;
I also can't find the dotnet System.Data.SqlClient
I've been trying to write an update function that takes the user to be updated(usr), the flag which then translates to the field to be updated and the new value. Here's the function,
bool DBManager::updateDB(User* usr, int flag, QVariant& value)
{
QSqlQuery query;
bool status = false;
QString temp_value = "";
QList<QString> fieldlist = {"First_Name", "Last_Name", "Email", "Username", "Password"};
QString field = fieldlist.at(flag);
if (field == "First_Name") {
usr->setFirstName(value.toString());
temp_value = usr->getFirstName();
} else if (field == "Last_Name") {
usr->setLastName(value.toString());
temp_value = usr->getLastName();
} else {
qDebug() << "invalid option";
}
query.prepare("UPADATE Users SET :field = :newValue WHERE Username = :Username");
query.bindValue(":field",field);
query.bindValue(":newValue",temp_value);
query.bindValue(":Username",usr->getUserName());
qDebug() << query.boundValues();
if (m_db.isOpen()){
if (query.exec()){
status = true;
qDebug() << "DATABASE:: Record update successful";
} else {
qDebug() << "DATABASE:: Record update unsuccessful - " << query.lastError();
}
} else {
qDebug() << "DATABASE:: not open ";
}
return status;
}
When I run the code I get an error. Here is the output:
QMap((":Username", QVariant(QString, "zielinkin1"))(":field", QVariant(QString, "Last_Name"))(":newValue", QVariant(QString, "Thibos")))
DATABASE:: Record update unsuccessful - QSqlError("", "Parameter count mismatch", "") User not updated DATABASE:: database closed
How to fix this?
Cause
First problem
It is not hard to guess, that value binding works only for values, not for field names.
For more info, please read about Inserting, Updating, and Deleting Records.
Second problem
Found by #JimCastro:
You have a typo in your query. UPADATE should be UPDATE.
Solution
Use a string concatenation to form your prepared query.
Example
Instead of
query.prepare("UPDATE Users SET :field = :newValue WHERE Username = :Username");
write
query.prepare("UPDATE Users SET " + field + " = :newValue WHERE Username = :Username");
Delete or comment this line
query.bindValue(":field",field);
I use sqlite on a c++ project, but I have a problem when i use WHERE on a column with TEXT values
I created a sqlite database:
CREATE TABLE User( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(24))
When i try to get the value of the column with VARCHAR values, it doesn't work, and return me a STATUS_CODE 101 just after the sqlite3_step :
int res = 0;
sqlite3_stmt *request;
char *sqlSelection = (char *)"SELECT * FROM User WHERE name='bob' ";
int id = 0;
res = sqlite3_prepare_v2(db, sqlSelection, strlen(sqlSelection), &request, NULL);
if (!res){
while (res == SQLITE_OK || res == SQLITE_ROW){
res = sqlite3_step(request);
if (res == SQLITE_OK || res == SQLITE_ROW ){
id = sqlite3_column_int(request, 0);
printf("User exist %i \n",id);
}
}
sqlite3_finalize(request);
I also tried with LIKE but it also doesn't work
SELECT * FROM User WHERE name LIKE '%bob%'
But when I execute the same code but for an INTERGER value
SELECT * FROM User WHERE id=1
It work fine.
In DB Browser for SQLite all requests work fine.
To solve the problem I searched what status code 101 means.
Here is what they said.
(101) SQLITE_DONE
The SQLITE_DONE result code indicates that an operation has completed.
The SQLITE_DONE result code is most commonly seen as a return value
from sqlite3_step() indicating that the SQL statement has run to
completion. But SQLITE_DONE can also be returned by other multi-step
interfaces such as sqlite3_backup_step().
https://sqlite.org/rescode.html
So, you're getting 101 because there is no more result from SELECT SQL.
The solution was to replace the VARCHAR fields by TEXT.
SQLite for c++ seems to don't manage VARCHAR fields when they are used after the WHERE
in Sharepoint 2013 i try to programmatically add a managed metadata column to a list using following code:
Field f = list.Fields.AddFieldAsXml("<Field Type='" + columntype + "' Name='" + columnname + "' DisplayName='" + columnname + "' ShowField='Term1033' />", true, AddFieldOptions.AddFieldToDefaultView);
clientContext.Load(f);
clientContext.ExecuteQuery();
TaxonomyField taxField = clientContext.CastTo<TaxonomyField>(f);
taxField.SspId = this.getDefaultTermStoreId();
taxField.TermSetId = getTermSetIdByName("Instanties");
taxField.AllowMultipleValues = false;
taxField.Open = true;
taxField.TargetTemplate = string.Empty;
taxField.AnchorId = Guid.Empty;
taxField.Update();
list.Update();
clientContext.ExecuteQuery();
The column is created in my list as a managed metadata type column but the termset i want the users to choose from is not filled in in settings. Anyone has a hint to set the TermSet of the managed metadata column?
the getDefaultTermStoreId() and the getTermSetIdByName(string) give me the right GUID; i checked that!
thanks a lot!
We should add
taxField.TargetTemplate = string.Empty;
taxField.AnchorId = Guid.Empty;
and then it works!
Here i am trying to read the list of sharepoint. For this i have done the following:
I have downloaded the WSDL file which i got from The URL like: sharepointsite.com/_vti_bin/Lists.asmx?WSDL.
and i have executed the following command to generate the classes in the directory
“C:\Program Files\Java\jdk1.6.0_12\bin\wsimport.exe” -p com.microsoft.schemas.sharepoint.soap -keep -extension Lists.wsdl.
Imported those classes in my eclipse IDE java application.
and i have written the following code
/* Creates a port connected to the SharePoint Web Service given.
* Authentication is done here. It also prints the authentication details
* in the console.
* #param userName SharePoint username
* #param password SharePoint password
* #return port ListsSoap port, connected with SharePoint
* #throws Exception in case of invalid parameters or connection error.
*/
public static ListsSoap sharePointListsAuth(String userName, String password) throws Exception {
ListsSoap port = null;
if (userName != null && password != null) {
try {
Lists service = new Lists();
port = service.getListsSoap();
System.out.println("Web Service Auth Username: " + userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
} catch (Exception e) {
throw new Exception("Error: " + e.toString());
}
} else {
throw new Exception("Couldn't authenticate: Invalid connection details given.");
}
return port;
}
/**
* Creates a string from an XML file with start and end indicators
* #param docToString document to convert
* #return string of the xml document
*/
public static String xmlToString(Document docToString) {
String returnString = "\n-------------- XML START --------------\n";
try {
//create string from xml tree
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans;
trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult streamResult = new StreamResult(sw);
DOMSource source = new DOMSource(docToString);
trans.transform(source, streamResult);
String xmlString = sw.toString();
//print the XML
returnString = returnString + xmlString;
} catch (TransformerException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
}
returnString = returnString + "-------------- XML END --------------";
return returnString;
}
/**
02
* Connects to a SharePoint Lists Web Service through the given open port,
03
* and reads all the elements of the given list. Only the ID and the given
04
* attributes (column names) are displayed, as well as a dump of the SOAP
05
* response from the Web Service (for debugging purposes).
06
* #param port an already authentificated SharePoint Online SOAP port
07
* #param listName original name of the Sharepoint list that is going to be read
08
* #param listColumnNames arraylist containing the various names of the Columns
09
* of the SharePoint list that are going to be read. If the column name isn't
10
* found, then an exception will be thrown
11
* #param rowLimit limits the number of rows (list items) that are going to
12
* be returned
13
* #throws Exception
14
*/
public static void displaySharePointList(ListsSoap port, String listName, ArrayList<String> listColumnNames, String rowLimit) throws Exception {
if (port != null && listName != null && listColumnNames != null && rowLimit != null) {
try {
//Here are additional parameters that may be set
String viewName = "";
GetListItems.ViewFields viewFields = null;
GetListItems.Query query = null;
GetListItems.QueryOptions queryOptions = null;
String webID = "";
//Calling the List Web Service
GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);
Object listResult = result.getContent().get(0);
if ((listResult != null) && (listResult instanceof ElementNSImpl)) {
ElementNSImpl node = (ElementNSImpl) listResult;
//Dumps the retrieved info in the console
Document document = node.getOwnerDocument();
System.out.println("SharePoint Online Lists Web Service Response:" + Manager.xmlToString(document));
//selects a list of nodes which have z:row elements
NodeList list = node.getElementsByTagName("z:row");
System.out.println("=> " + list.getLength() + " results from SharePoint Online");
//Displaying every result received from SharePoint, with its ID
for (int i = 0; i < list.getLength(); i++) {
//Gets the attributes of the current row/element
NamedNodeMap attributes = list.item(i).getAttributes();
System.out.println("******** Item ID: " + attributes.getNamedItem("ows_ID").getNodeValue()+" ********");
//Displays all the attributes of the list item that correspond to the column names given
for (String columnName : listColumnNames) {
String internalColumnName = "ows_" + columnName;
if (attributes.getNamedItem(internalColumnName) != null) {
System.out.println(columnName + ": " + attributes.getNamedItem(internalColumnName).getNodeValue());
} else {
throw new Exception("Couldn't find the '" + columnName + "' column in the '" + listName + "' list in SharePoint.\n");
}
}
}
} else {
throw new Exception(listName + " list response from SharePoint is either null or corrupt\n");
}
} catch (Exception ex) {
throw new Exception("Exception. See stacktrace." + ex.toString() + "\n");
}
}
}
public static void main(String[] args) {
try {
//Authentication parameters
String userName = "domain\\username";
String password = "pass";
//Opening the SOAP port of the Lists Web Service
ListsSoap port = Manager.sharePointListsAuth(userName, password);
/*
* Lists Web service parameters
* The list names below must be the *original* names of the list.
* if a list or column was renamed from SharePoint afterwards,
* these parameters don't change.
*/
String listName = "listname";
String rowLimit = "2";
ArrayList<String> listColumnNames = new ArrayList<String>();
listColumnNames.add("Name");
listColumnNames.add("ID");
//Displays the lists items in the console
Manager.displaySharePointList(port, listName, listColumnNames, rowLimit);
} catch (Exception ex) {
System.err.println(ex);
}
}
I am getting following exception :
Web Service Auth Username: "domain\username"
java.lang.Exception: Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
It would be helpfull if i get the specific exception from the server.With this expection i am unable to track my pgm.
I dont know where did i go wrong? am i missing anything ? any configuration is required ?
Thanks in advance for your help
I had the same problem, try with an Authenticator :
new BasicAuthentication(userName,password).authenticate();
My BasicAuthentication class :
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class BasicAuthentication extends Authenticator
{
private String username;
private String password;
public BasicAuthentication(String username, String password)
{
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return (new PasswordAuthentication(username,password.toCharArray()));
}
public void authenticate()
{
Authenticator.setDefault(this);
}
}