botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

[.Net SDK, Question] How to get the user context (which dialog the user currently in) when logging the activities inside IActivityLogger? - DialogStack is empty when logging outgoing messages inside IActivityLogger

Open hpksp opened this issue 8 years ago • 14 comments

Version Info: Bot Builder .Net v.3.12.2.4

I'm trying to get the user context (which dialog the user currently in) when logging the activities inside IActivityLogger. I tried resolving IDialogStack inside the logger which always ends up throwing DependencyResolutionException. How do I achieve this? Thanks in advance.

hpksp avatar Jan 08 '18 07:01 hpksp

Found the answer on stackoverflow. Sharing the link for the benefit of others

hpksp avatar Jan 08 '18 09:01 hpksp

I am using following code to get the dialog stack inside the IActivityLogger.

public async Task LogAsync(IActivity activity) { using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) { var botData = scope.Resolve<IBotData>(); await botData.LoadAsync(new System.Threading.CancellationToken()); var stack = scope.Resolve<IDialogStack>(); var frames = stack.Frames; } }

I am able to get the current context of the user (dialog) using the dialogstack for incoming messages. However, the stack is empty for outgoing messages. I am guessing that the current stack is not persisted yet to the documentdb and the latest stack is still in the memory. How do i get the latest stack in order to get the user context?

hpksp avatar Jan 08 '18 11:01 hpksp

@hpksp for outgoing messages the stack is always empty. For outgoing messages from id is always your botid. In order to get the latest stack on user context you can interchange from/recipient ids as shown below code snippets.

public class ActivityLogger : IActivityLogger
{
    async Task IActivityLogger.LogAsync(IActivity activity)
    {
        if (activity.From.Id == ConfigurationManager.AppSettings["YourBotId"])
        {
            var newMessage = Activity.CreateMessageActivity();

            newMessage.From = activity.Recipient; 
            newMessage.Recipient = activity.From;

            newMessage.ServiceUrl = activity.ServiceUrl;
            newMessage.Conversation = activity.Conversation;
            newMessage.ChannelId = activity.ChannelId;

            await LogMessage(newMessage);
        }
        else
            await LogMessage(activity.AsMessageActivity());
    }

    async Task LogMessage(IMessageActivity msg)
    {
        using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
        {
            var botData = scope.Resolve<IBotData>();
            await botData.LoadAsync(new System.Threading.CancellationToken());

            var stack = scope.Resolve<IDialogStack>();
            var frames = stack.Frames;

        }
    }
}

and then register activity logger @Application_Start() of Global.asax.cs

Conversation.UpdateContainer( builder => { builder.RegisterType().AsImplementedInterfaces().InstancePerDependency(); });

msmohan avatar Jan 09 '18 22:01 msmohan

@msmohan thanks for the response. I tried out your approach and I was able to get the stack. However, it seems that the stack is not the latest. This is how the flow happens.

I have two dialogs. Root and Greet dialogs

  1. Root.MessageReceivedAsync is waiting to be invoked when the next request comes in
  2. When a request comes in the activity logger get invoked and at that point in time the stack frame count is two (2)
  3. After that, the root dialog creates an instance of Greet dialog and invoke context.Call to push the child dialog to the stack
  4. When Greet.StartAsync gets invoked the stack frame count is three (3)
  5. Then I invoke await context.PostAsync("hi") inside Greet.StartAsync
  6. As soon as I do that the activity logger gets invoked, but the stack frame count is two (2)

Ideally, the stack frame count should be three (3) and the Greet dialog has to be on the top of the stack. What am I doing wrong?

hpksp avatar Jan 10 '18 02:01 hpksp

@hpksp can you please share this project as a zip folder somewhere I can download and repro?

msmohan avatar Jan 10 '18 18:01 msmohan

@msmohan I created a cut down version of the project with only root dialog, greet dialog and activity logger. You can use it to repro. testbot2.zip

hpksp avatar Jan 11 '18 10:01 hpksp

@msmohan any updates?

hpksp avatar Jan 23 '18 15:01 hpksp

Can you please let us know if the issue still persists?

fanidamj-zz avatar Jun 21 '18 23:06 fanidamj-zz

Yes it does. Currently I'm using Bot Builder SDK v3.15.2.2

hpksp avatar Jun 22 '18 00:06 hpksp

@hpksp The stack is not persisted until the dialog code is finished. When you create a new scope in the logger using using DialogModule.BeginLifetimeScope, it does not see the current dialog that sent the message because the current dialog has not been persisted to the state store yet.

Something you could do as a workaround is add a property to ChannelData for the outgoing message, and check that in the logger.


The Microsoft Bot Framework team prefers that how to questions be submitted on Stack Overflow. The official Bot Framework Github repo  is the preferred platform for submitting bug fixes and feature requests.  

EricDahlvang avatar Jul 16 '18 23:07 EricDahlvang

Thanks @EricDahlvang. I came up with a workaround using Aspect Oriented Programming (AOP) to get the user context. Anyways thanks for your suggestion.

hpksp avatar Jul 20 '18 01:07 hpksp

If it could be helpful for someone else, I had the same issue and the reason was that

using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) {
    var botData = scope.Resolve<IBotData>();

returns an IBotData instance that is different from the used in bot builder (hence it could not access data that has not been persisted yet), because it's resolved from a different scope. I solved it by using a factory (registered with FiberModule.Key_DoNotSerialize key) which constructor receives an IComponentContext:

public EvaBotFactory(IComponentContext scope) {
    SetField.NotNull(out _scope, nameof(scope), scope);
}

Then I registered my ActivityLogger implementation:

builder.Register(c => new DbActivityLogger(connectionString, c.Resolve<IBotFactory>()))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

And finally in LogAssync method I just use the factory to resolve IBotData and IDialogStack:

var frames = (await _factory.GetDialogStack()).Frames;

mitkodi avatar Aug 21 '18 10:08 mitkodi

@mitkodi can you share code snipet how are you resolving IBotData in DbActivityLogger as we are facing an exception:

Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = IBotData (DelegateActivator), Services = [Microsoft.Bot.Builder.Dialogs.Internals.IBotData], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = JObjectBotData (ReflectionActivator), Services = [Microsoft.Bot.Builder.Dialogs.Internals.JObjectBotData (Microsoft.Bot.Builder.Dialogs.Internals.IBotData), Microsoft.Bot.Builder.Dialogs.Internals.JObjectBotData], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> Unable to resolve the type 'Microsoft.Bot.Builder.Dialogs.Address' because the lifetime scope it belongs in can't be located. The following services are exposed by this registration:
- Microsoft.Bot.Builder.Dialogs.IAddress
- System.IEquatable`1[[Microsoft.Bot.Builder.Dialogs.IAddress, Microsoft.Bot.Builder, Version=3.15.2.2, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]

Details ---> No scope with a tag matching 'Microsoft.Bot.Builder.Dialogs.Internals.DialogModule' is visible from the scope in which the instance was requested.

etbuilder avatar Aug 21 '19 10:08 etbuilder

@etbuilder, I added IBotData botData to the constructor of DbActivityLogger and in the Load(ContainerBuilder builder) of my implementation of Autofac.Module I register DbActivityLogger as

 builder.Register(c => new DbActivityLogger(c.Resolve<IBotData>()))
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope();

I hope this can help you.

mitkodi avatar Aug 23 '19 10:08 mitkodi