I would like to display a Google Analytics report in my web application. So far I have successfully Authenticated a user through OAuth with server side and I have successfully stored AccessToken and UserProfileId in my database Table.
Now I want to display Chart like Below:
Here is the script which I have taken from the source to display above chart: Embeded API demo
Script:
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: 'REPLACE WITH YOUR CLIENT ID', // i dont want to authenticate here as i have already done authentication.instead use access token to by pass this
authentication
});
So is it possible to not authenticate user with this script and still display google analytics chart for login user??
I have search on internet and I found below link somewhat useful in which Philip Walton answer is saying that it is possible: Google Analytics Embed API authentication
So if anybody have done this then please do provide any solution.
I found this option Embed API - Component Reference from this link which solved my issue:
I just needed to set the access_token:
gapi.analytics.auth.authorize({
serverAuth: {
access_token: 'XXXXXX'
}
});
try this using JavaScript sdk
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>
<hr/>
<section id="chart-1-container"></section>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'xxxxxxxxxxx-xxxx.apps.googleusercontent.com';
//gapi.analytics.auth.authorize({
// container: 'auth-button',
// clientid: CLIENT_ID,
//});
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': 'xx.xxxxx-xxxxxxxxxx_xxxxxxx'
}
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
// Step 5: Create the timeline chart.
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:users',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
type: 'LINE',
container: 'timeline'
}
});
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:xxxxxxxx', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:sessions,ga:users',
'dimensions': 'ga:date'
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
// Step 6: Hook up the components to work together.
gapi.analytics.auth.on('success', function(response) {
viewSelector.execute();
});
viewSelector.on('change', function(ids) {
var newIds = {
query: {
ids: ids
}
}
timeline.set(newIds).execute();
});
});
</script>
</body>
</html>
Related
I am passing the token and userid from the direct line web channel. I want to know How to receive those values in Bot side to show the userid or email passed from the direct line channel.
<html>
<div id="webchat" role="main" />
<head>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
</head>
<body>
<script>
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token: '#Model.Token' }),
userID: '#Model.UserId'
},
document.getElementById('webchat'));
</script>
</body>
<html>
You can create a store like below and add c custom data channelData , i have used simpleUpdatein Package for it
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
action = window.simpleUpdateIn(action, ['payload', 'activity', 'channelData', 'myData'], () => myDataObj);
}
return next(action);
}
);
Then inject this store to directline instance like
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({
token: '#Model.Token',
}),
userID: '#Model.UserId'
store,
}, document.getElementById('webchat'));
Now in Bot side you can access it under context object ,full path below
dialogContext.Context.Activity.ChannelData
You can also take a look at this Samplefor more info
I have an image for my bot, but it's not showing up in the webchat.
Is there any way to make it happen like the image in this link (https://cloud.githubusercontent.com/assets/979837/19395693/cbdf6ac2-91f3-11e6-8a48-ba533bf91dca.png) ?
My script for the bot is:
<script>
//Scrip for the webchat window
(function () {
var div = document.createElement("div");
document.getElementsByTagName('body')[0].appendChild(div);
div.outerHTML = "<div id='botDiv' style='height: 38px; position: fixed; bottom: 0; right: 1%; z-index: 1000; background-color: #fff'><div id='botTitleBar' style='height: 38px; width: 350px; position:fixed; cursor: pointer;'></div><iframe width='400px' height='600px' src='https://webchat.botframework.com/embed/xxx'></iframe></div>";
document.querySelector('body').addEventListener('click', function (e) {
e.target.matches = e.target.matches || e.target.msMatchesSelector;
if (e.target.matches('#botTitleBar')) {
var botDiv = document.querySelector('#botDiv');
botDiv.style.height = botDiv.style.height == '600px' ? '38px' : '600px';
};
});
}());
</script>
I would recommend you step away from the webchat channel iFrame option and utilize the BotFramework-WebChat tool, instead. The webchat channel is fine for simple deployments, but it isn't overly robust out-of-the-bot.
If you look over sample 04.b.display-user-bot-images-styling from the BotFramework-WebChat repo, you will see precisely how you can effect the bot/user avatars.
In short, you will include the web chat CDN into you html file, assign some basic styling for the web chat div, followed by the script that connects to and generates that actual web chat experience.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Avatar with images and initials</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--
For demonstration purposes, we are using the development branch of Web Chat at "/master/webchat.js".
When you are using Web Chat for production, you should use the latest stable release at "/latest/webchat.js",
or lock down on a specific version with the following format: "/4.1.0/webchat.js".
-->
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body { height: 100% }
body { margin: 0 }
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// To talk to your bot, you should use the token exchanged using your Direct Line secret.
// You should never put the Direct Line secret in the browser or client app.
// https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication
const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
const { token } = await res.json();
const styleOptions = {
botAvatarImage: 'https://learn.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
botAvatarInitials: 'BF',
userAvatarImage: 'https://github.com/compulim.png?size=64',
userAvatarInitials: 'WC'
};
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
styleOptions
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
This option does require generating a direct line token. This is accomplished by passing your direct line secret to the direct line /tokens/generate api and receiving a token back. The generated token is tied to the particular session so, as such, provides a certain level of security. Please don't use your secret in this setting.
The below is a node.js example and can be run as an independent app or incorporated into your existing bot as a separate api call made while the html page / web chat is loading. It wouldn't be hard to recreate an equivalent dotnet version.
server.post('/directline/token', (req, res) => {
// userId must start with `dl_`
const userId = (req.body && req.body.id) ? req.body.id : `dl_${Date.now() + Math.random().toString(36) }`;
const options = {
method: 'POST',
uri: 'https://directline.botframework.com/v3/directline/tokens/generate',
headers: {
'Authorization': `Bearer ${process.env.directLineSecret}`
},
json: {
User: {
Id: userId
}
}
};
request.post(options, (error, response, body) => {
if (!error && response.statusCode < 300) {
res.send({
token: body.token
});
} else {
res.status(500).send('Call to retrieve token from DirectLine failed');
}
});
});
Hope of help!
I wanted to ask you, if there is any possibility to get more than 20 full-res images from Instagram, using the API.
<script type="text/javascript">
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
});
feed.run();
Thank you in advance, Laurenz Strauch
It may be caused by pagination.
Add
<button id="load-more">
Load more
</button>
to your html. Every time you click on the button, feed.next() will be called and fetches more images if they exist.
<script type="text/javascript">
var loadButton = document.getElementById('load-more');
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
// every time we load more, run this function
after: function() {
// disable button if no more results to load
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
},
});
// bind the load more button
loadButton.addEventListener('click', function() {
feed.next();
});
// run our feed!
feed.run();
</script>
Try this code.
Is there an example out there which describes how to implement an OAuth2 authentication in the frontend based on Polymer.js?
I just found some examples that describe the procedure for AJAX, which is also part of the Polymer element set. So how to go on ahead?
I found a git repo here which have demo. So you can take a look.
<oauth-user></oauth-user>
<polymer-element name="oauth-user">
<template>
<oauth-authenticator id="authenticator" client_id="282331888208-06mufq54k942624lv803nlm6kvlq76fr.apps.googleusercontent.com" scopes="https://www.googleapis.com/auth/userinfo.profile" on-authenticated="{{authenticated}}"></oauth-authenticator>
<core-ajax auto id="ajax" url="{{url}}" headers="{{headers}}" handleAs="json" on-core-response="{{ajaxResponse}}"></core-ajax>
<p>{{greeting}}</p>
</template>
<script>
Polymer({
url: '',
greeting: '...',
authenticated: function(event){
var token = event.detail.token;
this.headers = {'Authorization': 'Bearer ' + token};
this.url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
},
ajaxResponse: function(event, response) {
this.greeting = 'Hello ' + response.response.name + '!';
}
});
</script>
</polymer-element>
You can see there're event handler so you can redirect user or update screen. There're also a url to get user info.
I try to create event handling...so i followed this video tutorial ..everything working perfect. but in last minute video when i try to show user name in list view its not updating in real time as list view but i checked console.log('users') each object i can get it from my console.... but in view no updates or no errors ......... what is error ?
This is video tutorial - LINK
<body>
<ul id="users">
<li v-repeat="user: users">#{{ user.name }}</li>
</ul>
<script src="https://js.pusher.com/3.0/pusher.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.20/vue.min.js"></script>
<script>
// (function () {
// var pusher = new Pusher('82355e6cc93e7a15d7d5', {
// encrypted: true
// });
//
// var channel = pusher.subscribe('test');
// channel.bind('App\\Events\\UserHasRegistered', function(data) {
// console.log(data);
// });
// })();
new Vue({
el: '#users',
data:{
users:[]
},
ready: function(){
var pusher = new Pusher('82355e6cc93e7a15d7d5', {
encrypted: true
});
pusher.subscribe('test')
.bind('App\\Events\\UserHasRegistered',this.addUser);
},
methods: {
addUser: function(user){
this.users.push(user);
}
}
})
</script>
</body>
The v-repeat directive is deprecated in version 1.0 and replaced with the v-for.
1.0 replaces the old v-repeat directive with v-for. In addition to providing the same functionality and more intuitive scoping, v-for provides up to 100% initial render performance boost when rendering large lists and tables!
http://vuejs.org/2015/10/26/1.0.0-release/#Faster-Initial-Rendering