Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bot Emualor "ExceptionMessage": "Object reference not set to an instance of an object.", "exceptionType": "System.NullReferenceException",

I want to store the conversation on the chat bot and am using IActivityLogger for it. The code is as follows :

public class EntityFrameworkActivityLogger : IActivityLogger
{
    Task IActivityLogger.LogAsync(IActivity activity)
    {
        IMessageActivity msg = activity.AsMessageActivity();
        using (BotApplicationSqlData.ConversationDataContext dataContext = new BotApplicationSqlData.ConversationDataContext())
        {
            var newActivity = Mapper.Map<IMessageActivity, BotApplicationSqlData.Activity>(msg);
            if (string.IsNullOrEmpty(newActivity.Id))
                newActivity.Id = Guid.NewGuid().ToString();
            dataContext.Activities.Add(newActivity);
            dataContext.SaveChanges();
        }
        return null;
    }
}

I am getting an error of Request to

'https://botapplicationsqlexample.azurewebsites.net/api/messages' failed: [500] Internal Server Error .

On debugging, it shows a Null Reference Exception and Object reference not set to an instance of an object.

The conversation is getting stored on the Azure DB but no reply from the Bot's end is coming. Can anyone please help with me this?

like image 323
Muskan Sethia Avatar asked Jan 25 '26 23:01

Muskan Sethia


1 Answers

I ran this code, and noticed that if an activity of type ActivityTypes.Typing comes through, activity.AsMessageActivity() returns a null object. To fix this, just surround the saving code with a null check:

    public async Task LogAsync(IActivity activity)
    {
        IMessageActivity msg = activity.AsMessageActivity();

        if (msg != null)
        {
            using (Data.ConversationDataContext dataContext = new Data.ConversationDataContext())
            {
                var newActivity = Mapper.Map<IMessageActivity, Data.Activity>(msg);
                if (string.IsNullOrEmpty(newActivity.Id))
                    newActivity.Id = Guid.NewGuid().ToString();

                dataContext.Activities.Add(newActivity);
                dataContext.SaveChanges();
            }
        }
    }   
like image 70
Eric Dahlvang Avatar answered Jan 28 '26 09:01

Eric Dahlvang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!