ChatBot not working after Deploying on Azure - Internal server error - azure

I have deployed a chatbot with LUIS and QnA Maker. It works perfectly locally when I run it on Emulator. It loads up the adaptive cards at start of the chat and I get correct replies from LUIS.
However when I deploy the bot on Azure and test it on Web chat it gives the following error:
There was an error sending this message to your bot: HTTP status code InternalServerError
This is how my web.config looks like:
<configuration>
<appSettings>
<!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
<add key="BotId" value="BotLuis" />
<add key="MicrosoftAppId" value="9f9564ef-d627-450f-b943-98b7338c0f31" />
<add key="MicrosoftAppPassword" value="myapp-password" />
</appSettings>
I get the values for AppID and AppPassword from the Applications setting of the web bot I created on Azure. I know they are correct since I used these values to setup locally using Emulator.
I deploy the code from github to Azure. My bot loads up just fine (The adaptive cards show) on azure web chat but after that any input I give to it, whether it is interactive card or chat command, I get the above error.
The application Insight shows the following exception:
POST to BotLuis failed: POST to the bot's endpoint failed with HTTP status 500
Problem Id:System.Exception at Microsoft.Bot.ChannelConnector.BotAPI+d__31.MoveNext
The developers tool console shows this when I interact with the bot:
https://webchat.botframework.com/v3/directline/conversations/3NgflndFbpzCRDtnMdZpjf-g/activities 502 (Bad Gateway)
if you paste the above link in a browser this is what you will get:
{
"error": {
"code": "BadArgument",
"message": "Missing token or secret"
}
}
I am lost at this point. I can understand the problem but I don't know how to go forward. Am I supposed to add the messaging endpoint of my bot in my code somewhere?
A link to github repo of the code:here

Bot State Service retired on March 31st, 2018.
Therefore your sample is missing state storage when you run it on Azure, while it will work locally.
To make your sample work, simply add the following lines to your Global.asax.csfile.
protected void Application_Start()
{
RegisterBotDependencies();
GlobalConfiguration.Configure(WebApiConfig.Register);
var store = new InMemoryDataStore();
Conversation.UpdateContainer(
builder =>
{
builder.Register(c => store)
.Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
.AsSelf()
.SingleInstance();
builder.Register(c => new CachingBotDataStore(store,
CachingBotDataStoreConsistencyPolicy
.ETagBasedConsistency))
.As<IBotDataStore<BotData>>()
.AsSelf()
.InstancePerLifetimeScope();
});
}
Please note that this sample uses InMemory storage and is therefore not intended for production use. Following the blog post, you can easily switch over to Azure Table storage or CosmosDB.
I've cloned your repository, added these lines of code and deployed it to a new bot instance on Azure. Webchat test was successful.
Summary
Taken from above blog post.
We’ve been encouraging bot developers using the Bot Framework to use their own custom state service for a while. The default Bot Framework State service was intended for prototyping purposes only, and not designed to accommodate production bots. The state service will be deprecated on March 31, 2018 and will no longer be supported. Bot developers moving forward will be able to prototype their bots using temporary local memory storage as described in this article. Creating your own custom state service for your bot provides multiple benefits including improved latency and direct control over your bot’s conversation state and contextual user conversation state information, and we’ve provided multiple resources to guide you to do so. We appreciate the feedback we’ve been receiving from the bot developer community, which has helped us a lot in improving the Bot Framework as a whole. We also hope that we can continue helping you – the bot developer community, create better and better bot experiences for your users.

Related

instagram_graph_user_media & instagram_graph_user_profile permissions working only for test users

