Dialogflow .NET core, C# - detect intent not working - asp.net-core

I want to invoke DetectIntent programatically.
I am using Google.Cloud.Dialogflow.V2 - Client libraries.
using Google.Cloud.Dialogflow.V2;
var query = new QueryInput
{
Text = new TextInput
{
Text = text,
LanguageCode = "en-us"
}
};
var sessionId = "1234567890";
var agent = "myAgentName";
var creds = GoogleCredential.FromFile("JSONFileName");
Channel channel = new Channel(
SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
DetectIntentRequest request = new DetectIntentRequest
{
SessionAsSessionName = new SessionName("smartresort-facebook-bot-fgvjh", "1111"),
QueryInput = query,
};
DetectIntentResponse response = client.DetectIntent(request);
With above code I am getting error as below
I am already using same JSON file in node js code and it is working fine. So in nodejs detect intent code is working fine. I am trying to do the same in .NET core.
After this I have tried another code snippet.
var client = SessionsClient.Create();
var response = client.DetectIntent(
session: new SessionName("smartresort-facebook-bot-fgvjh", "1234567890"),
queryInput: new QueryInput()
{
Text = new TextInput()
{
Text = text,
LanguageCode = "en-us"
}
}
);
I am not trying to write fulfillment which would be called after the intent is detected. I am trying to write the code before intent is detected. So I want to give a call to detect intent and then process the response based on which intent is detected.

Check my answer here, It is an example on how to integrate Dialogflow with .Net Core based on a working sample. If you still have more questions let me know and I will be happy to help!

Related

Power App - generate PDF

I got an assignment to see if I can make power app that will generate some PDF file for end user to see.
After through research on this topic I found out that this is not an easy to achieve :)
In order to make power app generate and download/show generated pdf I made these steps:
Created power app with just one button :) to call Azure function from step 2
Created Azure function that will generate and return pdf as StreamContent
Due to power app limitations (or I just could not find the way) there was no way for me to get pdf from response inside power app.
After this, I changed my Azure function to create new blob entry but know I have problem to get URL for that new entry inside Azure function in order to return this to power app and then use inside power app Download function
My Azure function code is below
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, Stream outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
stream.CopyTo(outputBlob);
// result.Content = new StreamContent(stream);
// result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
// result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(pdfFile);
// result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// result.Content.Headers.ContentLength = stream.Length;
return result;
}
I left old code (the one that streams pdf back under comments just as reference of what I tried)
Is there any way to get download URL for newly generated blob entry inside Azure function?
Is there any better way to make power app generate and download/show generated PDF?
P.S. I tried to use PDFViewer control inside power app, but this control is completely useless cause U can not set Document value via function
EDIT: Response from #mathewc helped me a lot to finally wrap this up. All details are below.
New Azure function that works as expected
#r "Microsoft.WindowsAzure.Storage"
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
using Microsoft.WindowsAzure.Storage.Blob;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, CloudBlockBlob outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
outputBlob.UploadFromStream(stream);
return req.CreateResponse(HttpStatusCode.OK, outputBlob.Uri);
}
REMARKS:
Wee need to add "WindowsAzure.Storage" : "7.2.1" inside project.json. This package MUST be the same version as one with same name that is in %USERPROFILE%\AppData\Local\Azure.Functions.Cli
If you change your blob output binding type from Stream to CloudBlockBlob you will have access to CloudBlockBlob.Uri which is the blob path you require (documentation here). You can then return that Uri back to your Power App. You can use CloudBlockBlob.UploadFromStreamAsync to upload your PDF Stream to the blob.

what is the equivalent converted vb.net code for following c# code

I have tried various code converters but it is giving me error while running the application.
myCustomer.Card = new StripeCreditCardOptions() { TokenId = token };
myCustomer.Card = New StripeCreditCardOptions() With { .TokenId = token }

MobileFirst 7.0 image upload and javascript adapter parameters size limit

It seems that there is already a similar question on so and we meet with it indeed.
We are calling adapters and sending encoded base64 strings to the backend. All things works fine with tiny pictures less than 1Mb. But if the image size is larger (eg. 4Mb, just a ordinary Photo from the end-user's iPhone album), it stucked with adapter invoking errors. I also find clues after debugging that, in condition with uploading large image the adapter will never step into the backend business logic but in the condition the tiny pics can.
Some of the code snippets could be like below:
var base64Str = "";
var reader = new FileReader();
reader.onload = function(e) {
base64Str = e.target.result;
preview.setAttribute('src', base64Str );
uploadImage(picUuid, base64Str);
}
//calling the HTTP image upload adapter
function uploadImage(uuid, base64Data){
WL.Logger.debug("base64Data:" + base64Data);
var invocationData = {
adapter : 'ImageUploadAdapter',
procedure : 'uploadImage',
parameters : [uuid, base64Data]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : uploadImageSuccess,
onFailure : uploadImageFailure,
});
}
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
alert(srcData);
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
uploadImage(srcData);
}
fileReader.readAsDataURL(fileToLoad);
}
}
//calling the HTTP image upload adapter
function uploadImage(srcData){
WL.Logger.debug("srcData:" + srcData);
var invocationData = {
adapter : 'ImageUploadAdapter',
procedure : 'uploadImage',
parameters : [srcData]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : uploadImageSuccess,
onFailure : uploadImageFailure,
});
}
MobileFirst Platform 7.0 introduced Java adapters in addition to the existing JavaScript adapters.
With Java adapters there is no such limitation for the file sizes that can be operated on when using JavaScript adapters and data can be handled as Binary rather than encoded to base64, etc.
In other words, there is no multi-part support in JavaScript adapters, whereas in Java adapters (that are based on the JAX-RS specifications) you can.
You can read more about it here:
https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/server-side-development/adapter-framework-overview/

