How to fix issue related to 500 error code in web

2020-02-15 09:45发布

问题:

How to fix the issue related to 500 error occurring in web chat channel after clicking submit button in Adaptive card in chat bot developed through V4 C#?

Creating this new issue as suggested by @mdrichardson-msft as the issue is specific/other issues in below stack overflow question:

Is there a way to enable calendar option as an input in V4 chat bot C# other than using Adaptive cards?

Coming to my issue:

I have a water fall dialog class where I am using Adaptive card to select date time inputs and a submit button in step 1 and then in step#2 the values are captured and processed after I click on submit in step#1.

Currently as posted in the above link(issue explained in detail below) I am facing 500 error in the browser when clicked on submit button in the adaptive card:

STEP #1:

I am showing the adaptive card with two date and time inputs one for start and another for Stop

Actual Result:

The adaptive is displayed successfully both in Emulator and web chat channel without any issues

STEP #2: When I click on SetSchedule on the Adaptive card displayed in step 1 the values should be captured in step #2 and displayed on the screen

Actual Result:

Works perfectly fine in emulator but not in Web Chat channel bot. I get an error in the Web chat Channel BOT. Please find the HTML file for accessing bot, the waterfall dialog class and the Adaptive card json file attached for reference. Along with it please find the error screenshot attached in web chat channel for reference. I have tested through TestinWebChat also and it is throwing the error here also.

I have published it through VSTS 2019 and got no errors screenshot attached for reference "publishsuceeded_thruvisualStudio2019.jpg".

Can you please guide me to solve this issue as you did for the sign in the issue? Request your immediate help a this is blocking my work.

Language: C# SDK: V4 Published Through: Visual Studio 2019

HTML:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Custom style options</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://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication

            // Token is found by going to Azure Portal > Your Web App Bot > Channels > Web Chat - Edit > Secret Keys - Show
            // It looks something like this: pD*********xI.8ZbgTHof3GL_nM5***********aggt5qLOBrigZ8
            const token = '<<Your Direct Line Secret Key>>';

            // You can modify the style set by providing a limited set of style options
            const styleOptions = {
                botAvatarImage: 'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
                botAvatarInitials: 'BF',
                userAvatarImage: 'https://avatars1.githubusercontent.com/u/45868722?s=96&v=4',
                userAvatarInitials: 'WC',
                bubbleBackground: 'rgba(0, 0, 255, .1)',
                bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
            };

            // We are using a customized store to add hooks to connect event
            const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
                if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                    // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
                    dispatch({
                        type: 'WEB_CHAT/SEND_EVENT',
                        payload: {
                            name: 'webchat/join',
                            value: { language: window.navigator.language }
                        }
                    });
                }
                return next(action);
            });

            window.WebChat.renderWebChat({
                directLine: window.WebChat.createDirectLine({ token }),
                styleOptions,store
            }, document.getElementById('webchat'));

            document.querySelector('#webchat > *').focus();
        })().catch(err => console.error(err));
    </script>
</body>
</html>

Code:

using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EchoBot.Dialogs
{
    public class Adaptivecarddialog : WaterfallDialog
    {
        public const string cards = @"./AdaptiveCard.json";

        public Adaptivecarddialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
            : base(dialogId, steps)
        {
            AddStep(async (stepContext, cancellationToken) =>
            {
                var cardAttachment = CreateAdaptiveCardAttachment(cards);

                var reply = stepContext.Context.Activity.CreateReply();
                reply.Attachments = new List<Attachment>() { cardAttachment };

                await stepContext.Context.SendActivityAsync(reply, cancellationToken);
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        // You can comment this out if you don't want to display any text. Still works.
                    }
                };

                // Display a Text Prompt and wait for input
                return await stepContext.PromptAsync(nameof(TextPrompt), opts);
            });

            AddStep(async (stepContext, cancellationToken) =>
            {
                var res = stepContext.Result.ToString();
                dynamic jobject = JsonConvert.DeserializeObject(res);
                string NewStartDateTime = jobject.Startdate + " " + jobject.Starttime;
                string NewStopDateTime = jobject.Stopdate + " " + jobject.Stoptime;
                await stepContext.Context.SendActivityAsync($"StartDateTime:{NewStartDateTime}", cancellationToken: cancellationToken);
                await stepContext.Context.SendActivityAsync($"StopDateTime:{NewStopDateTime}", cancellationToken: cancellationToken);

                return await stepContext.EndDialogAsync();
            });

        }

        public static new string Id => "Adaptivecarddialog";

        public static Adaptivecarddialog Instance { get; } = new Adaptivecarddialog(Id);

        public static Attachment CreateAdaptiveCardAttachment(string filePath)
        {
            var adaptiveCardJson = File.ReadAllText(filePath);
            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content = JsonConvert.DeserializeObject(adaptiveCardJson),
            };
            return adaptiveCardAttachment;
        }
    }
}

