Application insights not logging Requests,Page views, Custom events - azure

I have promoted my app from dev to stage environment App Service.
But now I cant see Page views,Custom events getting logged in my Application Insights which was logging fine in Dev.
Why is this happening?
Note:
1.I am using correct Instrumentation Key
2.Track calls are 200
3.The app is a Teams tab app built using React and using React plugin for App insights(working fine in dev)
4.Runtime Stack for dev environment was Node.Js but for Stage is .NET (Is this causing this issue?)
Also Note I have gone through all scenarios in Troubleshooting guide

Did the issue resolved for you ?
If not,
Ensure that you install the npm package for React.js,
npm install #microsoft/applicationinsights-react-js
npm install #microsoft/applicationinsights-web
Initialize a connection to Application Insights:
in AppInsights.js
import { ApplicationInsights } from '#microsoft/applicationinsights-web';
import { ReactPlugin } from '#microsoft/applicationinsights-react-js';
import { createBrowserHistory } from 'history';
const browserHistory = createBrowserHistory({ basename: '' });
const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
extensions: [reactPlugin],
extensionConfig: {
[reactPlugin.identifier]: { history: browserHistory }
}
}
});
appInsights.loadAppInsights();
export { reactPlugin, appInsights };
And then Wrap your component with the higher-order component function to enable Application Insights on it:
import React from 'react';
import { withAITracking } from '#microsoft/applicationinsights-react-js';
import { reactPlugin, appInsights } from './AppInsights';
// To instrument various React components usage tracking, apply the `withAITracking` higher-order
// component function.
class MyComponent extends React.Component {
...
}
// withAITracking takes 4 parameters ( reactPlugin, Component, ComponentName, className)
// the first two are required and the other two are optional.
export default withAITracking(reactPlugin, MyComponent);
This will help you track all the requests, page views and custom events.
Also take a look at this doc for more reference : Javascript React SDK Plugin

Turns out it was a problem with the Application Insights instance itself and not in code or App service configuration.
When ever you face such problem where problem is not with code or App service,please reach out to your organization's support Team.

Related

Datastax Astra netlify and react-app, should I use nodejs client or REST API for serverless functions?

I built a simple react app with "create-react-app" and I want to use serverless functions with netlify.
I use DataStax Astra Cassandra DB for that purpose, and created a netlify.toml config and .env variables (for the Database) inside my react project.
I set up a serverless functions folder for netlify:
const { createClient } = require('#astrajs/collections')
// create an Astra client
exports.handler = async function (event, context) {
try {
const astraClient = await createClient({
astraDatabaseId: process.env.ASTRA_DB_ID,
astraDatabaseRegion: process.env.ASTRA_DB_REGION,
applicationToken: process.env.ASTRA_DB_APPLICATION_TOKEN,
})
// const basePath = `/api/rest/v2/KEYSPACES/${process.env.ASTRA_DB_KEYSPACE}/collections/messages`
const messagesCollection = astraClient
.namespace(process.env.ASTRA_DB_KEYSPACE)
.collection('messages')
const message = await messagesCollection.create('msg1', {
text: 'hello my name is Marc!',
})
return {
statusCode: 200,
body: JSON.stringify(message),
}
} catch (e) {
console.error(e)
return {
statusCode: 500,
body: JSON.stringify(e),
}
}
it works when I run netlify dev , then my .env variables are injected into the .js file.
However, I am wondering if I should use the nodejs datastax collections here, or the REST API functions from datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html)? Because with react, it's essentially running in the browser or not? I am wondering why this still works with nodejs (because its not a nodejs environment with react, or is it?)
I am getting access to my functions via localhost:8888/.netlify/functions/functionName is this served from a nodejs server or is it browser stuff?
it works when I run netlify dev , then my .env variables are injected into the .js file. However, I am wondering if I should use the nodejs datastax collections here, or the REST API functions from datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html)? Because with react, it's essentially running in the browser or not?
Correct - you would expose your Astra credentials to the world if you connect to your database directly from your React app.
I am wondering why this still works with nodejs (because its not a nodejs environment with react, or is it?) I am getting access to my functions via localhost:8888/.netlify/functions/functionName is this served from a nodejs server or is it browser stuff?
Netlify functions run serverside so it is safe to connect to Astra in your function code. Here's an example: https://github.com/DataStax-Examples/todo-astra-jamstack-netlify/blob/master/functions/createTodo.js