I have an app that displays user's instagram media(like some of the dating apps).
Also, my app has been reviewed successfully for permissions - instagram_graph_user_profile and instagram_graph_user_media and is in live mode.
But in the Facebook Developer Console, the instagram icon is not turning up green.
Please refer the screenshot.
https://drive.google.com/open?id=1VnMHLqjTf1oRbvcm2g8Ol80AfB3JqMOg
Flow to display the media is as follows.
1. My app ask users to authorize using
https://api.instagram.com/oauth/authorize?client_id=instagram-app-id&redirect_uri=redirect_uri&scope=scope&response_type=code&state=state
2. Above api responds with a code.Then backend calls -
https://api.instagram.com/oauth/access_token
with params - client_id, client_secret, code, grant_type, redirect_uri
3. Once I receive token from above API, I request long lived token from short-lived token using -
https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=xyz&access_token=abc
4. Using the long lived token, server requests user info using API -
https://graph.instagram.com/me?fields=id,username&access_token=abc
5. Using the same long lived token, server makes request to get user media using API -
https://graph.instagram.com/me/media?fields=id,media_type,media_url,username,caption,timestamp&access_token=abc
This flow works only for test users(Instagram test users who accepted invitation of being a tester in Instagram Developer Platform).
When non-test user tries to view media, on step 3, I get an error saying -
{ "error": {
"message": "Unsupported get request.",
"type": "IGApiException",
"code": 100,
"fbtrace_id": "A0A24rNXCScki9Ck-8J_55b" } }
Am I missing something?
This is how I see my Business API Settings.
Please refer the screenshot.
https://drive.google.com/open?id=1Dfdihf20krEcYEmoh8z43_a1T5UQStXr
Under my App review section, I do not see any relevant permission that needs to be reviewed again.
Edit 1 -
Note - My app is in beta mode (not yet live on play store).
Could this be the reason?
I just went through a similar process getting my app ready for the old API to officially depreciate. I finally found this— hope it helps:
https://developers.facebook.com/community/threads/2219648518091109/
"After your app has been approved, you can get the contract from your Business Manager. You need to do it on a Computer (mobile wont work) and have to be an Admin on the Business.
From your business Manager you just go to Business Info -> Business Contract (https://business.facebook.com/settings/info)
Please, let us others if this answer helped you!"
Thanks to Juanu for sharing!

Bot deployed on azure suddenly became non-responsive

I have a bot deployed on Azure using Bot Framework. Nothing was changed on the code. But today the bot became completely unresponsive. Any message I try to send results invariably in a "Couldn't Send. Retry?" message. Occasionally in past I could see the bot was slower to reply to one or other message, but this time is a different thing, the bot is completely mute. On inspecting the issues for web chat channel on azure dashboard I can see that the errors are all the same "There was an error sending this message to your bot: HTTP status code GatewayTimeout". What may I be doing wrong?
Just in case it is relevant, the bot uses LUIS services and also a database both deployed in azure. Tried to access these services separately and they are working fine with good response time. Anyway, I don't think the bot program reaches the point of trying to communicate with any of them. I doesn't even reach the first IDialogContext.PostAsync() which is the very first instruction on the StartAsync() method in the root dialog. Help with this much appreciated
the errors are all the same "There was an error sending this message to your bot: HTTP status code GatewayTimeout". What may I be doing wrong?
Firstly, I do a test with the following sample, and if the request take a long time to get response, which might cause " Gateway Timeout" issue. You can turn on Application Insights with your bot application to trace the request(s) sent from your bot, and check if some requests take too long time.
Example:
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
if (activity.Text.ToLower().Contains("timeout test"))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://xxxxx/api/values/xxx");
request.Method = "GET";
request.ContentType = "application/json";
//I set a 30s delay for returning response in my external api
var response = request.GetResponse();
string content = string.Empty;
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
}
activity.Text = content.ToString();
// return our reply to the user
await context.PostAsync($"API returned {activity.Text}");
}
else
{
// return our reply to the user
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
}
context.Wait(MessageReceivedAsync);
}
Test result:
Secondly, if your Bot Service pricing tier is free, please check if your bot service reached 10,000 messages/month limit (for Premium channels). In this SO thread, another community member reported reaching that limit would cause " Gateway Timeout" error.
Besides, if possible, you can create a new bot service on Azure portal and then publish your bot application to that corresponding new Azure web app that you specified as messaging endpoint, and check if your bot app can work as expected on new Azure environment.
Note:
I also checked the status history of Azure services and found:
6/27 RCA - App Service - West Europe
Summary of impact: Between 16:00 UTC on 27 Jun 2018 and 13:00 UTC on 28 Jun 2018, a subset of customers using App Service in West Europe may have received HTTP 500-level response codes, timeouts or high latency when accessing App Service (Web, Mobile and API Apps) deployments hosted in this region.
6/25 RCA - Multiple Services - South Central US
Summary of impact: Between 19:40 and 20:52 UTC on 25 Jun 2018, a subset of customers in South Central US may have experienced difficulties connecting to resources and/or 500-level errors hosted in this region. Virtual Machines may have rebooted unexpectedly. Impacted services included: Storage, Virtual Machines, Key Vault, Site Recovery, Machine Learning, Cloud Shell, Logic Apps, Redis Cache, Visual Studio Team Services, Service Bus, ExpressRoute, Application Insights, Backup, Networking, API Management, App Service (Linux) and App Service.
Not sure if above issue causes the problem, if you tried all approaches that you can do to troubleshoot the issue, but the issue with your bot service is still not mitigated, you can try to create support request to report it.
Try enabling [botauthentication] in message controller. Also try to open outgoing connection also from your IIS server to internet. By the way there can be some other problems as well like :
1)Your web.config file contains an App ID that does not match the one you posted.
2)Your server's time is incorrect. Tokens have 20 minutes of validity (5 minutes before the token was issued and 15 minutes after.) Is it possible your server time is different?
3)Your bot encountered a problem retrieving list of signing keys. Check to make sure you can access these URLs:
https://api.aps.skype.com/v1/keys
https://login.botframework.com/v1/.well-known/keys
You can also follow this issue to check if you're doing it correctly https://github.com/Microsoft/BotBuilder/issues/4389