Adaptive Card:

{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "id": "Start date text",
      "separator": true,
      "text": "Schedule Start DateTime:"
    },
    {
      "type": "TextBlock",
      "id": "DateTimeFormat",
      "horizontalAlignment": "Center",
      "separator": true,
      "weight": "Bolder",
      "color": "Warning",
      "text": "(In UTC Time Zone)"
    },
    {
      "type": "Input.Date",
      "id": "Startdate",
      "separator": true,
      "value": "2019-05-24"
    },
    {
      "type": "Input.Time",
      "id": "Starttime",
      "separator": true,
      "value": "08:00"
    },
    {
      "type": "TextBlock",
      "id": "Stop date text",
      "separator": true,
      "text": "Schedule Stop DateTime:"
    },
    {
      "type": "TextBlock",
      "id": "DateTimeFormat",
      "horizontalAlignment": "Center",
      "separator": true,
      "weight": "Bolder",
      "color": "Warning",
      "text": "(In UTC Time Zone)"
    },
    {
      "type": "Input.Date",
      "id": "Stopdate",
      "separator": true,
      "value": "2019-05-25"
    },
    {
      "type": "Input.Time",
      "id": "Stoptime",
      "separator": true,
      "value": "08:00"
    }
  ],
  "actions": [
    {
      "type": "Action.Submit",
      "id": "SubmitBtn",
      "title": "SetSchedule"
    }
  ],
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.0"
}

Screenshots:

Thanks & Regards

-ChaitanyaNG


Date: 6-June-2019

Log details from KUDU for reference as guided by Matt:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>IIS Detailed Error - 500.0 - Internal Server Error</title> 
<style type="text/css"> 
<!-- 
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;} 
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} 
.config_source code{font-size:.8em;color:#000000;} 
pre{margin:0;font-size:1.4em;word-wrap:break-word;} 
ul,ol{margin:10px 0 10px 5px;} 
ul.first,ol.first{margin-top:5px;} 
fieldset{padding:0 15px 10px 15px;word-break:break-all;} 
.summary-container fieldset{padding-bottom:5px;margin-top:4px;} 
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} 
legend{color:#333333;;margin:4px 0 8px -12px;_margin-top:0px; 
font-weight:bold;font-size:1em;} 
a:link,a:visited{color:#007EFF;font-weight:bold;} 
a:hover{text-decoration:none;} 
h1{font-size:2.4em;margin:0;color:#FFF;} 
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} 
h4{font-size:1.2em;margin:10px 0 5px 0; 
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; 
color:#FFF;background-color:#5C87B2; 
}#content{margin:0 0 0 2%;position:relative;} 
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} 
.content-container p{margin:0 0 10px 0; 
}#details-left{width:35%;float:left;margin-right:2%; 
}#details-right{width:63%;float:left;overflow:hidden; 
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; 
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; 
font-size:1em;color:#FFF;text-align:right; 
}#server_version p{margin:5px 0;} 
table{margin:4px 0 4px 0;width:100%;border:none;} 
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:normal;border:none;} 
th{width:30%;text-align:right;padding-right:2%;font-weight:bold;} 
thead th{background-color:#ebebeb;width:25%; 
}#details-right th{width:20%;} 
table tr.alt td,table tr.alt th{} 
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} 
.clear{clear:both;} 
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} 
--> 
</style> 

</head> 
<body> 
<div id="content"> 
<div class="content-container"> 
<h3>HTTP Error 500.0 - Internal Server Error</h3> 
<h4>The page cannot be displayed because an internal server error has occurred.</h4> 
</div> 
<div class="content-container"> 
<fieldset><h4>Most likely causes:</h4> 
<ul>    <li>IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.</li>    <li>IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.</li>    <li>IIS was not able to process configuration for the Web site or application.</li>     <li>The authenticated user does not have permission to use this DLL.</li>   <li>The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.</li> </ul> 
</fieldset> 
</div> 
<div class="content-container"> 
<fieldset><h4>Things you can try:</h4> 
<ul>    <li>Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account.</li>     <li>Check the event logs to see if any additional information was logged.</li>  <li>Verify the permissions for the DLL.</li>    <li>Install the .NET Extensibility feature if the request is mapped to a managed handler.</li>  <li>Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul> 
</fieldset> 
</div> 

