Coldfusion - Refreshing Page When A Database Record Updates - loops

Good day,
Let me describe my problem :
Scenario :
User 1 has a coldfusion webpage, containing 6 alerts as html elements populated using a database. User 1 is constantly monitoring this page for changes.
A user on a different computer (different session) logs into a admin console and add's a 7th element and inserts it into the database.
The database contains a field that changes from 0 to 1 as soon as an alert is added and inserted into the database.
The webpage of User 1 not has to dynamically refresh or update with the 8th alert.
Problem :
I am struggling to run a async loop that queries the database permanently for the record that tells it there is a change, while not freezing the rest of the page.
Solution :
I need to run a cfquery to check the isUpdated field in the database.
That cfquery needs to be run every minute.
As soon as the cfquery returns a 1, the page should refresh which in turn will populate the new alert as well.

Can be done through sockets, and you do not have to check the availability of a new record every minute.
You can also do it with javascript/jquery:
<script>
var lastAlert = '#lastAlert#'; //last at the time of loading the page
setInterval(function() {
lastAlert = isUpdated(lastAlert);
}, 60000);
function isUpdated(lastAlert){
res = lastAlert;
$.ajax({
url: 'checkAlerts.cfm', //in this file do check for changes in the database. should return the number of the last alert
type: 'POST',
data: {lastAlert:lastAlert},
cache: false,
success:function(res){
if(res > lastAlert){
//your code if there is a new entry
alert('a new entry has been added');
}
}
});
return res;
}
</script>
I did not check the code! But I hope you understand how to proceed.

Related

SalesForce query returns results in Query Editor, but returns null from APEX code in Lightning component