Marketo rest Api create lead

I have a question about this create/Update leads API, http://developers.marketo.com/documentation/rest/createupdate-leads/.
There is no sample code for C# or JAVA. Only ruby available. So I have to try it by myself. But I always get null return from the response.
Here is my code:
private async Task<CreateLeadResponseResult> CreateLead(string token)
{
string url = String.Format(marketoInstanceAddress+"/rest/v1/leads.json?access_token={0}", token);
var fullUri = new Uri(url, UriKind.Absolute);
CreateLeadResponseResult createLeadResponse = new CreateLeadResponseResult();
CreateLeadInput input = new CreateLeadInput { email = "123#123.com", lastName = "Lee", firstName = "testtesttest", postCode = "00000" };
CreateLeadInput input2 = new CreateLeadInput { email = "321#gagaga.com", lastName = "Lio", firstName = "ttttttt", postCode = "00000" };
List<CreateLeadInput> inputList = new List<CreateLeadInput>();
inputList.Add(input);
inputList.Add(input2);
CreateLeadRequest createLeadRequest = new CreateLeadRequest() { input = inputList };
JavaScriptSerializer createJsonString = new JavaScriptSerializer();
string inputJsonString = createJsonString.Serialize(createLeadRequest);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(fullUri.OriginalString, inputJsonString).ConfigureAwait(false);
// I can see the JSON string is in the message body in debugging mode.
if (response.IsSuccessStatusCode)
{
createLeadResponse = await response.Content.ReadAsAsync<CreateLeadResponseResult>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return createLeadResponse;}
//get null here.
Thank you.
-C.
The best way to debug this is to capture the exact URL, parameters and JSON that are submitted by your app and try submitting those manually via a tool like Postman (Chrome plug-in) or SOAP UI. Then you see the exact error message, which you can look up here: http://developers.marketo.com/documentation/rest/error-codes/. Based on that you can update your code. I don't know much about Java, but this is how I got my Python code to work.
Your example code was really helpful in getting my own implementation off the ground. Thanks!
After playing with it for a bit, I realized that the JavaScriptSerializer step is unnecessary since PostAsJsonAsync automatically serializes whatever object you pass to it. The double serialization prevents Marketo's API from processing the input.
Also, I agree with Jep that Postman is super helpful. But in the case of this error, Postman was working fine (using the contents of inputJsonString) but my C# code still didn't work properly. So I temporarily modified the code to return a dynamic object instead of a CreateLeadResponseResult. In debugging mode this allowed me to see fields that were discarded because they didn't fit the CreateLeadResponseResult type, which led me to the solution above.

log4javascript - obtain history of messages programmatically?

I'm looking into using a javascript logging framework in my app.
I quite like the look of log4javascript (http://log4javascript.org/) but I have one requirement which I'm not sure that it satisfies.
I need to be able to ask the framework for all messages which have been logged.
Perhaps I could use an invisible InPageAppender (http://log4javascript.org/docs/manual.html#appenders) to log to a DOM element, then scrape out the messages from that DOM element - but that seems pretty heavy.
Perhaps I need to write my own "InMemoryAppender"?
There's an ArrayAppender used in log4javascript's unit tests that stores all log messages it receives in an array accessible via its logMessages property. Hopefully it should show up in the main distribution in the next version. Here's a standalone implementation:
var ArrayAppender = function(layout) {
if (layout) {
this.setLayout(layout);
}
this.logMessages = [];
};
ArrayAppender.prototype = new log4javascript.Appender();
ArrayAppender.prototype.layout = new log4javascript.NullLayout();
ArrayAppender.prototype.append = function(loggingEvent) {
var formattedMessage = this.getLayout().format(loggingEvent);
if (this.getLayout().ignoresThrowable()) {
formattedMessage += loggingEvent.getThrowableStrRep();
}
this.logMessages.push(formattedMessage);
};
ArrayAppender.prototype.toString = function() {
return "[ArrayAppender]";
};
Example use:
var log = log4javascript.getLogger("main");
var appender = new ArrayAppender();
log.addAppender(appender);
log.debug("A message");
alert(appender.logMessages);