<div class="content-container"> 
<fieldset><h4>Detailed Error Information:</h4> 
<div id="details-left"> 
<table border="0" cellpadding="0" cellspacing="0"> 
<tr class="alt"><th>Module</th><td>&nbsp;&nbsp;&nbsp;AspNetCoreModule</td></tr> 
<tr><th>Notification</th><td>&nbsp;&nbsp;&nbsp;ExecuteRequestHandler</td></tr> 
<tr class="alt"><th>Handler</th><td>&nbsp;&nbsp;&nbsp;aspNetCore</td></tr> 
<tr><th>Error Code</th><td>&nbsp;&nbsp;&nbsp;0x00000000</td></tr> 

</table> 
</div> 
<div id="details-right"> 
<table border="0" cellpadding="0" cellspacing="0"> 
<tr class="alt"><th>Requested URL</th><td>&nbsp;&nbsp;&nbsp;https://testbotforoauthprompt:80/api/messages</td></tr> 
<tr><th>Physical Path</th><td>&nbsp;&nbsp;&nbsp;D:\home\site\wwwroot\api\messages</td></tr> 
<tr class="alt"><th>Logon Method</th><td>&nbsp;&nbsp;&nbsp;Anonymous</td></tr> 
<tr><th>Logon User</th><td>&nbsp;&nbsp;&nbsp;Anonymous</td></tr> 

</table> 
<div class="clear"></div> 
</div> 
</fieldset> 
</div> 

<div class="content-container"> 
<fieldset><h4>More Information:</h4> 
This error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error. 
<p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=500,0,0x00000000,14393">View more information &raquo;</a></p> 
<p>Microsoft Knowledge Base Articles:</p> 


