Hello I am new to apex and soql, I would like some help on my test class, below is the code i am having trouble with,
public class UpdateMyCard {
#AuraEnabled(cacheable=false)
public static Card__c updateCard(Double Amount){
String userId = UserInfo.getUserId();
Card__c myCard = [SELECT Id, Card_no__c, total_spend__c From Card__c Where OwnerId =:userId];
myCard.total_spend__c = myCard.total_spend__c + Amount;
try{
update myCard;
}catch (Exception e) {
System.debug('unable to update the record due to'+e.getMessage());
}
return myCard;
}
}
Test Class
#isTest
public static void updatecard(){
UpdateMyCard.updateCard(200);
}
Error:
System.QueryException: List has no rows for assignment to SObject
Your code assumes there's already a Card record for this user. And it's exactly 1 record (if you have 2 your query will fail). I'm not sure what's your business requirement. Is it guaranteed there will always be such record? Should the code try to create one on the fly if none found? You might have to make that "updateCard" bit more error-resistant. Is the total spend field marked as required? Because "null + 5 = exception"
But anyway - to fix your problem you need something like that in the test.
#isTest
public static void updatecard(){
Card__c = new Card__c(total_spend__c = 100);
insert c;
UpdateMyCard.updateCard(200);
c = [SELECT total_spend__c FROM Card__c WHERE Id = :c.Id];
System.assertEquals(300, c.total_spend__c);
}
The following is my constructor for a Student object. I will be using a list of student. I need to store the list so even if the program is turned off, I can still access all the contents. The only way I could think of was to use reader/writer and a text file.
1) Is there a more efficient way to store this information?
2) If not, how can I use reader/writer to store each field?
public Student(String firstName, String lastName, String gender, String
state, String school, String lit, String wakeUp, String sleep, String
social,String contactInfo, String country, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.state = state;
this.school = school;
this.lit = lit;
this.wakeUp = wakeUp;
this.sleep = sleep;
this.social = social;
this.contactInfo = contactInfo;
this.country = country;
this.major = major;
}
The possibilities are really project specific and subjective.
Some possibilities include:
CSV file which makes it easy for exporting to other programs and parsing data
Online server which allows access from any computer that has the
program and an internet connection
Text file which works for local devices that won't require many
additions
It really just depends on how you want to implement it and what method suits your needs best.
To use reader/writer to store your fields, you could use the accessor methods of each variable to store them line by line in your text file. Below is some sample code to get you started on writing to the file:
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream(FILE_LOCATION));
}
catch (FileNotFoundException ex) {
JOptionPane optionPane = new JOptionPane("Unable to write to file\n " + FILE_LOCATION, JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("Error!");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
System.exit(0);
}
Iterator<YOUR_OBJECT> i = this.List.iterator();
YOUR_OBJECT temp = null;
while (i.hasNext()) {
temp = i.next();
if (temp instanceof YOUR_OBJECT) {
outputStream.println(temp.getAttribute());
}
}
outputStream.close();
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 want to retrieve all the data inside the text file, so I will read to vector 1st then display all the data out. The 1st data in the text file I can get it properly, but the 2nd data in the text file, the username can't be retrieve and it gone.
Here's the text file data...
1|admin|admin|admin|Male|123|123|123|
1|jeff|jeff|jeff|Male|123|123|123|
And after I display all the data out...it become like this
1 admin admin admin Male 123 123 123
1 jeff jeff Male 123 123 123
Can anyone help me to solve?? THANKS
void Admin::displayMemberInfo(vector <Member> &memberProfile)
{
if(loginSucceed == true)
{
int memberID, age;
string username, password, name, gender, contact, ic;
memberProfile.erase(memberProfile.begin(),memberProfile.end());
ifstream inMember("Member.txt");
while(!(inMember.eof()))
{
string name,gender,contact, ic, username, password;
int age,memberID;
string readID,readAge;
getline(inMember,readID,'|');
istringstream(readID)>>memberID;
getline(inMember,username,'|');
getline(inMember,password,'|');
getline(inMember,name,'|');
getline(inMember,gender,'|');
getline(inMember,readAge,'|');
istringstream(readAge)>>age;
getline(inMember,contact,'|');
getline(inMember,ic,'|');
inMember.ignore(numeric_limits<streamsize>::max(), '|');
//if(username != "")
//{
// Member member(memberID, username, password, name, gender,age, contact, ic);
// memberProfile.push_back(member);
//}
cout<<memberID<<username<<password<<name<<gender<<age<<contact<<ic<<endl;
}
inMember.close();
system("pause");
}
}
You need to change this line
inMember.ignore(numeric_limits<streamsize>::max(), '|');
to
inMember.ignore(numeric_limits<streamsize>::max(), '\n');
Oh yeah, I forgot, you redeclare variables.
Try this entire function and tell me if it works better:
void Admin::displayMemberInfo(/* vector <Member> &memberProfile */) {
int memberID, age;
string username, password, name, gender, contact, ic;
//memberProfile.erase(memberProfile.begin(),memberProfile.end());
ifstream inMember("Members.txt");
if(inMember.fail()) return;
while(!(inMember.eof())) {
string readID,readAge;
getline(inMember,readID,'|');
istringstream(readID)>>memberID;
getline(inMember,username,'|');
getline(inMember,password,'|');
getline(inMember,name,'|');
getline(inMember,gender,'|');
getline(inMember,readAge,'|');
istringstream(readAge)>>age;
getline(inMember,contact,'|');
getline(inMember,ic,'|');
inMember.ignore(numeric_limits<streamsize>::max(), '\n');
//if(username != "")
//{
// Member member(memberID, username, password, name, gender,age, contact, ic);
// memberProfile.push_back(member);
//}
cout<<memberID<<username<<password<<name<<gender<<age<<contact<<ic<<endl;
}
inMember.close();
system("pause");
}
You were also re-declaring variables in the function as well as the while loop.
I commented out the vector stuff for my test.
My input file is
1|admin|admin|admin|Male|123|123|123|
2|jeff|jeff|jeff|Male|123|123|123|
Terminated with a new line. The output is
1adminadminadminMale123123123
2jeffjeffjeffMale123123123
I have insert some node into Neo4j DB.And I want to select some node from database and cast it to specific class.
Here are some code about the problem:
class Service {
Neo4jTemplate neo4jTemplate
#Transactional
def find() {
def id1 = 11
//Knowledge k = neo4jTemplate.findOne(1, Knowledge)
Result result = neo4jTemplate.query("start n=node(11) return ID(n),n.name,n.age;", null)
//how to cast the result to User class
println "the tpye of result called User is "+ result.to(User.class).is(cn.edu.bnuz.itc.bok.sub2.User.class)
}
}
The detail about node like :
+-------------------------------------------------------------------------+
| Node[11]{career:"programmer",name:"kelvin",age:35,introduce:"lazy doy"} |
+-------------------------------------------------------------------------+
#NodeEntity
class User {
#GraphId
Long id;
String name;
int age;
}
I just want get the node's id, name, age from db and put it into a User class.
But it failed many time with many method.
Here I have encounter a problem which is :How can I cast the result to my target class? I have try many method to cast but fail finally.Thank you for you attention.
Return the user node from the query and call the to method of the returned Result with the desired class as argument:
Result result = neo4jTemplate.query("start n=node(11) return n", null);
for(User u : result.to(User.class)) {
doSomethingWith(u);
}
You may want to consider using repositories that support cypher queries like:
public interface UserRepository extends GraphRepository<User> {
#Query("start n=node(11) return n")
Iterable<User> getUser11();
}