Building SOAP Listener with Azure Functions

I am using Azure Functions to build some integrations between various systems. I new requirement is to respond to record updates in Salesforce. Some quick research yielded what seems like a good solution from the Salesforce side. Use Outbound messaging which can send SOAP requests on record modifications.
How to create Salesforce application that will send record to external web service when record created/changed(https://salesforce.stackexchange.com/questions/73425/how-to-create-salesforce-application-that-will-send-record-to-external-web-servi)
The challenge now is to be able create a SOAP listener in Azure Function. I have created basic HTTP Triggers for my other listeners. Is there anything "built-in" to Azure Functions that would allow me to easily consume the incoming SOAP request?
Salesforce has the basics for a solution based on a more traditional web service and an ASMX file but I am not sure if or how that can be applied in Azure Functions. (https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_om_outboundmessaging_listener.htm)
That notification is just a SOAP request that is made over HTTP, so really not too different than a regular HTTP trigger request.
Although you could just treat that as a plain request and parse the contents yourself, Azure Functions does expose the great WebHook support we get from ASP.NET WebHooks, and luckily, there is a Salesforce receiver that significantly simplifies this task.
DISCLAIMER: It's worth noting that although the receiver is technically enabled in Azure Functions, there's no official support for it yet, so you won't find a lot of documentation and help will be limited to what you get on SO and Forums. Official support to this and other receivers will hopefully be coming soon, which means documentation, templates and UI support will become available.
To get started, you need the following:
Create a new function, selecting the GenericWebHook - CSharp template (this works for node as well, but I'll focus on C# here.
Follow the steps outlined on the ASP.NET WebHooks integration with Salesforce post in order to create the outbound message. Here you want to use the Function Url given to you by the portal WITHOUT THE CODE QUERY STRING (having the code there wouldn't hurt, but the receiver does not use that information).
IMPORTANT: Get your Salesforce Organization ID, which will be used for authentication and is located under Administer > Company Profile > Company Information > Salesforce.com Organization ID and back in the Azure Functions portal, open the Keys panel, delete your default function key (not host key) and create a new key, named default (this name is important) using the Organization ID value you got from Salesforce.
Go to Integrate
On the integration page, select Advanced Editor on the upper right (as mentioned, there's no official support, so the UI does not expose this. We're putting our explorer hats on and venturing into a more advanced workflow here :) )
Change the webHookType property value to sfsoap and save the configuration. Your function.json config should look like the following:
function.json:
{
"bindings": [
{
"type": "httpTrigger",
"direction": "in",
"webHookType": "sfsoap",
"name": "req"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
],
"disabled": false
}
Switch to the Develop tab. We're ready to write our code.
This is where the ASP.NET WebHooks receiver shines! It will parse the notification for you, exposing strong typed objects you can work with. All you need to do is modify the method/function signature you get withe template to use the SalesforceNotifications type, making sure you're referencing the required assembly (Microsoft.AspNet.WebHooks.Receivers.Salesforce, which is made available to you, so no need for package reference) and namespace reference (Microsoft.AspNet.WebHooks).
Here is a full sample of a function that will receive the request and log the Organization ID, Action ID, grab the first notification and log all of its properties:
#r "Microsoft.AspNet.WebHooks.Receivers.Salesforce"
using Microsoft.AspNet.WebHooks;
public static void Run(SalesforceNotifications req, TraceWriter log)
{
log.Info($"Salesforce webhook was triggered!");
log.Info(req.OrganizationId);
log.Info(req.ActionId);
var notification = req.Notifications.First();
foreach (var p in notification.Keys)
{
log.Info($"{p} = {notification[p]}");
}
}
This process will be a lot smoother when the receiver is officially supported, but even with the added steps, this still beats having to parse the SOAP messages yourself :)
I hope this helps!

EasyAuthModule_32 bit Error 401 in xamarin forms aad authentication

please kindly help me out with my attempt to implement client side authentication for a xamarin forms aplication i am developing. i have followed every single tutorial on how to integrate Azure active directory into xamarin when using azure mobile services. the error is always thrown at the point of calling loginAsync. on futher investigation using the azure log i found out that the error was coming from the easyauthmodule. please help like i said i have followed every single tutorial on this issue and i have been on it now everyday for the past one week
please find my code below
try
{
AuthenticationContext ac = new AuthenticationContext(authority);
ac.TokenCache.Clear();
AuthenticationResult ar = await ac.AcquireTokenAsync(resource, clientId, new Uri(returnUri), new PlatformParameters(this));
JObject payload = new JObject();
payload["access_token"] = ar.AccessToken;
// DataRepository.DefaultManager.CurrentClient.Logout();
user = await DataRepository.DefaultManager.CurrentClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,payload);
}
catch (Exception ex)
{
CreateAndShowDialog(ex.Message, "Authentication failed");
}
EasyAuth is incompatible with Azure Mobile Services. Are you sure you are using the right service moniker?
Make sure you are using the following NuGet for Azure Mobile Apps: https://www.nuget.org/packages/Microsoft.Azure.Mobile.Client/
EasyAuth is only available in Azure App Service. You need to configure the App Service Authentication / Authorization module. Assuming you have already integrated ADAL into your Xamarin app and have an access token from ADAL, your code is pretty close. However, I've found that configuration of AAD for mobile apps is complex. So I wrote a couple of blog posts about it.
Here is the server flow edition: https://shellmonger.com/2016/04/04/30-days-of-zumo-v2-azure-mobile-apps-day-3-azure-ad-authentication/
Here is the client flow edition: https://shellmonger.com/2016/04/06/30-days-of-zumo-v2-azure-mobile-apps-day-4-adal-integration/
Both are using Cordova as a mobile client, but the configuration of the service is identical. The client details (aside from the obvious language differences) are similar as well.

High Trust S2S Provider Hosted App with "App + User" Policy

I am relatively new to sharepoint app development.
Trying to create a on premises, High Trust provider hosted app with App + User Policy. I have followed below document to create a demo.
https://msdn.microsoft.com/library/office/fp179901(v=office.15)
http://blogs.msdn.com/b/russmax/archive/2014/06/23/part-1-intro-to-provider-hosted-apps-setup-the-infrastructure.aspx
I am facing few issue and I have some question to clarify, if anybody can help.
1) When I inspect my request in dev tools, it give me below form data.
SPAppToken:
SPSiteUrl:
SPSiteTitle:Home
SPSiteLogoUrl:
SPSiteLanguage:en-US
SPSiteCulture:en-US
SPRedirectMessage:EndpointAuthorityMatches
SPErrorCorrelationId:f069e89c-a0cd-20ce-a1c0-7db95db0334b
now when i inspect log with above corelation id, i am finding below errors.
-- Error when get token for app i:0i.t|ms.sp.ext|ab8ff461-bc75-4516-b475-b666ac47eec0#802f23e1-6e11-45d1-909c-07a7b0ab0ce2,
exception: Microsoft.SharePoint.SPException: The Azure Access Control
service is unavailable.
-- App token requested from appredirect.aspx for site: 92bfe5c4-7255-4b09-a89a-07e0e2b03622 but there was an error in
generating it. This may be a case when we do not need a token or when
the app principal was not properly set up.
-- Getting Error Message for Exception Microsoft.SharePoint.SPException: The Azure Access Control service is
unavailable.
a) I belive in high-trust app it shouldn't look for Azure ACS.
Is this error because of some incorrect configuration?
b) SPAppToken is null here. Is it null always in case of hig trust app?
2) Say I am logged into sharepoint with User A and trying to launch sharepoint app.
Within app code I want to get identity of logged in user(which is A). From below code i found that Request.LogonUserIdentity gives me identity of user A. But how can we sure that request is came from sharepoint only. I can copy the same app URL and paste in browser window and login with window credential and get the same result. So question is how can I verify if its legitimate request came from sharepoint only and no one is faking request.
ALos, when I inspect request in dev tools, its passing Authorization key in request header. What is use of this?
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) { clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title); }
3) Also what happens if my app doesnt support windows authentication and only support FBA, is there any way to get user identity in this case?
Any help would be much appreciated.
Thanks
For issue #1: It looks to me that the step # 9 (Configure authentication settings) in this section (from the first MSDN article you have referred) was missed, i.e., 'ACS Control service' was selected instead of 'Use a Certificate' option.
For issue #2: There are helper methods in TokenHelper.cs to validate the AccessToken from the HttpRequest, which identifies the validity of the request.

Resources