how to show upcoming data in Lightning datatable in aura lightning? - apex

Apex class code-
public class DesignAttClass {
#AuraEnabled public static sObject[] getRecords(String query) {
return Database.query(query);
}
}
helper code-
({
getRecrdHelper : function(component, event, helper) {
var action = component.get('c.getRecords');
action.setParams({'query' : component.get('v.Query')});
action.setCallback(this, function (res){
if(res.getState() === 'SUCCESS'){
console.log('Received = '+JSON.stringify(res.getReturnValue()));
component.set('v.recordsData',res.getReturnValue());
}else{
console.log('Something went wrong...!!!!');
}
});
$A.enqueueAction(action);
}
})
Now i wanted to try the upcoming data show in lightning datatable dynamically.

Related

Maui - FilePicker - Return TextFile FullPath Asynchronously

The goal is to have a Maui class library that will have a function that return a full path to read a text file in my Maui application.
Can you help me to fix the following code?
The error is when I try to return the FullPath as string
var FileFullPath = await result.FullPath.ToString();
Here the error description
Severity Code Description Project File Line Suppression State Error CS1061
'string' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) MPCFilePickerMauiLibrary (net7.0), MPCFilePickerMauiLibrary (net7.0-android), MPCFilePickerMauiLibrary (net7.0-ios), MPCFilePickerMauiLibrary (net7.0-maccatalyst) D:\repos\MPC-MassPropertiesCalculator\MPCFilePickerMauiLibrary\PickTxtFile.cs 35 Active
Here is the Maui class library that have created.
using Microsoft.Maui.Storage;
namespace MPCFilePickerMauiLibrary;
//Ref https://youtu.be/C6LV_xMGdKc - Intro To Class Libraries in C#
public class PickTxtFile
{
public static async Task<string> GetFilePathAsync()
{
//For custom file types
var customFileType = new FilePickerFileType(
new Dictionary<DevicePlatform, IEnumerable<string>>
{
{ DevicePlatform.iOS, new[] { "public.text" } }, // UTType values
{ DevicePlatform.Android, new[] { "text/plain" } }, // MIME type
{ DevicePlatform.WinUI, new[] { ".Txt" } }, // file extension
{ DevicePlatform.Tizen, new[] { "*/*" } },
{ DevicePlatform.macOS, new[] { "Txt" } }, // UTType values
});
var result = await FilePicker.PickAsync(new PickOptions
{
PickerTitle = "Pick MPC Demo file Please",
FileTypes = customFileType
});
if (result == null)
return "";
var FileFullPath = await result.FullPath.ToString();
return FileFullPath;
}
Here is the code where I'm using the function
using MPCFilePickerMauiLibrary;
using Microsoft.UI.Xaml.Controls;
namespace MPC_MassPropertiesCalculator_MAUIapp.Views;
public partial class MPCFileDemo : ContentPage
{
public MPCFileDemo()
{
InitializeComponent();
}
private void MenuFlyoutItem_Clicked(object sender, EventArgs e)
{
String filePath = PickTxtFile.GetFilePathAsync();
if (File.Exists(filePath))
{
//TODO Read file
}
}
}
With Jason's comments, here is the solution.
Maui class library
using Microsoft.Maui.Storage;
namespace MPCFilePickerMauiLibrary;
//Ref https://youtu.be/C6LV_xMGdKc - Intro To Class Libraries in C#
public class PickTxtFile
{
public static async Task<string> GetFilePathAsync()
{
//For custom file types
var customFileType = new FilePickerFileType(
new Dictionary<DevicePlatform, IEnumerable<string>>
{
{ DevicePlatform.iOS, new[] { "public.text" } }, // UTType values
{ DevicePlatform.Android, new[] { "text/plain" } }, // MIME type
{ DevicePlatform.WinUI, new[] { ".Txt" } }, // file extension
{ DevicePlatform.Tizen, new[] { "*/*" } },
{ DevicePlatform.macOS, new[] { "Txt" } }, // UTType values
});
var result = await FilePicker.PickAsync(new PickOptions
{
PickerTitle = "Pick MPC Demo file Please",
FileTypes = customFileType
});
if (result == null)
return "";
var FileFullPath = result.FullPath.ToString();
return FileFullPath;
}
}
Code in the application
using MPCFilePickerMauiLibrary;
namespace MPC_MassPropertiesCalculator_MAUIapp.Views;
public partial class MPCFileDemo : ContentPage
{
public MPCFileDemo()
{
InitializeComponent();
}
private async void MenuFlyoutItem_Clicked(object sender, EventArgs e)
{
string? filePath = await PickTxtFile.GetFilePathAsync();
if (File.Exists(filePath))
{
await DisplayAlert("File Path", $"File Path is: {filePath}", "OK");
}
else
{
await DisplayAlert("File Path", "Usre did not select a file", "OK");
}
}
}
Output result image.

using a function from Page Object in Protractor

I have this code in my afterEach block that works to console log the page source for a failed spec. But I want to move it to another class instead.
afterEach(function () {
const state = this.currentTest.state;
if (state === 'failed') {
browser.driver.getPageSource().then(function (res) {
console.log(res);
});
}
});
but when i try to use the following in another class, i get 'Property 'currentTest' does not exist on type 'HelperClass'. How do i declare the currentTest property?
import { browser, } from 'protractor';
export class HelperClass {
public getSource() {
const state = this.currentTest.state;
if (state === 'failed') {
browser.driver.getPageSource().then(function (res) {
console.log(res);
});
}
}
}
Try like below
test file:
const helper = new HelperClass(); // create object for class
afterEach(async ()=> {
const state = this.currentTest.state;
await helper.getSource(state);
});
Class File
import { browser, } from 'protractor';
export class HelperClass {
public getSource(state:any) {
if (state === 'failed') {
browser.driver.getPageSource().then(function (res) {
console.log(res);
});
}
}
}
Here we are sending the State from your test file.
Hope it helps you

Calling mongodb insert,find functions from another class in react native , returns undefined

This is my first class where I defined all db functions.
import React,{Component} from 'react';
var Datastore = require('react-native-local-mongodb')
, db = new Datastore({ filename: 'asyncStorageKey', autoload: true });
export default class RDDBManager {
static dbmanager = null;
static getInstance() {
if (RDDBManager.dbmanager == null) {
RDDBManager.dbmanager = new RDDBManager();
}
return this.dbmanager;
}
constructor () {
}
//insert items
insertItem(item){
var json = item.toJsonString();
console.log("Inside insertItem ::: "+json);
db.insert(json,function(err,newDos){
return newDos;
});
}
//read single item
readItem(itemId){
db.findOne({ id: itemId }, function (err, doc) {
return doc;
});
}
//read all items
readAllItems(){
db.find({}, function (err, docs) {
return docs;
});
}
getModalData(modalName) {
this.readAllItems();
}
//update
updateItem(itemId){
db.update({ id: itemId }, { $set: { system: 'solar system' } }, { multi: true }, function (err, numReplaced) {
});
}
//delete item
deleteItem(itemId){
db.remove({ id: itemId }, {}, function (err, numRemoved) {
return numRemoved;
});
}
}
But,when I try to call these functions from another class,the data is undefined.
loadDataFromDB() {
var items = RDDBManager.getInstance().readAllItems();
console.log("Items ======>>>>>> "+items);
}
the value of items is undefined.
This is because you are not doing things right, Your readallitems is async in nature so you have to do something like this:-
//read all items
readAllItems(callback){
db.find({}, function (err, docs) {
callback(docs);
});
}
And For calling something like this:-
loadDataFromDB() {
RDDBManager.getInstance().readAllItems(function(items){
console.log("Items ======>>>>>> "+items);
});
}
Alternatively, you can use promise or Async await also.

Events in Ionic v4

I'm using Ioni v4Beta and I'm traying to update the sidemenu when the user is login.
I search but the usual solution is use Events:
Ionic 3 refresh side menu after login
https://ionicframework.com/docs/api/util/Events/
But in the new version I don't find it, and I don't know how to do it
https://beta.ionicframework.com/docs/api
Thanks a lot, but I finally find how to import it:
import { Events } from '#ionic/angular';
Example on how to do it with subjects:
export const someEvent:Subject = new Subject();
export class ReceivingClass implements OnDestroy, OnInit
{
private someEventSubscription:Subscription;
public OnInit():void{
someEventSubscription = someEvent.subscribe((data) => console.log(data);
}
public onDestroy():void{
someEvent.unsubscribe();
}
}
export class SendingClass implements OnInit
{
public OnInit():void{
setTimeout(() => {
someEvent.next('hi');
}, 500);
}
}
Are you aware that Ionic v4 events will be deprecated soon?
I was also trying to update the sidemenu when a user logs in as well, so i tried using: import { Events } from '#ionic/angular';
However I got a warning referring me to this link https://angular.io/guide/observables#basic-usage-and-terms which I failed to follow because am not that familiar with observables.
After much research I found that I can still use events but I had to import them from angular's router directive.
This was my code before:
/* import was */
import { Events } from '#ionic/angular';
import { Storage } from '#ionic/storage';//ignore this import if doesn't apply to your code
/* inside the class */
constructor(
private events: Events,
private storage: Storage
) {
this.events.subscribe("updateMenu", () => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
console.log("User logged in.");
let user = userData.user;
console.log(user);
}
else {
console.log("No user found.");
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
changes i made that actually got my code working and deprecation warning gone:
/* import is now */
import { Router,RouterEvent } from '#angular/router';
import { Storage } from '#ionic/storage';//ignore this import if it does't apply to your code
Rest of code
constructor(
public router: Router,
public storage: Storage
){
this.router.events.subscribe((event: RouterEvent) => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
/*console.log("User logged in.");*/
let user = userData.user;
/*console.log(this.user);*/
}
else {
/*console.log("No user found.");*/
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
I got the idea after seeing this https://meumobi.github.io/ionic/2018/11/13/side-menu-tabs-login-page-ionic4.html. I hope my answer can be useful.
Steps to resolve the issue
import events in login page and in sidemenu view
In login page, after login success do your logic to publish the events.
for eg:
this.authService.doLogin(payload).subscribe((response) => {
if (response.status) {
this.storage.set('IS_LOGGED_IN', true);
this.events.publish('user:login');
}
}, (error) => {
console.log(error);
});
In sidemenu view, create a listener to watch the events 'user:login'
for eg:
this.menus = [];
// subscribe events
this.events.subscribe('user:login', () => {
// DO YOUR LOGIC TO SET THE SIDE MENU
this.setSidemenu();
});
// check whether the user is logged in or not
checkIsUserloggedIn() {
let isLoggedIn = false;
if (this.storage.get('IS_LOGGED_IN') == '' ||
this.storage.get('IS_LOGGED_IN') == null ||
this.storage.get('IS_LOGGED_IN') == undefined) {
isLoggedIn = false;
} else {
isLoggedIn = true;
}
return isLoggedIn;
}
// to set your sidemenus
setSidemenu() {
let isUserLoggedIn = this.checkIsUserloggedIn();
if(isUserLoggedIn) {
this.menus = ['Home', 'Aboutus', 'Contactus', 'My Profile', 'Logout'];
} else {
this.menus = ['Login', 'Home', 'Aboutus', 'Contactus'];
}
}

How to return an array of ParseObject from CloudCode call

There is a parse CloudCode function created as such:
Parse.Cloud.define("getCurrentEvents", function(request, response) {
var TimedEvent = Parse.Object.extend("TimedEvent");
var query = new Parse.Query(TimedEvent);
query.greaterThan("expiresOn", new Date());
query.find({
success: function(results) {
response.success(results);
},
error: function(error) {
response.error("There was an error while looking for TimedEvents");
}
});
});
It returns an array of TimedEvent, as shown in the curl test here:
{"result":[{"expiresOn":{"__type":"Date","iso":"2014-07-31T22:31:00.000Z"},"playMode":"Normal","tableId":"Carnival","objectId":"J1LSO3EnKi","createdAt":"2014-07-28T21:48:22.983Z","updatedAt":"2014-07-28T22:32:14.304Z","__type":"Object","className":"TimedEvent"}]}
When trying to access it from Unity SDK however, I get a "cannot convert to destination type" exception with the following line:
System.Threading.Tasks.Task<Parse.ParseObject[]> task =
Parse.ParseCloud.CallFunctionAsync<Parse.ParseObject[]> ("getCurrentEvents", parameters);
I also tried
System.Threading.Tasks.Task<IEnumerable<Parse.ParseObject>> task =
Parse.ParseCloud.CallFunctionAsync<IEnumerable<Parse.ParseObject[]>> ("getCurrentEvents", parameters);
with the same (lack of) results. What kind of signature is the SDK expecting?
Have you tried something like this (without IEnumerable?):
Threading.Tasks.Task<Parse.ParseObject> task = Parse.ParseCloud.CallFunctionAsync<Parse.ParseObject>("getCurrentEvents", parameters);
But better yet, you could extend ParseObject to create your own TimedEvent class in Unity, like this:
[ParseClassName("TimeEvent")]
public class TimeEvent : ParseObject
{
[ParseFieldName("expiresOn")]
public DateTime expiresOn
{
get { return GetProperty<DateTime>("expiresOn"); }
set { SetProperty(value, "expiresOn"); }
}
[ParseFieldName("playMode")]
public string playMode
{
get { return GetProperty<string>("playMode"); }
set { SetProperty(value, "playMode"); }
}
[ParseFieldName("tableId")]
public string tableId
{
get { return GetProperty<string>("tableId"); }
set { SetProperty(value, "tableId"); }
}
// any other fields you want to access
}
Then you can query your data like this:
IEnumerator getTimedEvents(Dictionary<string, object> parameters)
{
var cloudTask = Parse.ParseCloud.CallFunctionAsync<TimeEvent>("getCurrentEvents", parameters);
while (!cloudTask.IsCompleted)
yield return null;
if (cloudTask.IsCanceled || cloudTask.IsFaulted)
{
// handle error
}
else
{
TimeEvent t = cloudTask.Result;
// do stuff with t
}
}
P.S. Don't forget to register your Parse class somewhere (I usually do it in the Awake() of an early GameObject). In your case, you would do it like this:
Parse.ParseObject.RegisterSubclass<TimedEvent>();