I implemented Application Insigths in the frontend applciation and I want to disable/enable it based on a variable that can change over the lifetime of the applications. (e.g. user declined Application Insights consent => Disable Telemetry)
What I tried is:
appInsights.appInsights.config.disableTelemetry = true
however if I try to enable it back setting disableTelemetry =false this is not working anymore.
Is anything else that I need to make to persist this change or is there another way of doing this?
You could use a telemetry filter for that:
var filteringFunction = (envelope) => {
if (condition) {
return false; // Do not send telemetry
}
return true; // Do send the telemetry
};
Register the filter like this:
appInsights.addTelemetryInitializer(filteringFunction);
While Peter's answer is correct, I have different approach where instead of using telemetry filters we can stop the application insights object itself from starting to log to app insights.
Here in the following code based on the value of the variable a it will start the app insight service.
So, we will run appInsights.start(); only for a particular for value of variable a.
import { createRequire } from "module";
const require = createRequire(import.meta.url);
let appInsights = require('applicationinsights');
appInsights.setup("<Your connection String>")
.setAutoCollectConsole(true, true);
var a = 10 ;
if(a==10)
{appInsights.start();}
console.log("Hello World ");
Here I am running the code twice but with different value of variable a.
Here in application insights one log appear.
Related
Given a browser Single Page Application
When using AppInsights JS SDK v2.5.3
Then I want a CustomServiceName to be sent with ALL requests.
a) Should the custom properties be on the envelope.data, env.data.baseData or envelope.data.properties ?
It appears to change depending on the type of call made.
b) Can I set the CustomServiceName on the operation context instead of EVERY request instead?
Currently we are using this
var telemetryInitializer = (envelope) => {
envelope.tags["ai.application.ver"] = "1.2.3";
if (envelope.data) {
envelope.data["CustomServiceName"] = "MyName";
if (envelope.data.properties) {
envelope.data.properties["CustomServiceName"] = "MyName";
}
}
};
aisdk.addTelemetryInitializer(telemetryInitializer);
Based on https://github.com/microsoft/ApplicationInsights-JS#telemetry-initializers
a) envelope.data is the base of the model and setting new properties directly on this object may not be ingested properly, and env.data.baseData will vary depending on the type of data you send. envelope.data.properties should exist on all telemetry types and allows you to send whatever custom data along with your telemetry you wish. envelope.data.properties["CustomServiceName"] = "MyName"; is the correct implementation.
b) Using a telemetry initializer is the best way to achieve this- adding a property to each request is one of the use cases for them. The context has a small number of specific data points, and the list isn't customizable. Depending on the rest of your setup, Cloud Role may fit, but you will still need to use a telemetry initializer to set it.
I have an android application I developed, that allows the sign up of users. I wrote a firebase cloud function that triggers when a User is created, to generate a 5-digit random integer value for the user who just signed up and it stores the generated code in firebase real time database in the following structure.
MainProject
|
|-Codes
|-UniqueUID_1
|-code:72834
|-UniqueUID_2
|-code:23784
The function that I deployed in order to make sure that the code generation is in the backend, is as seen below. There is a value "checker" which is initialised as 0. I use this value to determine when to exit the while loop. Basically I want the function to generate a 5-digit random value, then check the real time database if that generated value exists in all entries under "Codes", then if it does not exist, append it to the Codes under the relevant UID. If it exists, checker remains zero and the loop continues.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var checker = 0;
exports.createUserCode = functions.auth.user().onCreate(event => {
while (checker == 0){
var newRand = getUserCode(89999,10000);
var userObject = {
uCode : newRand
};
//run a db query to strategically check value generated
return admin.database().ref("Codes/").orderByChild("uCode").equalTo(newRand).once("value",snapshot => {
if (!snapshot.exists()){
checker = 1;
//add uCode into respective uid slot under Codes
console.log(""+newRand+" : "+event.uid);
return admin.database().ref('Codes/' + event.uid).set(userObject);
}else{
checker = 0;
console.log("uCode "+newRand+" exists");
console.log("uCode generation failed for: "+event.uid);
}
});
}
});
function getUserCode(size, add){
return Math.floor(Math.random()*size+add);
}
I tested it and it worked fine. I thought the problem was solved. However, on the 7th to 11th trial, it gave me a Function returned undefined, expected Promise or value error. I tried it again after a while, and it generated the code fine. Some one else tested it and it brought the same error.
How can I fix this issue to ensure it always works? Thanks in advance.
It's really not clear to me what this function is supposed to do, and the top-level while loop doesn't make sense to me. However, I can see there are a few things wrong with what this code is doing.
First of all, it's depending on the global state checker too heavily. This value will not be the consistent for all function invocations, because they all won't be running on the same server instance. Each running server instance will see a different value of checker. Please watch this video series for more information about how Cloud Functions runs code.
Second of all, when checker has a value of 1 when the function starts, the function will do exactly what the error message says - it will return undefined. It should be pretty easy to see how this happens by reading the code.
To fix this, I suggest first coming up with a clear description of what this function is supposed to do when invoked. Also, I would strongly suggest eliminating dependency on global variables, unless you are absolutely certain you understand what you're doing and the effect they have.
I had the same problem a while ago. ESLint won't allow the function to complete because it evaluates whether every part of your code returns a promise.
From what i can see the first part of the if does return something. Try returning a boolean in the else block.
if (!snapshot.exists()){
checker = 1;
//add uCode into respective uid slot under Codes
console.log(""+newRand+" : "+event.uid);
return admin.database().ref('Codes/' + event.uid).set(userObject);
}else{
checker = 0;
console.log("uCode "+newRand+" exists");
console.log("uCode generation failed for: "+event.uid);
return false;
}
Using Nativescript I want to be able to decrement the icon badge number when specific actions are done in the app.
I've started with this code (example):
if (app.ios) {
app.getNativeApplication().applicationIconBadgeNumber = 5;
}
I've read that for iOS 10+ I need to get an authorization from the UNUserNotificationCenter. I tried using an app delegate when the app starts to ask for the authorization and it doesn't seem like I can have access to the authorization class from Nativescript.
I tried looking for plugins and can't seem to find any ...
If anyone knows how I could access the Authorization api or even deal with icon badge update from NativeScript it would be appreciated.
You could use the nativescript-local-notifications for requesting permissions.
I made some progress, in my AppDelegate I updated to:
appDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (application, launchOptions) {
var center = coreUtils.ios.getter(UNUserNotificationCenter, UNUserNotificationCenter.currentNotificationCenter);
center.delegate = this;
const authorizationOptions = UNAuthorizationOptions.Badge;
center.requestAuthorizationWithOptionsCompletionHandler(authorizationOptions, (granted, error) => {
if(!error) {
application.applicationIconBadgeNumber = 5;
} else {
console.log("Error", error);
}
});
Now the problem is that when I open the app, the applicationIconBadgeNumber gets set to 0. I was able to test that by putting an event listener on the applicationDidEnterBackground event and setting applicationIconBadgeNumber to 5. I was then able to see the badge icon. Now I have to figure out why the applicationIconBadgeNumber gets set to 0 on app open.
I have written firebase cloud function to trigger on update record. sometimes I am not getting the same record which is updating. I am adding my code below.Please check attached image also.
exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}/userResponse').onUpdate(event => {
return admin.database().ref(`/Notification/${event.params.userId}/${event.params.notificationId}`).once('value').then(function (snapshot) {
var notification = snapshot.val();
if (!notification) {
console.error("Notification not found on notification update");
return;
};
I can also get Notification object from the parent but I want to know issue best approach and the problem with this code.
this is error log
this is database structure
This is my 1st post here please let me know if need more information.
Thanks
You don't have to call once within the Function since it is already returning the data at the location you are listening to, just listen to the parent node.
So you should do like:
exports.onNotificationUpdate = functions.database.ref('/Notification/{userId}/{notificationId}').onUpdate(event => {
const notification = event.data.val();
if (notification === null) {
console.error("Notification not found on notification update");
return null;
//actually this would only be called in case of deletion of the Notification
} else {
//do something with the notification data: send Android notification, send mail, write in another node of the database, etc.
//BUT return a Promise
//notification const declared above is a JavaScript object containing what is under this node (i.e. a similar structure than your database structure as shown in the image within your post.)
}
});
I would suggest that you have a look at these three videos from the Firebase team:
https://www.youtube.com/watch?v=7IkUgCLr5oA&t=517s
https://www.youtube.com/watch?v=652XeeKNHSk&t=27s
https://www.youtube.com/watch?v=d9GrysWH1Lc
Also, note that Cloud Functions have been updated and the first line of your code shall be written differently if you are using a CF version above 1.0.0. See https://firebase.google.com/docs/functions/beta-v1-diff
I am trying to create a webapp on a node/couchdb/windows stack but get terribly stung by what seems to be a lack of experience.
In the database, there is a view that returns all users with passwords. Based on the tutorial for a blog I have tried to access the view through my node code.
Whenever I investigate the structure of the users or users variable, I get an undefined object.
The call to getDatabase() has been tested elsewhere and works at least for creating new documents.
function GetUser(login)
{
var users = GetUsers();
return users[login];
}
function GetUsers() {
var db = getDatabase();
var usersByEmail = [];
db.view("accounts", "password_by_email")
.then(function (resp) {
resp.rows.forEach(function (x) { usersByEmail[x.key] = x.value});
});
//usersByEmail['test'] = 'test';
return usersByEmail;
}
I am aware that both the use of non-hashed passwords as well as reading all users from the database is prohibitive in the final product - just in case anyone wanted to comment on that.
In case something is wrong with the way I access the view: I am using a design document called '_design/accounts' with the view name 'password_by_email'.
Your call to db.view is asynchronous, so when you hit return usersByEmail the object hasn't yet been populated. You simply can't return values from async code; you need to have it make a callback that will execute the code that relies on the result.