How to update the tables in dataclass IBM? - ibm-cloud

I am trying to update a dataclass table with extra values after inserting some fields in the columns,again if i want insert the details in the same column,its not working,it gets in the second row,could anyone please help me,i want this answer as soon as possible

This is how I updated the row in bluemix by getting a particular column value position. Here is the code.
This is the code for getting the entire values from the bluemix table:
IBMQuery<Company> query = IBMQuery.queryForClass(Company.CLASS_NAME);
query.find().continueWith(new Continuation<List<Company>, Void>() {
public Void then(Task<List<Company>> task) throws Exception {
final List<Company> objects = task.getResult();
// Log if the find was cancelled.
if (task.isCancelled()) {
Log.e(CLASS_NAME, "Exception : Task " + task.toString()
+ " was cancelled.");
}
// Log error message, if the find task fails.
else if (task.isFaulted()) {
Log.e(CLASS_NAME, "Exception : "
+ task.getError().getMessage());
}
// If the result succeeds, load the list.
else {
companyList.clear();
for (IBMDataObject storeObject : objects) {
companyList.add((Company) storeObject);
}
if (task.isCompleted()) {
handler.sendEmptyMessage(2);
}
}
Where Company is the name of the Table and companyList is the company class array list.
After this code is executed the companylist will get all the rows and columns values stored in bluemix from which we can get the required row by using the query
query.whereKeyEqualsTo(User.RegisterName, userName);
query.whereKeyEqualsTo(User.Password, password);
Where User is the table name
RegisterName and Password are static variable defined in the User Class
userName and password is the user defined given inputs.
By getting the position of the required row retrieved in companyList, I do the update in the following way:
Company companyObject=Company.getPosition(position);
companyObject.setName("Something");
companyObject.save() query......
Now the problem is I'm able to do the update properly, but I'm not able to retrieve the table values from bluemix using the code which I mentioned in the top.

// Find a set of objects by class
IBMQuery<Item> queryByClass = IBMQuery.queryForClass(Item.class);
// Find a specific object
IBMQuery<Item> queryForObject = myItem.getQuery();
query.find().continueWith(new Continuation<List<Item>, Void>() {
#Override
public Void then(Task<List<Item>> task) throws Exception {
if (task.isFaulted()) {
// Handle errors
} else {
// do more work
List<Item> objects = task.getResult();
}
return null;
}
});
This code came from http://mbaas-gettingstarted.ng.bluemix.net/android

Related

Flutter Parse Server Sdk not saving the second object in the table (class)

this function takes a ServicePoint object as argument, which has the following attributes:
adminId (String)
name (String)
serviceType (enum)
I want this function to create a new Table with name: "name+adminId". This is achieved.
Also I want this function to create a new Table (if it is not there already) by the name ServicePoints.
ServicePoints stores the relationship between user (with objectId = adminId) and the new Table.
To achieve this, I set "serviceTable" attribute with value as the new Table created, acting as a pointer.
When I run the code first time, I achieve the required tables. But, when I run the function second time, it doesn't add the new row/record to ServicePoints table.
I don't know why.
UPDATE I found that set ParseObject operation is the culprit. But, to my surprize, it executes successfully for the very first time. But fails every next time. This is really absurd behaviour from parse_server_sdk_flutter.
Future<bool> createServicePoint(ServicePoint servicePoint) async {
String newServicePointName = servicePoint.name + servicePoint.adminId;
var newServiceTable = ParseObject(newServicePointName);
var response = await newServiceTable.save();
if (response.success) {
print('Now adding new row to ServicePoints table');
var servicePointsTable = ParseObject('ServicePoints')
..set<String>("serviceName", servicePoint.name)
..set<String>("adminId", servicePoint.adminId)
..set<String>("serviceType", _typeToLabel[servicePoint.serviceType])
..set<ParseObject>("serviceTable", newServiceTable);
var recentResponse = await servicePointsTable.save();
return recentResponse.success;
} else {
return false;
}
}
If anyone runs into this problem, you need to check the result after saving the ParseObject. If there is error like "Can't save into non-existing class/table", then just go to the dashboard and create the table first.

Parse Server SDK - Include Object method doesn't work for fetching the whole object in flutter

I was using parse server sdk in my app for database.
I have three class in my Back4App Dashboard which are "_User", "Office", "Office_Members".
In Office_Members class it has following columns,
user_id (Pointer to _User)
office_id (Pointer to Office)
count
To fetch the data including Pointer to _User as well from Office_Members, I am using following code,
QueryBuilder<ParseObject> parseQuery = QueryBuilder<ParseObject>(ParseObject("Office_Members"))
..whereEqualTo("office_id", ParseResponse_OfficeObject)
..includeObject(["user_id "]);
ParseResponse apiResponse = await parseQuery.query();
Output :
Payload : [{"className":"Office_Members","objectId":"twpDY51PUK","createdAt":"2020-08-14T09:58:59.775Z","updatedAt":"2020-08-14T09:58:59.775Z","office_id":{"__type":"Pointer","className":"Office","objectId":"4dkfSMrwBI"},"user_id":{"__type":"Pointer","className":"_User","objectId":"Hx5xJ5ABxG"},"count":1}]
In my payload response i am not getting whole user_id pointer response.
So can anybody help me that what i might be doing wrong?
Thanks.
The data should be included.
The logging function simply does not print the data of pointers.
The data should be included. The print function not print the data of pointers.
You can print it out directly for testing purposes, E.g.
response.results[0].get('user_id').get('name')
Evaluation Expression E.g.
In your model u can access at same way, E.g
Call Model
if(response.success){
return response.results.map((p) => Example.fromParse(p)).toList();
} else {
throw ParseErrors.getDescription(response.error.code);
}
Model
import 'package:parse_server_sdk/parse_server_sdk.dart';
class Example {
Example({this.id, this.name});
Example.fromParse(ParseObject parseObject) :
id = parseObject.objectId,
name = parseObject.get('user_id').get('name');
final String id;
final String name ;
#override
String toString() {
return 'Example{id: $id, name: $name}';
}
}
Why not simply use cloud code ? I'm not to familiar with flutter but I can suggest you this alternative solution.
Write a function like this.
Parse.Cloud.define("fetchMemberAndUser", async (request) => {
//Pass in ParseResponse_OfficeObject ID as parameter
var objectId = request.params.id;
//Now do a simple get query
var query = new Parse.Query(Parse.Object.extend("Office_Members"));
//Using .includes to get the user profile object
query.include("user_id");
//This will return Office_Memebers Object along with user profile
return query.get(objectId,{useMasterKey:true});
}

Insert or update record in HighScore table

I have a table that receives high score entries. However, if the user already has an entry in the table (tracked through a GUID field, not the user parameter) I want to update it if the new entry has a better time otherwise don't change the existing record. However, if the user doesn't have a record in the high score table then add a new record. I also have two query parameters to pass to the query.
I want the insert operation to handle this for the table. I have this so far but I get an exception raised when I call InsertAsync(...) on the highscore table
function insert(item, user, request) {
var sql ="select Id from HighScore where PlayerGUID=? AND PlayerBadge=?";
mssql.query(sql, [user.PlayerGUID], [user.PlayerBadge], {
success: function(results) {
if(results.length > 0) {
// leader board record exists so update the current record
// Check the existing record and update it is the new time is better
console.log("Found existing entry");
} else {
// no record exists for this user to insert one
request.execute();
console.log("Found existing entry");
}
}
});
}
Can anyone offer me any assistance with achieving my goal?
Many thanks,
J.
It took some time and some help but here's where I ended up. It works just as I intended it to.
function insert(item, user, request) {
// Store the passed in item object for us when inserting or updating
resultsItem = item;
// Store the request object to allow calld functions to send respond commands
thisRequest = request;
// Retrieve the HighScore table so we can check it for an existing record
hsTable = tables.getTable('HighScore');
// Update the leaderboard
updateLeaderboard(item);
}
// Global variables
var resultsItem, hsTable, thisRequest;
function updateLeaderboard(item){
//Filter the table using the where operator to only include those
// records for the current PlayerGUID and PlayerBadge fields
hsTable.where({
PlayerGUID: item.PlayerGUID,
PlayerBadge: item.PlayerBadge
}).read({
success:updateScore,
error: errorHandler
})
}
function updateScore(results){
if(results.length > 0) {
// If a record already exists then check the PlayerTime
if(results[0].PlayerTime > resultsItem.PlayerTime)
{
// Update the PlayerTime if it is less than the currently saved value
hsTable.update({
id: results[0].id,
PlayerTime: resultsItem.PlayerTime
}, {
success: logSuccess,
error: errorHandler
})
} else {
// Send them OK. Could change this and use the returned code/text to display a custom
// message that tells the user that a previous time is faster.
thisRequest.respond(statusCodes.OK);
}
} else {
// The record for this PlayerGUID and PlayerBadge exists so write one
hsTable.insert({
PlayerName: resultsItem.PlayerName,
PlayerCountry: resultsItem.PlayerCountry,
PlayerTime: resultsItem.PlayerTime,
PlayerBadge: resultsItem.PlayerBadge,
PlayerGender: resultsItem.PlayerGender,
PlayerDOB: resultsItem.PlayerDOB,
PlayerGUID: resultsItem.PlayerGUID
}, {
success: logSuccess,
error: errorHandler
})
}
}
// Called if there is an error
function errorHandler(error){
console.error
("An error occurred trying to update leaderboard infor for player" +
resultsItem.PlayerName);
thisRequest.respond(statusCodes.BAD_REQUEST);
}
//Called if things work out ok.
function logSuccess()
{
thisRequest.respond(statusCodes.OK);
}

Updating in Entity Framework - The following objects have not been refreshed because they were not found in the store

I'm saving an Order object using the following code:
public void SaveOrder (string orderNo)
{
using (var se = new StoreEntities)
{
var order = new Order { OrderNumber = orderNo }
try
{
//// Update
if (se.Orders.Any(e => e.OrderNumber == orderNo))
{
se.Orders.Attach(order);
se.ObjectStateManager.ChangeObjectState(order, EntityState.Modified);
}
//// Create
else
{
se.Orders.AddObject(order);
}
se.SaveChanges();
}
catch (OptimisticConcurrencyException){
se.Refresh(RefreshMode.ClientWins, order);
se.SaveChanges();
}
}
}
This works fine when it's a new order and I'm just inserting into the DB.
However, if I'm trying to update an existing order, I get his error:
The following objects have not been refreshed because they were not
found in the store: 'EntitySet=Orders;OrderID=0'.
In the database, the Order table looks like
OrderID | OrderNumber
13 567-87
15 567-93
where OrderID is an Identity key. There are no other rows besides these two as they have been deleted.
What am I doing wrong that I can't update a record?
Looks like you're getting the error because you're attaching the new Order object you've created as if it's an Order which already exists - that's why the OrderID in the error is zero.
Try this:
try
{
//// Update
var existingOrder = se.Orders.FirstOrDefault(e => e.OrderNumber == orderNo);
if (existingOrder != default(Order))
{
existingOrder.DateLastUpdated = DateTime.Now;
se.ObjectStateManager.ChangeObjectState(existingOrder, EntityState.Modified);
}
//// Create
else
{
se.Orders.AddObject(order);
}
se.SaveChanges();
}
Edit
You can update the order details property-by-property, or if you have an Order (or an OrderViewModel, perhaps) with the details you want to update, you could use something like AutoMapper to copy the values for you.

The given key was not present in the dictionary

I am developing a plugin in crm 5.0 to retrieve date "ct_valuedate" from an entity called "ct_marketvalue" and formatting and saving in a field called "ct_dateserial"
I get an error while I debug "The given key was not present in the dictionary"
public class MarketValueDateFormatting : PluginBase
{
protected override void ExecutePlugin()
{
try
{
switch (_crmMessage)
{
case CrmPluginMessageEnum.Create:
if (_context.InputParameters.Contains("ct_marketvalue"))
{
//Obtain the logical name of the entity
string moniker1 = ((EntityReference)_context.InputParameters["EntityMoniker"]).LogicalName;
//Verify that the target entity represents an Account.
//If not, this plug-in was not registered correctly.
if (moniker1.Equals("ct_marketvalue"))
{
Entity marketvalueimage = (Entity)_context.PostEntityImages["ct_marketvalue"];
Guid marketvalueid = marketvalueimage.Id;
if (marketvalueimage.Contains("ct_valuedate"))
{
DateTime dateserial = (DateTime)marketvalueimage.Attributes["ct_valuedate"];
String dateserialstring = dateserial.ToString("YYYYMMdd");
Ct_marketvalue marketvalue = new Ct_marketvalue();
marketvalue.Ct_dateserial = dateserialstring;
marketvalue.Id = marketvalueid;
_serviceContext.UpdateObject(marketvalue);
}
}
}
break;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Few notes about your code.
You should check in your code that _context.PostEntityImages contains "ct_marketvalue". It's possible either to forgot register or to do a mistake in image name.
Might be better use .ToEntity rather than access attributes using .Attributes["ct_valuedate"].
I'm not sure what is purpose of the plugin you wrote, but it looks it is post stage plugin and it updates the same entity instance, that was in InputParameters. Might be better to make this plugin pre stage and update value directly in InputParameters. Because, if not "The given key was not present in the dictionary" exception, it will cause infinite loop. You will need check context.Depth.