I'm completely new to SalesForce and have inherited a report that's not working. Please excuse any incorrect terminology, since I'm learning about all this as I go. The report has three prompts: states, years, and members. All dropdowns are supposed to populate with data returned from functions in an APEX class. State, which populates from a picklist, and years, which is populated with a loop, work fine. Members, which populates from a SQL query, returns nothing. If I run the report without any prompts selected (which should return an unfiltered list of results from a SQL query), it also returns nothing. Both of the SQL queries return data when I execute them directly in the query editor in the developer console, but they return nothing when called from the APEX functions.
Here's the initialization code from the Lightning controller:
doInit: function (component, event, helper) {
var action = component.get('c.getTrcAccounts');
action.setCallback(this, function (response) {
var state = response.getState();
if (state === 'SUCCESS' && component.isValid()) {
component.set('v.trcAccList', response.getReturnValue());
}
helper.getLocationState(component, event);
helper.getYear(component, event);
});
$A.enqueueAction(action);
},
Here are the two helper functions referenced in that code:
getLocationState: function (component, event) {
var action = component.get('c.getLocationState');
action.setCallback(this, function (response) {
var state = response.getState();
if (state === 'SUCCESS') {
component.set('v.LocationStateList', response.getReturnValue());
}
});
$A.enqueueAction(action);
},
getYear: function (component, event) {
var action = component.get('c.yearsOptions');
action.setCallback(this, function (response) {
var state = response.getState();
if (state === 'SUCCESS') {
component.set('v.LocationYearList', response.getReturnValue());
}
});
$A.enqueueAction(action);
}
Here is the code from the APEX class that returns the data for those three prompts:
Global class DataTableLocations {
#AuraEnabled
Global static List<TRC_Account__c> getTrcAccounts(){
set<string> trcAccountSet = new set<string>();
List<TRC_Account__c> traccList = new List<TRC_Account__c>();
for(TRC_Account__c trcacc : [SELECT Id, Name from TRC_Account__c WHERE TRC_Member__c = True order by Name limit 50000]){
if(!trcAccountSet.contains(trcacc.Name)){
trcAccountSet.add(trcacc.Name);
traccList.add(trcacc);
}
}
if(traccList.size()>0){
return traccList;
}
else{
return null;
}
}
#AuraEnabled
Global static List<string> getLocationState(){
List<string> options = new List<string>();
//options.add(new SelectOption('SelectAll', 'Select All'));
for( Schema.PicklistEntry f : Location__c.Physical_Address_State__c.getDescribe().getPicklistValues()) {
options.add(f.getValue());
}
return options;
}
#AuraEnabled
Global static List<string> yearsOptions() {
List<string> options = new List<string>();
date OldDate= date.today().addYears(-18);
integer oldyear=OldDate.year();
for( integer i=0; i<19 ;i++) {
options.add(string.valueOf(oldyear));
oldyear++;
}
return options;
}
}
If I run SELECT Id, Name from TRC_Account__c WHERE TRC_Member__c = True order by Name limit 50000 directly in the query editor window in the developer console, I get 7 results. However, if I output the response.getReturnValue() for getTrcAccounts in the doInit function, it's null.
Any help is greatly appreciated, as we're in a bit of a time crunch in conjunction with a site redesign. I'm told these reports were working at one point, but no one knows when they stopped working, and we inherited this code from a different company that did the original development. Thank you!
UPDATE:
In case it helps, this is the code in the lightning app that I think is used on the public page:
<aura:application extends="ltng:outApp" access="GLOBAL" implements="ltng:allowGuestAccess">
<aura:dependency resource="c:SearchBinReceiptsByYear"/>
</aura:application>
Edit
Right, it's a public page, it's called "Salesforce Sites". It's exposed to whole world without having to log in. These have special security in place because most of the time you don't want to expose data like that. At best you'd display contact us form, maybe some documents to download, product catalog... It's all very locked down, default is to ban everything and then admin decides what's allowed. It's bit unusual to have a Visualforce page + Aura component but ok, it happens.
You (and any other internal user) can see the results if you'd access this page from within salesforce. Something like https://mydomain.my.salesforce.com/apex/SearchBinReceiptsByYear and for you the page will work fine, "just" not outside of salesforce.
When exposed like that on the web - there's no logged in user. There's special "[Site Name] Guest User", you can see them if you search "Sites" in Setup. It has a special profile, also with [Site Name] in it. And nasty thing is - it doesn't show on the list of Users or Profiles.
Your code broke when Salesforce (auto)activated a critical update. Probably this one: https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_networks_secure_perms_guests.htm There are some good resources on the net if you Google "Secure Object Permissions for Guest Users", for example https://katiekodes.com/salesforce-spring-20-guest-user/
Ask your system administrator colleague or read up a bit about sharing rules.
You'll have to go to Setup -> Sharing Rules. There's a checkbox that caused your stuff to break and you can't untick it.
Scroll down to your TRC Account object and hit "New". You'll need to create something like this, but with your criteria (TRC Member equals true)
Save, wait a bit (it might take a while to recalculate the sharing, you'll get an email) and try the page.
If it still doesn't work you'll have to check the Guest user's profile, it might need permissions to Read TRC Accounts and their Name field.
If it's Salesforce Sites - try this to find it: https://help.salesforce.com/articleView?id=000334554&type=1&mode=1
If it's a Customer Portal, Community, Digital Experience (they renamed the product few times) - try with https://help.salesforce.com/articleView?id=sf.rss_config_guest_user_profile.htm&type=5
Original answer
It looks like it's running OK because accounts (members?) are fetched first and in that fetch's callback (what to do when data comes back from server) you have helper.getLocationState, helper.getYear. And you wrote that these populate OK. It's not the best performance code but it should get the job done.
In no specific order...
Does the whole thing work OK for sysadmins? Or is it broken for everybody? If it works for sysadmins it might be something to do with sharing, your sysadmin should know (Setup -> Sharing settings is where you control who can see what. Maybe "mortals" are not allowed to see any data? Typically sysadmins bypass it. As a quick & dirty test you can modify the class definition to global without sharing class DataTableLocations but it's a really ugly hack.
What happens if you open DeveloperConsole (upper right corner) while running this component, do you see any errors in the logs? What happens if in the console you go Debug -> Open ExecuteAnonymous and run this piece of code:
System.debug(DataTableLocations.getTrcAccounts());
Does it return something? Throw error?
You can go to Setup -> Debug Mode, tick the checkbox next to your user and save. This slows the system down a bit but lets you debug the javascript better. You can then sprinkle some debugger; or console.log statements in the source code and view what happens in your browser's console (Ctrl+Shift+J in Chrome, Ctrl+Shift+I in firefox). For example
action.setCallback(this, function (response) {
var state = response.getState();
debugger;
console.log(state);
console.log(component.isValid());
console.table(response.getReturnValue());
if (state === 'SUCCESS' && component.isValid()) {
component.set('v.trcAccList', response.getReturnValue());
}
console.log(component.get('v.trcAccList'));
debugger;
helper.getLocationState(component, event);
helper.getYear(component, event);
});
How's the trcAccList variable actually used in the "cmp" file, in the HTML-like file? Maybe it's being set all right and contains 7 records but it's not displayed right?

Background Geolocation Plugin: Track location and update database every 5 minutes

I'm currently developing a mobile app using AngularJS / Ionic 3.
I need to track at all time, if my users are within a radius of 100m of a certain geolocation (let's call it "Home Location". I need to know at all time which user is at his home location, and who is not (even when the app is running in background or is closed/ terminated).
I thought to realize this, using the Ionic Native Background-Geolocation plugin and the cordova-plugin-background-geolocation. My plan was, to check the users geolocation every 5 minutes and compare it to the home.
Case 1) If the distance between the two locations is < 100m I know the user is "at home". I would then update the user node in my database (Firebase) to mark the user as isAtHome: true and add a current timestamp.
Case 2) If the user is not within 100m of his home location I would mark him as isAtHome: false and add a current timestamp.
I need to update my database even in case the user didn't move, because I need to know that I received a current signal. Otherwise I don't know if he didn't move or turned off his smartphone, for example.
If I want to know, who of my users is at his home location, I would check the isAtHome-attributes and if they are set to true, I would check the timestamp to be sure that I have up-to-date data and the data was written within the last 15 minutes.
I tried many different things, but I'm not sure how to realize this with the Cordova Background Geolocation Plugin and if it's even possible.
My question is:
Is it possible to check the users geolocation every 5 minutes (even in background / terminated state) and call a function that updates my firebase DB accordingly? As described, I need to receive the location even if the user didn't move within the last 5 minutes.
If it isn't possible: Does anybody have an idea, of how to approach the requirements on another way?
Thank you very much for your help!
As described in the cordova-plugin-background-geolocation says, you can configure an interval in milliseconds for the plugin to get the location, see this example from the plugin github page:
backgroundGeolocation.configure(callbackFn, failureFn, {
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
url: 'http://192.168.81.15:3000/locations',
httpHeaders: { 'X-FOO': 'bar' },
maxLocations: 1000,
// Android only section
locationProvider: backgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
interval: 60000, // <-- here
fastestInterval: 5000,
activitiesInterval: 10000,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
notificationIconColor: '#FEDD1E',
notificationIconLarge: 'mappointer_large',
notificationIconSmall: 'mappointer_small'
});
The case is this interval property works only for Android. I would sugest a workaround like this:
public getLocation: boolean = true; // CREATE A BOOLEAN TO KNOW IF YOU CAN GET LOCATION
backgroundGeolocation.start( // i've never used this plugin, so i'm assuming this is what starts de background watcher
() => {
if(getLocation == true){
this.getLocation = false; // SET TO FALSE SO IT DON'T DO YOUR FUNCTION THE NEXT TIME IT GETS THE LOCATION
// DO YOUR CODE TO SAVE AND CHECK YOUR DATA
// IT'S BETTER IF YOU USE A PROMISE, ASYNC/AWAIT FOR THE SAVING CODE
yourSavingCodeFunction().then(() => {
setTimeout(()=>{
// AFTER 5 MINUTES, SET THE GETLOCATION TO TRUE SO IT CAN DO YOUR FUNCTION AGAIN
this.getLocation = true;
}, 500000);
});
}
},
(error) => {
// Tracking has not started because of error
// you should adjust your app UI for example change switch element to indicate
// that service is not running
}
);
If you haven't thought about your cases 1 and 2 we can work on this too. Hope this helps or can give you some ideas :D

Angularjs 1: delete an item, but item still exist until refresh

Here is my simple angular 1 app.
Source code here.
Basically it is a copy of this.
I am able to do CRUD operations. The issue is that, when I delete a record. It redirects back to the home page. The record I deleted is still here. If I refresh the page, it is gone.
Is it a way to delete a record and then after redirect, I should see the latest list?
Update 1:
Unfortunately, it is still unresolved. Something strange that it seems the promise in resolve is cached. I added a few console.log inside the code. You can see the code flow. Open chrome developer tool to see it.
i review you code , the problem is here:
this.deleteContact = function(contactId) {
var url = backend_server + "/contacts/" + contactId;
// actually http delete
return $http.delete(url)
.then(function(response) {
return response;
}, function(response) {
alert("Error deleting this contact.");
console.log(response);
});
}
if you have service to manage your contact use there to call your server to delete the contact.
the reason you cannot delete without refresh is:
your delete from DB but not from angular array.
must review (update the scope (array))
your code is hard to read , i have suggestion for you, using:
broserfy , watchify
lodash
and backen use mvc
You delete it remotely but not locally. So you can see result only after refreshing (only after you requesting updated data from server). You need to update your local contacts after you succeed on server side.
$scope.deleteContact = function(contactId) {
Contacts.deleteContact(contactId).then(function(data){
...
//DELETE YOU LOCAL CONTACT HERE
...
$location.path("/");
});
}
I didn't look deeply into your code, so I can't say how exactly you should do it, but as I see you keep your local contacts in $scope.contacts in your ListController.

$scope not updating after passing to new view with $location.path

I have a simple CRUD I put together with Angularjs. From a product list display I pass the user to a new view template for the "Create New" form.
The form processes fine and updates the database. I then pass the user back to the list display using "$location.path(url)".
For some reason when the list page displays, the changes do not appear in the $scope and you have to refresh the page to see the changes.
Sample code:
$scope.acns = acnFactory.query()
.$promise.then(function (data) {
$scope.acns = data;
});
the above displays the list of items.
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
The above POSTs the new product then redirects to the list page (/acn)
My assumption is that the list page will reprocess or watch the changes to the $scope but the view does not update.
The problem is most probably here:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn);
$location.path('/acn');
}
creating a product most certainly consists in sending an HTTP request to the server. This is asynchronous. This means that acnFactory.create() returns immediately after the request has been sent. Not after the response has been received.
So, this code sends the request to create the product and immediately goes to the page which lists the products. The GET request sent to get the product list is thus sent almost at the same instant as the one used to create the new product. The two requests are handled concurrently by the server, and the returned list contains the list without the new product, which is being created in a separate transaction.
You need to wait for the response to come back, and make sure it's successful, before going to the product list. Assuming the service returns a promise, as it should do:
$scope.createAcn = function () {
$scope.acn.isActive = true;
acnFactory.create($scope.acn).then(function() {
$location.path('/acn');
});
};

Constantly update the view angularJs

I would like to update the view even if the change happened from a different computer without refreshing the page.I tried to set interval and call my api every ten seconds,clear my cache.The problem here is that every ten seconds i would have to reload all my data and for the view to be update i should switch states.Is there a better way to handle this?
im managed to resolve the issue.I created a function that check if the data from server is equal with the data from the model and if not i update the cache without deleting it and the model.
this.refresh = function(){
apiService.someFunction(false) //the false is parametr for cache
.then(function(someValue) {
if(someValue.length !== vm.model.length){ //check if the model is equal with the data from database
var cache = $cacheFactory.get('$http')
var get = cache.get('URL'); //getting the cache
var data = angular.toJson(someValue); //turn response from then to Json
get[1] = data; //changing the cache data
vm.model= someValue; //changing the model data
}
})
}

Resources