</fieldset> 
</div> 
</div> 
</body> 
</html> 
2019-06-06 05:04:50 TESTBOTFOROAUTHPROMPT POST /api/messages X-ARR-LOG-ID=b3f7a170-d306-477e-b318-fbd82ec285f6 443 - 52.172.202.195 BF-DirectLine+(Microsoft-BotFramework/3.2++https://botframework.com/ua) ARRAffinity=232908322fb7729ed3fe519abf975a28a9506866f45a7a57c7acd29d79e24c2f - testbotforoauthprompt.azurewebsites.net 500 0 0 294 2493 3475

Please help me in resolving this issue and i request a detailed step by step guided manner as I am very new to code and all other technical things.

If possible we can have a mutually agreeably skype/teams call session so that we can go over step by step detailed manner wherever required.


Date: 16-June-2019 Updating POST with additional debugging points.

Hi Matt,

I have debugged using NGROK for remote channels like test in webchat and also emulator to see what data is coming as different:

Using Emulator: Using Emulator when I hit the button inside the Adaptive card there is channel data coming from emulator which when parsed i get POSTBACK as true as a result i am able to go to the next step in waterfall dialog due to which the additional code that was put in to process the data from the Adaptive card was executed

Please see screenshot with name "ChannelDataComing_fromemulator.jpg" for reference.

Using TestInWebChat of Azure: Here, the Channel data is coming as NULL due to which the code is erroring out as it is not able to parse it since there is no parsing it it gives error as Object reference error. There is no channel data there is no POSTback hence it is not going into next step of waterfall to process data.

Please see screenshot with name "ChannelDataComingnull_fromTestinWeBChat.jpg" for reference.

Queries:

  1. Why is the channel data not coming when it is coming through the test done in emulator?
  2. How to get channel data to be passed in this case so that the POST back comes as true and then the next step of waterfall will be executed?
  3. If this does not work is there any other way it can be done so that it goes to next step and i can process the data the way I seem fit?

It is not be noted that the Channel data does come when a first HI message is being sent since the code is inside the Activity==Message condition and the channel does not have post back the code does not execute in full but where as after hitting the submit button in the Adaptive card after it is displayed the channel data does not come not sure why?

Please help me in resolving this issue as I am stuck here and I really want this to be working?

回答1:

Below is a summary of the comments on the OPs post that lead to the resolution of the issue.

Debugging techniques

  • Ensure that the bot is working locally.
  • Check the Log stream or log files via Kudu under Development Tools > Advanced tools for your App Service. You can also turn on Application logs under Monitoring > App Service logs for your App Service then view the log stream via the Log stream section of your App Service while you test your bot in Web Chat in another tab/window.
  • Check that the App Settings entries exist and are correct (password, app id etc).
  • Debug the remote channel using your local code as per @Kyle Delaney. More instructions are available here, basically this entails the following:
  • Ensure that ngrok is installed.
  • The following instructions are roughly based on the guide here :
  • Open the solution in Visual Studio.
  • Start debugging in Visual Studio.
  • Note down the port in the localhost address for the web page that is opened (this should be 3978).
  • Navigate into the directory where you extracted ngrok.
  • Type cmd into the address bar and press enter to open a new command prompt window.
  • Create a publicly accessible URL that tunnels all http traffic on a specified port to your machine:
  • ngrok http 3978 --host-header=localhost
  • Copy the https forwarding URL.
  • This should be in the form of https://.ngrok.io.
  • Keep the command prompt window running ngrok open because once it is closed the URL will no longer be accessible.
  • Stop debugging.
  • In the Azure Portal open the Web App Bot resource.
  • Go to Bot management > Settings > Configuration and replace the first part of the URL https://.azurewebsites.net with the ngrok URL.
  • The final URL should be in the form of https:///api/messages.
  • Click Save (you have click outside of the text box for the Save button to be enabled).
  • Go to App Service > Settings > Configuration and note down the value for MicrosoftAppId and MicrosoftAppPassword.
  • The value in the .bot file is the encrypted value, we need the decrypted value for the emulator.
  • In Visual Studio Copy the appId and appPassword key value pairs from the Production endpoint in the .bot file to the Development endpoint.
  • Ensure that the endpoint value for the Development endpoint is set to the localhost URL (http://localhost:3978/api/messages ).
  • Save your changes in Visual Studio.
  • Start debugging in Visual Studio.
  • Open Test in Web Chat in Azure.
  • Test the bot functionality.
  • You should hit any breakpoints that you've set in the code.

  • CLEAN UP STEPS - IMPORTANT!!!

  • Restore the Messaging endpoint URL for the Web App Bot in Azure to it's original value AND save the change.
  • Undo/revert any changes to the .bot file.
  • Close the command prompt window running ngrok.
  • Close the Bot Framework Emulator

Null reference error

This has been covered numerous times by multiple authors but in a nutshell... one of your objects or a property of one of your objects that you are trying to access is null. When you hit your breakpoint, step through your code line by line in the debugger until you find the line that breaks. Once you find the line that breaks you can inspect your variables and their properties by hovering over them.


ChannelData not coming through in the WebChat channel

I ran into this problem myself and couldn't find any documentation on why this is the case, but I managed to solve this issue with the following code inside my OnTurnAsync method:

if (dc.Context.Activity.Type == ActivityTypes.Message)
{
    //PropertyInfo channelDataProperty = dc.Context.Activity.GetType().GetProperty("ChannelData");
    Activity activity = dc.Context.Activity;
    object rawChannelData = activity.ChannelData;

    // For the Bot Framework Emulator
    if (rawChannelData != null)
    {
        JObject channelData = JObject.Parse(rawChannelData.ToString());

        if (channelData.Children().Any(c => ((JProperty)c).Name == "postBack") && activity.Value != null)
        {
            dc.Context.Activity.Text = "your-value-here";
        }
    }
    // For the WebChat channel since it doesn't provide ChannelData
    else if (activity.ChannelId == Channels.Webchat && activity.Value != null)
    {
        dc.Context.Activity.Text = "your-value-here";
    }
}

This could be further simplified (if you like) to:

if (dc.Context.Activity.Type == ActivityTypes.Message)
{
    // For the Bot Framework Emulator AND the WebChat channel
    if (dc.Context.Activity.Value != null && dc.Context.Activity.Text == null)
    {
        dc.Context.Activity.Text = "your-value-here";
    }
}

The reason that the simplified version of code above should work is because as you know Adaptive Cards are the only time that the .Value property of the Activity should be populated, the rest of the time the postback data is in the .Text property and it will be automatically picked up by the code in your WaterfallDialog. I would advise testing this simplified code yourself before deciding to go with it as you may have scenarios that I do not where .Value is populated outside of an Adaptive Card.