I'm trying to get a specific value over an wmi query. I know that this value is stored in an array itself but I can't get access on it.
ManagementObjectSearcher ^searcher =
gcnew ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive WHERE PNPDeviceID LIKE '" + marshal_as<String^>(DEV_FILTER) +"%'");
for each (ManagementObject ^drive in searcher->Get())
{
for each (ManagementObject ^o in drive->GetRelated("Win32_DiskPartition"))
{
for each (ManagementObject ^logDisk in o->GetRelated("Win32_LogicalDisk"))
{
Console::WriteLine(
"Disk: " + drive["Caption"]
+ "\n\tSize : " + drive["Size"]
+ "\n\tDriveLetter : " + logDisk["Name"]
+ "\n\t" + drive["PNPDeviceID"]
+ "\n\tSerialNumber: " + drive["SerialNumber"]
+ "\n\t" + drive["Capabilities"]
+ "\n\tRevision : " + drive["FirmwareRevision"]);
}
}
}
on Debug investigation, I can see every single Value of drive["Capabilites"] but everything I've tried so far, I can't get this array's child values.
I want to do this in c++,
every help is appreciated.
To access such values you must cast the property and an array and then iterate over the elements. try this C++ CLI sample code.
#include "stdafx.h"
#using <system.management.dll>
using namespace System;
using namespace System::Management;
int main(array<System::String ^> ^args)
{
ManagementObjectSearcher ^searcher =
gcnew ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive");
for each (ManagementObject ^drive in searcher->Get())
{
for each (ManagementObject ^o in drive->GetRelated("Win32_DiskPartition"))
{
for each (ManagementObject ^logDisk in o->GetRelated("Win32_LogicalDisk"))
{
Console::WriteLine(
"Disk: " + drive["Caption"]
+ "\n\tSize : " + drive["Size"]
+ "\n\tDriveLetter : " + logDisk["Name"]
+ "\n\t" + drive["PNPDeviceID"]
+ "\n\tSerialNumber: " + drive["SerialNumber"]
+ "\n\tRevision : " + drive["FirmwareRevision"]);
Console::WriteLine("Capabilities");
for each(UInt16 v in (array<UInt16>^)(drive->Properties["Capabilities"]->Value))
{
Console::WriteLine(v);
}
}
}
}
Console::ReadLine();
return 0;
}
Related
I'm quite new to C++ and know a little bit about pqxx library. What I want to implement is to prepare statements and bind parameters. In PHP I'm used to doing this in such a nice and concise manner:
$s = $db->prepare("SELECT id FROM mytable WHERE id = :id");
$s->bindParam(':id', $id);
$s->execute();
or using tokens:
$data = array();
$data[] = 1;
$data[] = 2;
$s = $db->prepare("SELECT id FROM mytable WHERE id = ? or id = ?");
$s->execute($data);
I tried to fugure out from pqxx documentation how to implement this, but to me documentation looks like a mess and lacks short and simple examples (like I provided above). I hope someone can also provide such simple examples (or of comparable simplicity - without having to write some behemoth code) when dealing with Postgresql in C++.
A simple example. This just prints the number of entries with id value 0.
#include<pqxx/pqxx>
#include<iostream>
int main()
{
std::string name = "name";
int id = 0;
try {
//established connection to data base
pqxx::connection c("dbname=mydb user=keutoi");
pqxx::work w(c);
//statement template
c.prepare("example", "SELECT id FROM mytable WHERE id = $1");
//invocation as in varible binding
pqxx::result r = w.prepared("example")(id).exec();
w.commit();
//result handling for accessing arrays and conversions look at docs
std::cout << r.size() << std::endl;
}
catch(const std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
The function w.prepared() is a bit convoluted. It's similar to a curried(curry) function in haskell, as in it takes a parameter and returns another function which in turn takes another parameter. That kind of thing.
Documentation says:
How do you pass those parameters? C++ has no good way to let you pass an unlimited, variable number of arguments to a function call, and the compiler does not know how many you are going to pass. There's a trick for that: you can treat the value you get back from prepared as a function, which you call to pass a parameter. What you get back from that call is the same again, so you can call it again to pass another parameter and so on.
Once you've passed all parameters in this way, you invoke the statement with the parameters by calling exec on the invocation
If there are more parameters use $1 $2 and so on in the prepare function.
c.prepare("SELECT id name FROM mytable WHERE id = $1 AND name = $2")
and give the varibles as
w.prepared("example")(dollar1_var)(dollar2_var).exec()
An Example for dynamic preparation
#include<pqxx/pqxx>
#include<iostream>
#include<vector>
//Just give a vector of data you can change the template<int> to any data type
pqxx::prepare::invocation& prep_dynamic(std::vector<int> data, pqxx::prepare::invocation& inv)
{
for(auto data_val : data)
inv(data_val);
return inv;
}
int main()
{
std::string name = "name";
//a data array to be used.
std::vector<int> ids;
ids.push_back(0);
ids.push_back(1);
try {
pqxx::connection c("dbname=mydb user=keutoi");
pqxx::work w(c);
c.prepare("example", "SELECT id FROM mytable WHERE id = $1 or id = $2");
pqxx::prepare::invocation w_invocation = w.prepared("example");
//dynamic array preparation
prep_dynamic(ids, w_invocation);
//executing prepared invocation.
pqxx::result r = w_invocation.exec();
w.commit();
std::cout << r.size() << std::endl;
}
catch(const std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
if you want to handle other data types use this function definition
template<class T> pqxx::prepare::invocation& prep_dynamic(std::vector<T> data, pqxx::prepare::invocation& inv)
{
for(auto data_val : data)
inv(data_val);
return inv;
}
Use pqxx::prepare::invocation where you can, and bind more values before execution, because it's more stable and error preventative, but there is a faster way as I describe it below.
I.
With invocation:
pqxx::nontransaction W(C);
std::string m_insertCommand = "INSERT INTO tableforperftest(column1, column2) VALUES";
unsigned int m_nCurrentRow = 32767;
for (size_t i = 0; i < m_nCurrentRow; i++)
{
unsigned int countOf$ = i * 2;
for (unsigned int i = 0; i < 2; ++i)
{
if (i == 0)
{
m_insertCommand += "(";
}
else
{
m_insertCommand += ", ";
}
m_insertCommand += "$";
std::stringstream ss;
ss << countOf$ + i + 1;
m_insertCommand += ss.str();
}
if(i < m_nCurrentRow - 1)
m_insertCommand += ") ,";
}
m_insertCommand += ")";
C.prepare("insert_into_db", m_insertCommand);
pqxx::prepare::invocation inv = W.prepared("insert_into_db");
for (size_t i = 0; i < m_nCurrentRow; i++)
{
inv(i)(i);
}
inv.exec();
II.
With stored procedure which gets more values for parameters:
CREATE OR REPLACE FUNCTION insertintoboosted(valuesforinsert TEXT) RETURNS VOID AS
$$
BEGIN
EXECUTE 'INSERT INTO tableforperftestproof(column1, column2) VALUES (' || valuesforinsert || ')';
END;
$$
LANGUAGE plpgsql;
Code:
for (size_t i = 0; i < m_nCurrentRow; i++)
{
if (i == 0)
ss << i << "," << i;
else
ss << "(" << i << "," << i;
if (i < m_nCurrentRow - 1)
ss << "),";
}
C.prepare("prep2", "select insertintoboosted($1::text)");
W.prepared("prep2")(ss).exec();
III.
With parameter bindings and execution for each time:
std::string m_insertCommand3 = "INSERT INTO tableforperftest(column1, column2) VALUES ($1, $2)";
C.prepare("insert_into_db3", m_insertCommand3);
for (size_t i = 0; i < m_nCurrentRow; i++)
{
W.prepared("insert_into_db3")(i)(i).exec();
}
To compare the solutions with 32767 inserts:
Invocation: --> Elapsed: 0.250292s
Stored Proc: --> Elapsed: 0.154507s
Parameter binding + execution each time: --> Elapsed: 29.5566s
I'm using USBHIDDRIVER to access a scale connected to our local workstation. Everything works fine when I run the WCF in Visual Studio 2012 Debug. But once I attempt to run the service in IIS it doesn't seem to recognize the USBHIDDRIVER. I have a test service in the WCF which works fine so the WCF is working.
Any information on how to troubleshoot this would be extremely helpful. My problem is that the WCF is compiled when I deploy to the IIS server so I'm having a hard time trying to troubleshoot.
Here is additional information regarding USBHIDDRIVER: http://www.florian-leitner.de/index.php/projects/usb-hid-driver-library/
namespace USBDevices
{
public class Service1 : IService1
{
public string GetWeight(string id)
{
USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface("vid_0922","pid_8007");
//string[] list = usb.getDeviceList();
string result;
string resultDesc;
byte itemWeight;
byte itemUOM;
result = "";
resultDesc = "";
itemWeight = 0;
itemUOM = 0;
if (usb.Connect() == true)
{
usb.startRead();
Thread.Sleep(100);
for (int i = 0; i < 200; i++)
{
var weight = USBHIDDRIVER.USBInterface.usbBuffer;
var cnt = weight.Count;
itemWeight = ((byte[])weight[cnt - 1])[4];
itemUOM = ((byte[])weight[cnt - 1])[2];
}
usb.stopRead();
result = "Success";
resultDesc = "Scale Found";
Debug.WriteLine("Result: " + result + "-" + resultDesc + " - Item Weight: " + ((float)itemWeight / 10));
}
else
{
result = "Failed";
resultDesc = "Scale Not Active";
itemWeight = 0;
itemUOM = 0;
Debug.WriteLine("Result: " + result + "-" + resultDesc + " - Item Weight: " + ((float)itemWeight / 10));
}
return result + "|" + resultDesc + "|" + ((float)itemWeight / 10) + "|" + itemUOM;
}
public string XMLData(string id)
{
return "You requested product " + id;
}
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
In order to resolve the problem I had to turn on "Enable 32-Bit Applications" for the website. Believe the problem is related to the DLL's that are used but USBHIDDRIVER
I am absolute beginner, I can't solve the the problem, getting error & exception is being thrown at
objCommand.ExecuteNonQuery();
Exception Message : "Must declare scalar variable #userId."
private void btnRegister_Click(object sender, EventArgs e)
{
if (tbxUserName.Text == "" || tbxPassword.Text == "")
{
MessageBox.Show("Please enter values!");
return;
}
string strConnection;
strConnection = ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString;
SqlConnection objConnection = new SqlConnection();
objConnection.ConnectionString = strConnection;
objConnection.Open();
string strSQL;
SqlCommand objCommand = new SqlCommand("SELECT * FROM LoginTable WHERE UserId='" + tbxUserName.Text + "';", objConnection);
SqlDataAdapter objAdapter = new SqlDataAdapter();
objAdapter.SelectCommand = objCommand;
objAdapter.Fill(objDataSet);
int i = objDataSet.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("User Name " + tbxUserName.Text + " already exists");
tbxPassword.Text = "";
objDataSet.Clear();
}
else
{
strSQL = "INSERT INTO LoginTable(UserId, Password) VALUES(#UserId, #Password)";
objCommand.Parameters.AddWithValue("#UsesrId", tbxUserName.Text);
objCommand.Parameters.AddWithValue("#Password", tbxPassword.Text);
objCommand.CommandText = strSQL;
objCommand.ExecuteNonQuery();
objConnection.Close();
message = "Registered Successfully! " + "Welcome " + tbxUserName.Text;
this.Hide();
WelcomeForm wf = new WelcomeForm(message);
wf.Show();
}
}
You have typo in your code, change it as following.( #UsesrId != #UserId)
strSQL = "INSERT INTO LoginTable(UserId, Password) VALUES(#UserId, #Password)";
objCommand.Parameters.AddWithValue("#UserId", tbxUserName.Text);
std::string output;
if ((checkbox1->isChecked() && checkbox2->isChecked()) &&
(!checkbox3->isChecked() || !checkbox4->isChecked() || !checkbox5->isChecked() || !checkbox6->isChecked()))
{
output = " Using Checkbox: 1, 2 ";
}
if ((checkbox1->isChecked() && checkbox2->isChecked() && checkbox3->isChecked()) &&
(!checkbox4->isChecked() || !checkbox5->isChecked() || !checkbox6->isChecked()))
{
output = " Using Checkbox: 1, 2, 3 ";
}
....
using QT creator how can I verify how many checkboxes have been checked and change the output string accordingly?
with multiple if statements it's not working due to me getting confused with all those NOT AND OR.
and it takes a long time to code all possibilities.
All your checkBoxes should be in groupBox
Try this:
QList<QCheckBox *> allButtons = ui->groupBox->findChildren<QCheckBox *>();
qDebug() <<allButtons.size();
for(int i = 0; i < allButtons.size(); ++i)
{
if(allButtons.at(i)->isChecked())
qDebug() << "Use" << allButtons.at(i)->text()<< i;//or what you need
}
Use an array of checkboxes like this
// h-file
#include <vector>
class MyForm {
...
std::vector< QCheckBox* > m_checkBoxes;
};
// cpp-file
MyForm::MyForm() {
...
m_checkBoxes.push_back( checkbox1 );
m_checkBoxes.push_back( checkbox2 );
...
m_checkBoxes.push_back( checkbox5 );
}
...
output = " Using Checkbox:";
for ( int i = 0, size = m_checkBoxes.size(); i < size; ++i ) {
if ( m_checkBoxes[ i ]->isChecked() ) {
output += std::to_string( i + 1 ) + ", ";
}
}
TLDR: Place them in a container and build your string by iterating over them.
Code:
// line taken from #Chernobyl
QList<QCheckBox *> allButtons = ui->groupBox->findChildren<QCheckBox *>();
auto index = 1;
std::ostringstream outputBuffer;
outputBuffer << "Using Checkbox: ";
for(const auto checkBox: allButtons)
{
if(checkBox->isChecked())
outputBuffer << index << ", ";
++index;
}
auto output = outputBuffer.str();
Use QString instead of std::string and then:
QCheckBox* checkboxes[6];
checkbox[0] = checkbox1;
checkbox[1] = checkbox2;
checkbox[2] = checkbox3;
checkbox[3] = checkbox4;
checkbox[4] = checkbox5;
checkbox[5] = checkbox6;
QStringList usedCheckboxes;
for (int i = 0; i < 6; i++)
{
if (checkbox[i]->isChecked())
usedCheckboxes << QString::number(i+1);
}
QString output = " Using Checkbox: " + usedCheckboxes.join(", ") + " ";
This is just an example, but there's numerous ways to implement this. You could keep your checkboxes in the QList which is a class field, so you don't have to "build" the checkboxes array every time. You could also use QString::arg() instead of + operator for string when you build the output, etc, etc.
What I've proposed is just a quick example.
Here Maps: I originally used this code to get the address on a category search but now address seems to have been removed and replaced with a vicinity property in HTML. Is this correct and is there a way to gain this level of detail?
if (locations[i].address.house != undefined) {
catResults2 = catResults2 + locations[i].address.house + " "
}
if (locations[i].address.street != undefined) {
catResults2 = catResults2 + locations[i].address.street
}
if (locations[i].address.district != undefined) {
catResults2 = catResults2 + ", " + locations[i].address.district
}
if (locations[i].address.city != undefined) {
catResults2 = catResults2 + ", " + locations[i].address.city
}
if (locations[i].address.state != undefined) {
catResults2 = catResults2 + ", " + locations[i].address.state
}
if (locations[i].address.postalCode != undefined) {
catResults2 = catResults2 + " " + locations[i].address.postalCode
}
if (locations[i].address.country != undefined) {
catResults2 = catResults2 + ", " + locations[i].address.country
}
if (locations[i].address.countryCode != undefined) {
catResults2 = catResults2 + " " + locations[i].address.countryCode
};
If you are reverse geocoding the address of a location using the HERE Maps API for JavaScript (as in this example here), then a properly localized address can be obtained using
locations[i].address.text