React native and IBM Watson

I have been using expo to build a react native app and would like to integrate an IBM Watson chatbot onto my platform. When I import the module however I receive a lot of error messages as core node modules such as os and fs seem to be missing, but aren't downloaded with node.js for some reason. When I try and add these manually, the HTTPS module is missing the index.js file. Is there any way for me to find this file or resolve this problem another way?
It's not completely clear from your question but I shall assume that you are using the Node SDK for Watson Assistant. This is designed to be run in a Node.js environment which a react native JavaScript bundle is not (with or without expo). That's why you are missing key libraries like os and fs which the Node SDK expects. Installing fs won't resolve your problem because it also expects a Node.js environment to work, hence why there are react native specific fs libraries that are able to use ios and android code to interact with the file system of the phone.
What you should be attempting is running the Node SDK on an independent server and running simple api requests using libraries like axios or for more robust production systems graphql so that your architecture will approximate this high level design.
a high level architecture diagram which shows a phone connected by an arrow reading axios api request to another box labelled cloud hosted server. From this box another arrow labelled Node SDK is pointing to another box labelled Watson Assistant
Web applications are similarly limited. The code run on the user's browsers can't directly use the Watson Assistant SDK, these requests to Watson Assistant need to be run by a server. There is an example starter Watson Assistant web application that does this. If you run or host this application you can use the same server for your requests (although bear in mind this simple app and shared traffic probably isn't scalable for anything but a proof of concept).
So rather than running the api requests to Watson Assistant directly you run them to this domain of the server and then the necessary endpoint. The server in the example app is set up to accept requests to start the session at <your domain>/api/session and to send messages at <your domain>/api/message
You optionally can run direct api calls to Watson Assistant from a react native app without the SDK. It's not advisable because you would need to store your private keys on the device where they could be viewed by anyone.
Here is a functional component that is able to complete api calls direct to Watson Assistant using the v1 of the message tool without the SDK. BUT IT IS NOT ADVISED BECAUSE I MUST STORE MY KEYS INSECURELY.
import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import axios from 'axios';
import base64 from 'react-native-base64';
const workspace = ''; //replace with your own workspace id
const key = ''; //replace with your own key
const encodedKey = base64.encode(`apikey:${key}`);
// the following url will be different depending on where you host your Watson Assistant
// this is for Frankfurt as an example hence eu-de in the domain name
const assistantInstance =
'https://api.eu-de.assistant.watson.cloud.ibm.com/instances/<This is your own>/v1'; //replace with your own
const ExampleComponent = () => {
const [response, setResponse] = useState('');
const sendMessage = () => {
axios
.post(
`${assistantInstance}/workspaces/${workspace}/message?version=2018-09-20`,
{
input: { text: 'This is the message' },
},
{
headers: {
Authorization: `Basic ${encodedKey}`,
'Content-Type': 'application/json',
},
},
)
.then((data: any) => {
console.log(data);
setResponse('Got response');
})
.catch((err: any) => {
console.log(err);
setResponse('Got an error');
});
};
return (
<View>
<Text>{response}</Text>
<TouchableOpacity
onPress={() => {
sendMessage();
}}
>
Send message
</TouchableOpacity>
</View>
);
};
export default ExampleComponent;
The next complication you will find is that you will need to add code to store the context returned in the response otherwise your state is lost. Your body would end up looking something like
{
input: { text: 'This is the message' },
context: savedContextObject
},
The newer version of the API has a stateful version which you may want to use instead. You can use this axios as a pattern for constructing whatever requests your prefer.
For the third and final time PLEASE DO NOT SAVE TO THE JS FILE YOUR API KEY as I do here. This is just as an example and for proof of concepts. Anyone who downloads your app will be able to unzip your apk and read these strings in your generated JS bundle unencrypted!

Angular Service with Azure Cosmos

I am really new to Angular. I am trying to create a service which i want to consume in my angular component. While doing so i am getting below error.
Below is my code which i am writing
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http';
import { CosmosClient } from '#azure/cosmos';
import {Observable,of} from 'rxjs'
#Injectable({
providedIn: 'root'
})
export class ApiService {
databaseId='dbName';
containerId='Container Name';
constructor() { }
public async getProjects():Promise<Observable<any>>{
const endpoint = "https://AAAA.documents.azure.com:443/";
const key = "==";
const client = new CosmosClient({ endpoint, key });
const database = client.database(this.databaseId);
const container = database.container(this.containerId);
const querySpec = {query: "SELECT * from c where c.Category=\"Details\""};
const { resources:items } = await container.items.query(querySpec).fetchAll();
return of(items);
}
}
Any help is really appreciated.
There is an exception to every rule, but the use cases for connecting to a DB directly from a web browser are pretty close to zero. By doing so, you lose all fine grained control over what a user can do in your database and the only way to revoke access is to rotate your keys. You may not currently have anything in your database that is sensitive, but it is still considered bad practice.
For this reason, the CosmosDB library is compatible with NodeJS as a server-side framework. Whether or not it works with front end frameworks like Angular or React are incidental. There are some large changes in how Angular compiles projects in version 9, and it looks like the Cosmos client is not compatible with the new Ivy compiler.
You do have a couple options here.
(recommended) Use an API layer between your database and your front end. You can use Node to keep it within Javascript. If you are running on Azure, there are services like Azure Functions that can make this even easier to implement securely, or you can run it from the same App Service, VM, or whatever hosting solution you are using.
Disable the new Ivy compiler.You can do this by adding aot: false in your angular.json

