i want to create login system in c++, and i've got simple login function:
bool DBProperties::loginToSystem(string identifier, string password)
{
connectToDatabase();
prep_stmt = con->prepareStatement("SELECT * FROM user WHERE identifier_code = ? AND password = ?");
prep_stmt->setString(1, identifier);
prep_stmt->setString(2, generateHashPassword(password));
res = prep_stmt->executeQuery();
if (res->rowsCount() == 1) {
res->next();
}
delete prep_stmt;
delete con;
return false;
}
And my question is, how to store user that i get from database? Can i create object which will be visible from whole project? I need to do operates on this user from other functions.
Thanks.
If what you want is one user class that could have members like
user.name; user.password; user.email;
you could use a singleton pattern which would be declared globally.
this is a general outline of a singleton this website has a full explanation though. singletons.
``
// rough singleton pattern
class user
{
private:
user(){
// single instance checking code here
}
public:
string user;
string password;
string email;
};
user* userObject = new user();
int main(){
cout << userObject.user << endl;
cout << userObject.email << endl;
}
``
singleton patterns have a major flaw though, they are inherently difficult to expand on, say you at some point wanted to cache another user you would have to create another user class.
you could put the class on the heap(so it won't be deleted when the function ends) and then pass a pointer to your user object to wherever it's needed
the pointer method might be a better solution
// something like this
class user{
user(string user, string password, string email){
user = user;
email = email;
password = password;
}
string user;
string password;
string email;
};
int myLoginFunction(string username, string password, string email, user* userObject){
userObject = new user(username, password, email);
}
you can then use that pointer to your user object to access that object with userObjectPointer->memberValue
I am using Univocity parser version 2.7.3. I have a CSV file that has 1 Million records and might grow in future. I am reading only a few specific columns from the file and below are my requirements:
DO NOT store the CSV contents into memory at any point
Ignore/skip bean creation if either of latitude or longitude columns
in CSV are null/blank
To meet these requirements, I tried implementing CsvRoutines so that the CSV data is not copied over to memory. I am using #Validate annotation on both "Latitude" and "Longitude" fields and have used error handler to not throw back any exception so that the record will be skipped on validation failure.
Sample CSV:
#version:1.0
#timestamp:2017-05-29T23:22:22.320Z
#brand:test report
network_name,location_name,location_category,location_address,location_zipcode,location_phone_number,location_latitude,location_longitude,location_city,location_state_name,location_state_abbreviation,location_country,location_country_code,pricing_type,wep_key
"1 Free WiFi","Test Restaurant","Cafe / Restaurant","Marktplatz 18","1233","+41 263 34 05","1212.15","7.51","Basel","test","BE","India","DE","premium",""
"2 Free WiFi","Test Restaurant","Cafe / Restaurant","Zufikerstrasse 1","1111","+41 631 60 00","11.354","8.12","Bremgarten","test","AG","China","CH","premium",""
"3 Free WiFi","Test Restaurant","Cafe / Restaurant","Chemin de la Fontaine 10","1260","+41 22 361 69","12.34","11.23","Nyon","Vaud","VD","Switzerland","CH","premium",""
"!.oist*~","HoistGroup Office","Office","Chemin de I Etang","CH-1211","","","","test","test","GE","Switzerland","CH","premium",""
"test","tess's Takashiro","Cafe / Restaurant","Test 1-10","870-01","097-55-1808","","","Oita","Oita","OITA","Japan","JP","premium","1234B"
TestDTO.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class TestDTO implements Serializable {
#Parsed(field = "location_name")
private String name;
#Parsed(field = "location_address")
private String addressLine1;
#Parsed(field = "location_city")
private String city;
#Parsed(field = "location_state_abbreviation")
private String state;
#Parsed(field = "location_country_code")
private String country;
#Parsed(field = "location_zipcode")
private String postalCode;
#Parsed(field = "location_latitude")
#Validate
private Double latitude;
#Parsed(field = "location_longitude")
#Validate
private Double longitude;
#Parsed(field = "network_name")
private String ssid;
}
Main.java
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.detectFormatAutomatically();
parserSettings.setLineSeparatorDetectionEnabled(true);
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setSkipEmptyLines(true);
parserSettings.selectFields("network_name", "location_name","location_address", "location_zipcode",
"location_latitude", "location_longitude", "location_city","location_state_abbreviation", "location_country_code");
parserSettings.setProcessorErrorHandler(new RowProcessorErrorHandler() {
#Override
public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) {
//do nothing
}
});
CsvRoutines parser = new CsvRoutines(parserSettings);
ResultIterator<TestDTO, ParsingContext> iterator = parser.iterate(TestDTO.class, new FileReader("c:\\users\\...\\test.csv")).iterator();
int i=0;
while(iterator.hasNext()) {
TestDTO dto = iterator.next();
if(dto.getLongitude() == null || dto.getLatitude() == null)
i++;
}
System.out.println("count=="+i);
Problem:
I actually expected the count to be zero since I have added error handler and haven't thrown back the data validation exception but seems thats not the case. I thought #Validate will throw back an exception when it encounters a record with either Latitude or Longitude as null (both the columns may be null in same record as well) which is handled and ignored/skipped at error handler.
Basically I do not want UniVocity to create and map unnecessary DTO objects in heap (and lead to out of memory) since there are chances that the incoming CSV file might have more than 200 or 300k records with either Latitude/Longitude as null.
I even tried adding custom validator in #Validate as well but in vain.
Could someone please let me know what am I missing here?
Author of the library here. You are doing everything right. This is a bug and I just opened this issue here to be resolved today.
The bug appears when you select fields: the reordering of values makes the validation run against something else (in my test, it validated the city instead of latitude).
In your case, just add the following line of code and it will work fine:
parserSettings.setColumnReorderingEnabled(false);
This will make the rows be generated with nulls where fields were not selected, instead of removing the nulls and reordering the values in the parsed row. It will avoid the bug and also make your program run slightly faster.
You will also need to test for null in the iteration bit:
TestDTO dto = iterator.next();
if(dto != null) { // dto may come null here due to validation
if (dto.longitude == null || dto.latitude == null)
i++;
}
}
Hope this helps and thank you for using our parsers!
I have a custom object Employee with fields below. The employee data is maintained in an external system which is sending a base64 encoded string of the csv extract by calling a web service.
I am able to decode the string by using EncodingUtil.base64Decode(). My question is how can I prepare inserts from the decoded base64 string in Salesforce custom object.
String File = 'U25vLE5hbWUsTGFzdCBOYW1lLEVtcCBJZCxKb2IgRnVuY3Rpb24NCjEsU2FjaGluLENob3VyYXNpeWEsMzMwLEJ1c2luZXNzDQoyLFJhamF0ICxTYXhlbmEgLDMzNCxGdW5jdGlvbmFsDQo=';
String myFile = EncodingUtil.base64Decode(file).toString();
System.debug('Sachin'+'['+ myFile + ']');
Debug logs
I found an answer by myself. Please take a look and provide feedback.
String File = 'U25vLE5hbWUsTGFzdCBOYW1lLEVtcCBJZCxKb2IgRnVuY3Rpb24NCjEsU2FjaGluLENob3VyYXNpeWEsMzMwLEJ1c2luZXNzDQoyLFJhamF0ICxTYXhlbmEgLDMzNCxGdW5jdGlvbmFsDQo=';
String myFile = EncodingUtil.base64Decode(file).toString();
System.debug('Sachin'+'['+ myFile + ']');
List<String> EmployeeList = new List<String>();
EmployeeList = myFile.split('\n');
List<Employee__c> employeeInsertList = new List<Employee__c>();
for (String employee : EmployeeList)
{
List<String> fields = new List<String>();
fields = employee.split(',');
Employee__c empRecord = new Employee__c();
empRecord.LastName__c = fields[2];
empRecord.Name = fields[1];
empRecord.EmpId__c = fields[3];
empRecord.Job_Function__c = fields[4];
employeeInsertList.add(empRecord);
}
System.debug('Employee List is '+employeeInsertList);
insert employeeInsertList;
I have an xObject Class which basically is a trivial "Person" Class and I want to be able to serialize the whole class to a .json file, and then read that file in order to be able to extract the variables from the file and link those variables to the name of the class.
So for example:
xObject Class Code:
class xObject{
string name;
string lastname;
int age;
public:
string getName(){
return name;
}
string getLastname(){
return lastname;
}
int getAge(){
return age;
}
}
And then I create an object with some attributes on it.
int main(){
xObject homer;
homer.name = "Homer";
homer.lastname = "Simpson";
homer.age = 30;
//SERIALIZATION OF HOMER.
homer.serialExport("File.json")
return 0;
}
So now, my File.json should look like this:
{"homer" :
{"name" : "Homer"
"lastname" : "Simpson"
"age" : 30
}
}
and then, I want to be able to read from the file to extract data from it with something like this:
int main(){
xObject bart;
bart.name = "Bart";
//ACTUAL USE OF THE .JSON FILE HERE
myFile = ("File.json");
bart.lastname = Deserializer(myFile).getLastname(); //It is supossed to assign "Simpson"
//to the lastname reading from the serialized
//homer class file described above.
bart.age = Deserializer(myFile).getAge() - 20; //Sets homer's age minus 20 years.
return 0;
}
So, how can I do that on c++? (Libraries implementation accepted)
And how could I retrieve the class name that has been serialized?
For example Deserialize(myFile).getClassName() should return "homer"
I've done something similar in java with XML serialization, and it was pretty straight forward, but it seems that in C++ this is not very easy to do, and I'm relatively new to C++.
In c++ there is not introspection/reflection, so you can't automatically serialize a class without explicitly write your member variables in your stream. For the same reason, you can't retrieved the class name that have been serialized.
So the solution is to write a function in your class that serializes the member variables you want.
Of course you will not reinvent the wheel to format your file in json. You can use: https://github.com/open-source-parsers/jsoncpp.
For instance you can write:
Json::Value root;
root["homer"]["name"]="Homer";
root["homer"]["lastname"]="Simpson";
//etc
ofstream file;
file.open("File.json");
file << root;
file.close();
However, for the read, you can do as you wanted:
Json::Value root2;
ifstream file2;
file2.open("File.json");
file2 >> root2;
file2.close();
xObject homer;
homer.lastname = root2["homer"]["lastname"].toStyledString();
//etc
Of course your attribute has to be public. Otherwise you need to add a setter function.
I need to create a program with Windows forms. I made a bit of code in c++...and Windows forms in c++/cli at the same time. Now I'm trying to adapt the c++ code from the forms, but I'm having some problems with the file, it's completely different from c++.
I have 2 forms. The first is for registration (it should register every student in a file). The second is for modifying students data with a given surname for example.
In registration.cpp I have created a list of objects but when I write I use streamwriter, but I guess there isnt any relationship with my list.
So my problems are:
How can I WRITE my data list into a file?
How can I MODIFY that data?
Now I post some code, but it's in italian :D as I am from italy (sorry for my mistakes.)
//.cpp of the registration
class studente
{
private:
string cognome;
string nome;
public:
studente(){
cognome="";
nome="";
};
~studente(){};
void set(string str1,string str2){
cognome=str1;
nome=str2;
}
class primo_anno:public studente
{
private:
int voto_diploma;
public:
primo_anno(){
cognome="";
nome="";
voto_diploma='0';
};
~primo_anno(){};
void set(string str1,string str2, int mark){ voto_diploma=mark; };
void stampa(){//I KNOW ITS NOT USEFUL HERE..BUT IN C++ I USED THAT
f<<"\ncognome: "<<cognome<<"\n";
f<<"nome: "<<nome<<"\n";
f<<"voto: "<<voto_diploma<<"\n";
};
};
list<primo_anno> l1;//DECLARE MY STL LIST
{//WHEN I CLICK ON MY REGISTER BUTTON THE PROGRAM RUN THIS
int mark;
primo_anno *s;
s=new primo_anno;
char* str1=(char*)(Marshal::StringToHGlobalAnsi(textBox1->Text)).ToPointer();
char* str2=(char*)(Marshal::StringToHGlobalAnsi(textBox2->Text)).ToPointer();
mark = Convert::ToInt16(textBox35->Text);
s->set(str1,str2,mark);
l1.push_back(*s);
list<primo_anno>::iterator it;
//I HAVE FOUND THIS METHOD BUT ITS NOT LINKED TO MY STL LIST.
//BY THE WAY I AM ABLE TO WRITE ON FILE WITH THIS.BUT LATER I DONT KNOW HOW TO MODIFY
//FOR EXAMPLE "DELETE THE LINE WHERE THERE IS Rossi SURNAME".HOW!!!
TextWriter ^tw = gcnew StreamWriter("primoAnno.txt", true);//true append
tw->WriteLine(textBox1->Text + "\t\t" + textBox2->Text + "\t\t" + textBox35->Text);
tw->Close();
Thank you in advance! And sorry again for my English... I'm just a student:)
Normally, you can convert a std::string into a System::String^ quite easily (it's even possible that simply using gcnew String(myPrimoAnnoObj.cognome) will give you a string with the right contents, easily written into the managed stream.
However you appear to have failed to grasp how new works for unmanaged objects: Your code allocates a primo_anno structure dynamically for no reason, before copying its value into the list and leaking the pointer. You also leak the pointers to the unmanaged strings you obtained from the Marshal class.
Are you sure you should be using unmanaged objects? It would be much easier to have everything in a managed System::Collections::Generic::List<> of managed objects...
Added: For writing everything in a file, you can try something like this:
ref class MyClass
{
public:
String^ cognome;
String^ nome;
int voto_diploma;
};
//...
List<MyClass^>^ primo = gcnew List<MyClass^>();
//...
MyClass^ myObj = gcnew MyClass();
myObj->cognome = textBox1->Text;
myObj->nome = textBox2->Text;
myObj->voto_diploma = Convert::ToInt32(textBox35->Text);
primo->Add(myObj);
//...
TextWriter ^tw = gcnew StreamWriter(L"primoAnno.txt", true);
for each(MyClass^ obj in primo)
{
//You can use any character or string as separator,
//as long as it's not supposed to appear in the strings.
//Here, I used pipes.
tw->Write(obj->cognome);
tw->Write(L"|");
tw->Write(obj->nome);
tw->Write(L"|");
tw->WriteLine(obj->voto_diploma);
}
tw->Close();
For reading, you can use a function like this:
MyClass^ ParseMyClass(String^ line)
{
array<String^>^ splitString = line->Split(L'|');
MyClass^ myObj = gcnew MyClass();
myObj->cognome = splitString[0];
myObj->nome = splitString[1];
myObj->voto_diploma = Convert::ToInt32(splitString[2]);
return myObj;
}
And for deleting:
TextWriter^ tw = gcnew StreamWriter(L"primoAnno2.txt", true);
TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
String^ line;
while((line=tr->ReadLine()) != nullptr)
{
MyClass^ obj = ParseMyClass(line);
if(obj->cognome != L"cat")
tw->WriteLine(line);
}
tr->Close();
tw->Close();
File::Delete(L"primoAnno.txt");
File::Move(L"primoAnno2.txt", L"primoAnno.txt");
It may not be the exact code, but it's overall what should work.
Note: If you want your separator to be spaces, and there can be spaces in the strings, things will get a lot more complicated.
I have tried to use a generic list..(thanks MSDN).in the comments below there are my dubts..
List<String^>^ primo=gcnew List<String^>();
int mark;
char* str1=(char*)(Marshal::StringToHGlobalAnsi(textBox1->Text)).ToPointer();
char* str2=(char*)(Marshal::StringToHGlobalAnsi(textBox2->Text)).ToPointer();
mark = Convert::ToInt16(textBox35->Text);
//here i add TEXTBOXES to my generic list...not objects of my stl list
primo->Add(textBox1->Text);
primo->Add(textBox2->Text);
primo->Add(textBox35->Text);
TextWriter ^tw = gcnew StreamWriter("primoAnno.txt", true);
for each(String^ prim in primo){
//here i write my string one by one in column..i want them all in a line!how?
tw->WriteLine(prim);
}
//i also have tried to delete an object..but i dont like the remove..i mean i want all the strings in a line, if i find "cat" for example i want to delete the ENTIRE line..not just "cat"
if(primo->Contains("cat"))tw->WriteLine("ok");primo->Remove("cat");
for each(String^ prim in primo){
tw->WriteLine(prim);
}
tw->Close();
i make an example of my primoAnno.txt file
first time i write(and push the register button) i want this:
cat gae 5
second time i write(and push the register button again) i want this:
cat gae 5
bla bla 1
then, when i remove(if there is "cat" in a line delete that line) i want this:
bla bla 1
hope it s useful. thanks to ones who will reply