I've been migrating my Direct Line Bot from Webchat v3 to v4.
The new version demands the use of tokens rather than the Direct Line secret in the calling page.
Here is the code (index.html) used to start the bot:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Question:
What code do I need to write to generate the token in other to be called by https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token ??
Realize it's got to be something like
POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer SECRET
but I don't know if it's got to be a php, js or other type of file to work.
Thanks in advance
I used php to solve this. You could give it a try.
<?php
$botSecret = '<your secret>';
$response = wp_remote_get( 'https://webchat.botframework.com/api/tokens', array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
$header = $response['headers'];
$token = $response['body'];
}
?>
<script type="text/javascript">
var webChatToken = <?php echo $token; ?>;
</script>
I had the same issue yesterday, I just post it here in case it helps anyone in the future. If you change your code to this it should work:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token',
{ method: 'POST', headers: { Authorization: 'write your direct line secret here' }});
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
You had to add the authorization in the header of the post request to generate the token in the async function. Unfortunately this might not be obvious from Microsoft's documentation on how the generate the token
What you need to do is implement some kind of server side logic using whatever technology you're most comfortable with that uses the secret, which is kept only on your server, to generate a new token by making an HTTP request to the DirectLine channel as you point out above. Then, in your web page's start up logic, you make a request to get that token and, with the token, initialize the direct line instance in the web page. Using this approach ensures that nobody external ever gets a hold of your secret.
So, there is no one type of file to "make it work". You will need to choose Node, PHP, ASP.NET or any other server technology and implement it in the way you would any other HTTP request handler.
This article will help in understanding the authentication concepts and APIs and here's a blog post that shows how you might do it with ASP.NET and Node.
Related
I'm trying to use fetch() to POST React form data to my Rails API, but my error within the Network tab of chrome dev tools returns:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /undefined/cars</pre>
</body>
</html>
The error in the console states the "Unexpected token '<'" indicating that my response is being sent as HTML instead of JSON, but I'm not sure why it's not converting.
Here's my fetch request:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Could someone please help me with this? Thanks.
Figured it out. I had to run npm i dotenv, then add a .env file to my root and add the following:
REACT_APP_API_URL=http://localhost:3001/
In my mvc net core app I need to implement drag&drop files uploader. I found Dropzone js and hoping to use it in my purposes. But can't configure it, I need to allow it upload ony zip files.
My code:
<div class="row">
<div class="col-md-9">
<div id="dropzone">
<form action="/Home/Upload" class="dropzone needsclick dz-clickable" id="uploader">
<div class="dz-message needsclick">
Drop files here or click to upload.<br>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function () {
Dropzone.options.uploader = {
paramName: "file",
maxFilesize: 256,
acceptedFiles: "application/zip,application/octet-stream,application/x-zip-compressed,multipart/x-zip,.zip",
maxFiles: 1
};
});
</script>
Also of course I have controller:
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
var uploads = Path.Combine(_environment.ContentRootPath, "Uploads");
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return RedirectToAction("Index");
}
But still, application allows to upload any file with any MIME type. Where is a problem?
Also restriction of maxFiles isn't working too - it allows me to upload infinite count of files.
You can use option of dropzone.js name acceptedfile.
Dropzone.options.myAwesomeDropzone = {
....
acceptedFiles: ".zip",
....
};
According to the documentation (https://www.dropzonejs.com/#configuration), you can do it like this:
Dropzone.options.myAwesomeDropzone = {
accept: function(file, done) {
if (file.name.endsWith !== ".zip") {
done("Naha, you don't.");
}
else { done(); }
}
};
A function that gets a file and a done function as parameters. If the
done function is invoked without arguments, the file is "accepted" and
will be processed. If you pass an error message, the file is rejected,
and the error message will be displayed. This function will not be
called if the file is too big or doesn't match the mime types.
Edit:
Here is a fiddle to demonstrate it: http://jsfiddle.net/behyzjng/15/
Set acceptedFiles: 'application/zip' in defaultOptions
Here are the documentation for you to work on Dropzone.js:
Github: https://github.com/dropzone/dropzone
Docs: https://docs.dropzone.dev
check all avaliable options at https://github.com/dropzone/dropzone/blob/main/src/options.js
check the desired extensions allowed and write the MIME type as a value of acceptedFiles at https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Working solution here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
<title>Document</title>
</head>
<body>
<style>
.my-dropzone {
width: 100%;
height: 100px;
border: 1px dashed;
display: flex;
align-items: center;
justify-content: center;
}
</style>
<div class="my-dropzone">
Drag and drop zip files here, or click here to upload.
</div>
<script>
// Dropzone.js
// Github: https://github.com/dropzone/dropzone
// Docs: https://docs.dropzone.dev
// check all avaliable options at
// https://github.com/dropzone/dropzone/blob/main/src/options.js
const defaultOptions = {
url: "/file/post",
// check the desired extensions allowed and write the MIME type as a value of acceptedFiles at
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
acceptedFiles: 'application/zip'
};
// Dropzone has been added as a global variable.
const dropzone = new Dropzone("div.my-dropzone", defaultOptions);
</script>
</body>
</html>
I have this code (see end of question) and all I have to do is put in my access token, the thing is I've downloaded the p12 file and whenever I try to open it, I just get some Microsoft certificate program that doesn't tell me the stuff I need, how do I go about getting inside this p12 file to get the access token that its asking for?
Thanks.
<!doctype html>
<html lang="en">
<head>
<title>Google Charts</title>
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
gapi.analytics.ready(function() {
var ACCESS_TOKEN = '???'; // obtained from your service account
gapi.analytics.auth.authorize({
serverAuth: {
access_token: ACCESS_TOKEN
}
});
var data = new gapi.analytics.report.Data({
query: {
ids: 'ga:????????',
metrics: 'ga:users,ga:sessions,ga:bounceRate',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'output': 'dataTable',
}
});
data.execute();
data.on('success', function(response) {
var data = new google.visualization.DataTable(response.dataTable);
var formatter = new google.visualization.NumberFormat({fractionDigits: 2});
formatter.format(data, 1);
var table = new google.visualization.Table(document.getElementById('test'));
table.draw(data);
});
});
google.load('visualization', '1', {'packages':['table']});
google.setOnLoadCallback(table);
</script>
</head>
<body>
<div>
<div id="embed-api-auth-container"></div>
<div id="test"></div>
</div>
</body>
</html>
Don't try and use a service account with the embed API. Use normal oauth 2 as shown in the documentation Embeded API Getting started
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'Insert your client ID here';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
If you must use a service account I suggest you drop the embedded API and use a scripting language like PHP directly with the reporting API.
I have implemented plupload using a ColdFusion backend script (available at https://gist.github.com/1116037).
The url attribute in the uploading page is url : '../upload.cfc?method=upload',
This simply calls a function within the cfc script. It works fine. This script also creates a variable called 'response' to hold information uploaded files.
The problem I am having is accessing the information held in the 'response' variable.
I would like to display that information in a table after the all the files have been uploaded to the server.
I am using the queue_widget for my needs’ think that an event (onComplete) needs to be triggered to call a function to process the information in variable, but I don't know how to do this.
I need to access the information held in the 'response' variable, preferably in ColdFusion code. Has anyone managed to get plupload working with ColdFusion yet?
Any help, guidance or coding would be appreciated.
Here is the full code I have used:
This is the main page - queue_widget.cfm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plupload - Queue widget example</title>
<link rel="stylesheet" href="../../js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../../js/plupload.js"></script>
<script type="text/javascript" src="../../js/plupload.flash.js"></script>
<script type="text/javascript" src="../../js/jquery.plupload.queue/jquery.plupload.queue.js"></script>
</head>
<body>
<h1>Queue widget example</h1>
<p>Shows the jQuery Plupload Queue widget and under different runtimes.</p>
<div style="float: left; margin-right: 20px">
<h3>Flash runtime</h3>
<div id="flash_uploader" style="width: 700px;">Your browser does not have Flash installed!</div>
</div>
<br style="clear: both" />
<cfoutput><cfset mnum=6></cfoutput>
<script type="text/javascript">
$(function() {
// Setup flash version
$("#flash_uploader").pluploadQueue({
// General settings
runtimes : 'flash',
url : '../upload.cfc?method=upload',
max_file_size : '1mb',
max_file_count: <cfoutput>#mnum#</cfoutput>, // You can limit the num of files that can be uploaded by manipulating the mnum variable above
unique_names : false,
multiple_queues : true,
multi_selection: true,
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
],
init : {
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
if (up.files.length > <cfoutput>#mnum#</cfoutput>) {
up.removeFile(file);
}
});
if (up.files.length >= <cfoutput>#mnum#</cfoutput>) {
$('#pickfiles').hide('slow');
}
},
FilesRemoved: function(up, files) {
if (up.files.length < 1) {
$('#pickfiles').fadeIn('slow');
}
}
},
resize : {width : 300, height : 10000, quality : 90}, // forces images to be resized to a width of 300px if wider than 300px
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, response){
function IsJson(response) {
alert('Response from server: ' + response.file); // for testing only
counter++
var newRow = '<tr><td><input type="hidden" name="file_'+counter+'" value="'+response.file+'">'
newRow += 'Label the file: '+response.file+' <input type="text" name="filename_'+counter+'"></td></tr>'
$("#detail").append(newRow)
}});
};
</script>
<div id="results"></div>
<table id="detail">
</table>
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
</body>
</html>
This the backend processing page - upload.cfc
<cfcomponent>
<cffunction name="upload" access="remote" returntype="struct" returnformat="json" output="false">
<cfscript>
var uploadDir = expandPath('/uploads/'); // should be a temp directory that you clear periodically to flush orphaned files
var uploadFile = uploadDir & arguments.NAME;
var response = {'result' = arguments.NAME, 'id' = 0};
var result = {};
</cfscript>
<!--- save file data from multi-part form.FILE --->
<cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="overwrite"/>
<cfscript>
// Example: you can return uploaded file data to client
response['size'] = result.fileSize;
response['type'] = result.contentType;
response['saved'] = result.fileWasSaved;
return response;
</cfscript>
</cffunction>
</cfcomponent>
You can try the above example here: [url] www.turn2cash.co.uk/plupload/examples/jquery/queue_widget.cfm [/url]
As mentioned above, the script works well with uploading (in this case) upto 6 images as determined by the mnum variable. What I need help with is with how to access the uploaded files (with page refresh) and be able to manipulate them.
I have setup an example (using cffileupload) of what I am after here [url] www turn2cash.co.uk/a/index.cfm [/url]
Although this works fine, it requires a page refresh, which is what I am trying to avoid.
Please provide any help you can.
Added 7 september 2012
I have tried both methods suggested by Miguel but did not achieve any positive outcomes. They actually caused the UI not to sow at all. However I found this and tried it:
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, Response){
alert('Response from server: ' + Response.response);
});
};
</script>
I now get an alert displaying:
Response from server: {"saved":true,"result":"home.png","id":"0","size":"5988","type":"image"}
This at least prooves that the cfc script is working and the 'response' varialable is being returned. I still have no idea how to make use of this information as I have no knowledge of jquery, ajax or javascript. Please help if you can.
The link that I posted before has the example code. Sorry to post this as an answer but since I have no rep I cannot comment.
I think part of your confusion is in the request processing. You have this line of code at the bottom of your example.
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
That will never fire because the coldfusion page is processed before you make the javascript ajax call to the server for the file upload. You will need to handle the response in javascript.
Are you seeing this alert from the attachCallbacks function?
alert('Response from server: ' + response.file); // for testing only
been searching without finding a solution for me,
I need to be able to send and recive current tab URL when the Chrome extension is shown:
this is My popup.html:
<html>
<head>
<style>
div, td, th { color: black; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script>
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
</script>
<script src="http://keepyourlinks.com/API/public/chrome.js"></script>
</head>
<body style="width: 650px;height:600px;margin:0px;paddin:0px;width:100%;">
<span class="keeper">keep</span>
</body>
</html>
An then, in my webiste, on a chrome.js file i try:
$("body").ready(function(){
var url = getURL_please();
$(".keeper").click(function(event) {
event.preventDefault();
window.open("http://keepyourlinks.com/API/public/compartir_link.php?url="+url,'about to keep', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=600');
});
});
But URL is allways: Undefined
Any idea what i'm doing wrong?
Thanks a lot!
HI Toni,
Google Chrome Extensions use an Asynchronous API,
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
The above will always return null. If you want to make it work correctly.
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
var url = tab.url;
// Do what you want here.
});
}
You would need to the windows open after you you fetch the url. One question though, what do you mean "in your website"? You cannot run Chrome Extension JavaScript directly on your website, so I assume via "Content Script" (most likely, just making sure)?
If your using a Content Script, why would you need to use the Extension API? You can just use window.location.href