What is the right way of implementing a service in an Angular application?

Last year when I worked on building an Alexa skill, this is how I used to define a service:
service.ts
var createReport = function(variable,callback){
//Method code here
};
module.exports.createReport = createReport;
And this is how I used to call it in the :
app.ts
const service= require('../service.ts');
servicee.createReport (name,function=> {
//Callback function code here
}
)
This year I am building an Angular app in which services manipulation is different from the previous example.
Here's an example for state management service in my angular app:
service.ts
import { Injectable } from "#angular/core";
import { BehaviorSubject } from "rxjs";
#Injectable()
export class listOfThirdPartiesService {
constructor() {}
/************************************************** */
private listOfThirdPartiesValuesSource = new BehaviorSubject<string[][]>([
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
['','','','','','','',''],
]);
currentListOfThirdParties = this.listOfThirdPartiesValuesSource.asObservable();
/************************************************************************ */
}
And this is how I I call it in the :
app.ts
import { listOfThirdPartiesService } from "../services/listOfThirdPartiesService.service";
Also in app.module.ts, I have to declare it in the providers.
So my questions are:
What is the difference between the two ways of implementing a service?
And in which use cases can I use the first one and the second one?
Take a look at this documentation on Services
You can simple create a service in Angular 2+ and above using the below command
ng generate service your-service
or simply
ng g s your-service
The above command automatically register your service into the module as well.
Now if you specify your service in providers in NgModule like as shown below, then it will be available to all components in that NgModule
#NgModule({
providers: [
YourService,
],
...
})
But if you want to use your service specifically only for some components the specify it under providers in your component
#Component({
selector: 'app-test',
templateUrl: './app-test.component.html',
providers: [ YourService ]
})
The first method, to me, seems to be just defining a function. This provides a functionality, and a closure. This isn't really a "Service".
The second method (using the #Injectable() decorator), make the class, well, injectable. This means that it will play with Angular's DI system. You can inject it into other Angular classes (Components and Services) by passing it in the constructor along with the typescript type. The Angular compiler will look to its providers and find a service of this type and you will have access to that exact instantiation of the class. You say that you are providing this in the AppModule. This means you are providing this in the root of the app and this service will be a singleton. In effect this method is the most convenient. I try to explain this with images in my half baked blog.
With the first method, if you care about how many instantiations you have, and which instance you are interacting with at any given time, you will need to watch how you are importing it, and if you are code-splitting.

session management using core node.js without express.js

How to handle/create middleware for server side session management in a core node.js /non express.js project. I can find modules for express based project but not for core node.js. Please suggest me any modules or middleware for non express.js project.
Session management can be implemented via database (MySQL, MongoDB, Redis etc.) or some local cache.
The main logic behind sessions - is object with data.
So you can provide user on first interaction with some random id, like uuid.
And save it to some module, which looks like this:
class OwnSession(){
constructor(){
this.sessions = {};
}
getUser(sessionId){
return this.sessions[sessionId];
}
setUser(sessionId, userData){
if(this.sessions[sessionId]){
Object.assign(this.sessions[sessionId], userData);
return;
}
this.sessions[sessionId] = userData;
}
}
// We export here new OwnSession() to keep singleton across your project.
module.exports = new OwnSession();
And then, in any module you require OwnSession and call the method.

Resources