private TestFlow CreateNoResourceExplorerFlow(BotCallbackHandler handler)
        {
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = new TestAdapter(TestAdapter.CreateConversation(MethodBase.GetCurrentMethod().ToString()));

            adapter
            .UseStorage(storage)
            .UseBotState(userState, convoState)
            .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            return(new TestFlow(adapter, handler));
        }
        private TestFlow CreateFlow(BotCallbackHandler handler)
        {
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName));

            adapter
            .UseStorage(storage)
            .UseState(userState, convoState)
            .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            return(new TestFlow(adapter, handler));
        }
Example #3
0
        public async Task <object> ProcessActivity(Payload actionPayload, BotCallbackHandler callback)
        {
            TurnContext context = null;

            try
            {
                var activity = RequestToActivity(actionPayload);
                BotAssert.ActivityNotNull(activity);

                context = new TurnContext(this, activity);

                Responses = new Dictionary <string, List <Activity> >();

                await base.RunPipelineAsync(context, callback, default(CancellationToken)).ConfigureAwait(false);

                var key = $"{activity.Conversation.Id}:{activity.Id}";

                try
                {
                    object response   = null;
                    var    activities = Responses.ContainsKey(key) ? Responses[key] : new List <Activity>();

                    if (WebhookType == GoogleWebhookType.DialogFlow)
                    {
                        response = CreateDialogFlowResponseFromLastActivity(activities, context);
                    }
                    else
                    {
                        response = CreateConversationResponseFromLastActivity(activities, context);
                    }

                    return(response);
                }
                finally
                {
                    if (Responses.ContainsKey(key))
                    {
                        Responses.Remove(key);
                    }
                }
            }
            catch (Exception ex)
            {
                await OnTurnError(context, ex);

                throw;
            }
        }
        private async Task <ResourceResponse> ProcessActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string replyToActivityId, Activity activity, CancellationToken cancellationToken)
        {
            var skillConversationReference = await GetSkillConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false);

            ResourceResponse resourceResponse = null;

            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                turnContext.TurnState.Add(_skillConversationReferenceKey, skillConversationReference);
                activity.ApplyConversationReference(skillConversationReference.ConversationReference);
                turnContext.Activity.Id       = replyToActivityId;
                turnContext.Activity.CallerId = $"{CallerIdConstants.BotToBotPrefix}{JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims)}";
                switch (activity.Type)
                {
                case ActivityTypes.EndOfConversation:
                    await _conversationIdFactory.DeleteConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false);
                    await SendToBotAsync(activity, turnContext, ct).ConfigureAwait(false);
                    break;

                case ActivityTypes.Event:
                    await SendToBotAsync(activity, turnContext, ct).ConfigureAwait(false);
                    break;

                case ActivityTypes.Command:
                case ActivityTypes.CommandResult:
                    if (activity.Name.StartsWith("application/", StringComparison.Ordinal))
                    {
                        // Send to channel and capture the resource response for the SendActivityCall so we can return it.
                        resourceResponse = await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await SendToBotAsync(activity, turnContext, ct).ConfigureAwait(false);
                    }

                    break;

                default:
                    // Capture the resource response for the SendActivityCall so we can return it.
                    resourceResponse = await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false);
                    break;
                }
            });

            await _adapter.ContinueConversationAsync(claimsIdentity, skillConversationReference.ConversationReference, skillConversationReference.OAuthScope, callback, cancellationToken).ConfigureAwait(false);

            return(resourceResponse ?? new ResourceResponse(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)));
        }
Example #5
0
        public async Task OAuthPromptRecognizeTokenAsync_WithNullTextMessageActivity_DoesNotThrow()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            var connectionName  = "myConnection";
            var retryPromptText = "Sorry, invalid input. Please sign in.";

            // Create new DialogSet.
            var dialogs = new DialogSet(dialogState);

            dialogs.Add(new OAuthPrompt("OAuthPrompt", new OAuthPromptSettings()
            {
                Text = "Please sign in", ConnectionName = connectionName, Title = "Sign in"
            }));

            BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);

                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync("OAuthPrompt", new PromptOptions()
                    {
                        RetryPrompt = MessageFactory.Text(retryPromptText)
                    }, cancellationToken : cancellationToken);
                }
            };

            var messageActivityWithNullText = Activity.CreateMessageActivity();

            await new TestFlow(adapter, botCallbackHandler)
            .Send("hello")
            .AssertReply(activity =>
            {
                Assert.Single(((Activity)activity).Attachments);
                Assert.Equal(OAuthCard.ContentType, ((Activity)activity).Attachments[0].ContentType);
                Assert.Equal(InputHints.AcceptingInput, ((Activity)activity).InputHint);
            })
            .Send(messageActivityWithNullText)
            .AssertReply(retryPromptText)
            .StartTestAsync();
        }
Example #6
0
        [InlineData(true, Channels.Msteams, true)]   //Override: show link;  ChannelRequiresSingInLink() returns true; Result: show link
        public async Task OAuthPromptSignInLinkSettingsCases(bool?showSignInLinkValue, string channelId, bool shouldHaveSignInLink)
        {
            var oAuthPromptSettings = new OAuthPromptSettings();

            oAuthPromptSettings.ShowSignInLink = showSignInLinkValue;

            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            // Create new DialogSet
            var dialogs = new DialogSet(dialogState);

            dialogs.Add(new OAuthPrompt("OAuthPrompt", oAuthPromptSettings));

            BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);

                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync("OAuthPrompt", new PromptOptions(), cancellationToken : cancellationToken);
                }
            };

            var initialActivity = new Activity()
            {
                ChannelId = channelId,
                Text      = "hello"
            };

            await new TestFlow(adapter, botCallbackHandler)
            .Send(initialActivity)
            .AssertReply(activity =>
            {
                Assert.Single(((Activity)activity).Attachments);
                Assert.Equal(OAuthCard.ContentType, ((Activity)activity).Attachments[0].ContentType);
                var oAuthCard  = (OAuthCard)((Activity)activity).Attachments[0].Content;
                var cardAction = oAuthCard.Buttons[0];
                Assert.Equal(shouldHaveSignInLink, cardAction.Value != null);
            })
            .StartTestAsync();
        }
        /// <summary>
        /// Starts activity processing for the current bot turn.
        /// </summary>
        /// <param name="turnContext">The turn's context object.</param>
        /// <param name="callback">A callback method to run at the end of the pipeline.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="turnContext"/> is null.</exception>
        /// <remarks>The adapter calls middleware in the order in which you added it.
        /// The adapter passes in the context object for the turn and a next delegate,
        /// and the middleware calls the delegate to pass control to the next middleware
        /// in the pipeline. Once control reaches the end of the pipeline, the adapter calls
        /// the <paramref name="callback"/> method. If a middleware component doesn’t call
        /// the next delegate, the adapter does not call  any of the subsequent middleware’s
        /// <see cref="IMiddleware.OnTurnAsync(ITurnContext, NextDelegate, CancellationToken)"/>
        /// methods or the callback method, and the pipeline short circuits.
        /// <para>When the turn is initiated by a user activity (reactive messaging), the
        /// callback method will be a reference to the bot's
        /// <see cref="IBot.OnTurnAsync(ITurnContext, CancellationToken)"/> method. When the turn is
        /// initiated by a call to <see cref="ContinueConversationAsync(string, ConversationReference, BotCallbackHandler, CancellationToken)"/>
        /// (proactive messaging), the callback method is the callback method that was provided in the call.</para>
        /// </remarks>
        protected async Task RunPipelineAsync(ITurnContext turnContext, BotCallbackHandler callback, CancellationToken cancellationToken)
        {
            BotAssert.ContextNotNull(turnContext);

            // Call any registered Middleware Components looking for ReceiveActivityAsync()
            if (turnContext.Activity != null)
            {
                if (turnContext.Activity.Locale != null)
                {
                    try
                    {
                        Thread.CurrentThread.CurrentCulture = new CultureInfo(turnContext.Activity.Locale);
                        (turnContext as TurnContext).Locale = turnContext.Activity.Locale;
                    }
                    catch (CultureNotFoundException)
                    {
                        // if turnContext.Activity.Locale is invalid, then TurnContext.Locale will set to Thread.CurrentThread.CurrentCulture.Name as default.
                        (turnContext as TurnContext).Locale = Thread.CurrentThread.CurrentCulture.Name;
                    }
                }

                try
                {
                    await MiddlewareSet.ReceiveActivityWithStatusAsync(turnContext, callback, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    if (OnTurnError != null)
                    {
                        await OnTurnError.Invoke(turnContext, e).ConfigureAwait(false);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                // call back to caller on proactive case
                if (callback != null)
                {
                    await callback(turnContext, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Example #8
0
        public async Task ContinueConversationAsync(ConversationReference reference, BotCallbackHandler logic, CancellationToken cancellationToken)
        {
            if (reference == null)
            {
                throw new ArgumentNullException(nameof(reference));
            }
            if (logic == null)
            {
                throw new ArgumentNullException(nameof(logic));
            }
            var request = reference.GetContinuationActivity().ApplyConversationReference(reference, true);

            using (var context = new TurnContext(this, request))
            {
                await RunPipelineAsync(context, logic, cancellationToken).ConfigureAwait(false);
            }
        }
Example #9
0
        public async Task ProcessActivityBySocketAsync(
            BotCallbackHandler callback = null
            )
        {
            await InitUserIfNeeded();

            var socket = new SlackRtmClient(options.BotUserToken);
            await socket.Connect().ConfigureAwait(false);

            var sub = socket.Messages.Subscribe(async(message) =>
            {
                await ProcessActivityAsync(message, callback);
            });

            await socket.Events;

            sub.Dispose();
        }
        private TestFlow CreateNoResourceExplorerFlow(string locale, BotCallbackHandler handler)
        {
            TypeFactory.Configuration = new ConfigurationBuilder().Build();
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = new TestAdapter(TestAdapter.CreateConversation(TestContext.TestName));

            adapter
            .UseStorage(storage)
            .UseState(userState, convoState)
            .UseAdaptiveDialogs()
            .UseLanguageGeneration()
            .Use(new TranscriptLoggerMiddleware(new FileTranscriptLogger()));

            return(new TestFlow(adapter, handler));
        }
Example #11
0
        /// <inheritdoc/>
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            var typing = adapter.MakeActivity();

            typing.Type = ActivityTypes.Typing;

            if (!string.IsNullOrEmpty(User))
            {
                typing.From      = ObjectPath.Clone(typing.From);
                typing.From.Id   = User;
                typing.From.Name = User;
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            await adapter.ProcessActivityAsync((Activity)typing, callback, default).ConfigureAwait(false);
        internal async Task <ResourceResponse> OnUpdateActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string activityId, Activity activity, CancellationToken cancellationToken = default)
        {
            var skillConversationReference = await GetSkillConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false);

            ResourceResponse resourceResponse = null;
            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                turnContext.TurnState.Add(_skillConversationReferenceKey, skillConversationReference);
                activity.ApplyConversationReference(skillConversationReference.ConversationReference);
                turnContext.Activity.Id       = activityId;
                turnContext.Activity.CallerId = $"{CallerIdConstants.BotToBotPrefix}{JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims)}";
                resourceResponse = await turnContext.UpdateActivityAsync(activity, cancellationToken).ConfigureAwait(false);
            });

            await _adapter.ContinueConversationAsync(claimsIdentity, skillConversationReference.ConversationReference, skillConversationReference.OAuthScope, callback, cancellationToken).ConfigureAwait(false);

            return(resourceResponse ?? new ResourceResponse(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)));
        }
Example #13
0
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback)
        {
            if (this.Text == null)
            {
                throw new Exception("You must define the Text property");
            }

            var activity = adapter.MakeActivity(this.Text);

            if (!string.IsNullOrEmpty(this.User))
            {
                activity.From      = ObjectPath.Clone(activity.From);
                activity.From.Id   = this.User;
                activity.From.Name = this.User;
            }

            await adapter.ProcessActivityAsync(activity, callback, default(CancellationToken)).ConfigureAwait(false);
        }
Example #14
0
        public async Task ProcessActivityAsyncForForwardedActivity()
        {
            var botAppId    = "00000000-0000-0000-0000-000000000001";
            var skill1AppId = "00000000-0000-0000-0000-000000skill1";
            var claims      = new List <Claim>
            {
                new Claim(AuthenticationConstants.AudienceClaim, skill1AppId),
                new Claim(AuthenticationConstants.AppIdClaim, botAppId),
                new Claim(AuthenticationConstants.VersionClaim, "1.0")
            };
            var identity = new ClaimsIdentity(claims);

            var credentialProvider = new SimpleCredentialProvider()
            {
                AppId = botAppId
            };
            var serviceUrl = "https://root-bot.test.azurewebsites.net/";
            var callback   = new BotCallbackHandler((context, ct) =>
            {
                GetAppCredentialsAndAssertValues(context, skill1AppId, botAppId, 1);
                GetConnectorClientsAndAssertValues(
                    context,
                    skill1AppId,
                    botAppId,
                    new Uri(serviceUrl),
                    1);

                var scope = context.TurnState.Get <string>(BotAdapter.OAuthScopeKey);
                Assert.Equal(botAppId, scope);
                Assert.Equal($"{CallerIdConstants.BotToBotPrefix}{botAppId}", context.Activity.CallerId);
                return(Task.CompletedTask);
            });

            var sut = new BotFrameworkAdapter(credentialProvider);
            await sut.ProcessActivityAsync(
                identity,
                new Activity("From root-bot")
            {
                ChannelId  = Channels.Emulator,
                ServiceUrl = serviceUrl
            },
                callback,
                CancellationToken.None);
        }
        /// <inheritdoc/>
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            if (inspector != null)
            {
                await inspector((dc) =>
                {
                    foreach (var assignment in Assignments)
                    {
                        dc.State.SetValue(assignment.Property.GetValue(dc.State), assignment.Value.GetValue(dc.State));
                    }
                }).ConfigureAwait(false);

                Trace.TraceInformation($"[Turn Ended => SetProperties completed]");
            }
            else
            {
                throw new InvalidOperationException("No inspector to use for setting properties");
            }
        }
        /// <summary>
        /// Sends the personal message using bot context and message activity for a user
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="message">The message.</param>
        /// <param name="cancellationToken">Cancelation token</param>
        /// <param name="to">Recipient</param>
        public async Task SendPersonalMessageTo(ITurnContext context, Activity message, CancellationToken cancellationToken, ChannelAccount to)
        {
            var teamsChannelId = context.Activity.ChannelId;
            var botAdapter     = (BotFrameworkAdapter)context.Adapter;
            var serviceUrl     = context.Activity.ServiceUrl;
            var parameters     = new ConversationParameters
            {
                IsGroup  = false,
                Bot      = context.Activity.Recipient,
                Members  = new[] { to },
                TenantId = tenantInfo.Id,
            };

            BotCallbackHandler createConversationcallback = async(createConvContext, createConvCancellationToken) =>
            {
                await createConvContext.SendActivityAsync(message, cancellationToken);
            };
            await botAdapter.CreateConversationAsync(teamsChannelId, serviceUrl, microsoftAppCredentials, parameters, createConversationcallback, cancellationToken);
        }
Example #17
0
        public async Task ProcessActivityAsync(
            MessageEvent message,
            BotCallbackHandler callback = null
            )
        {
            await InitUserIfNeeded();

            switch (message.Type)
            {
            case "message":
                await OnMessageReceived(message, callback);

                break;

            default:
                // TODO: Implement non-message type
                break;
            }
        }
Example #18
0
        public async Task ProcessActivityAsyncCreatesCorrectCredsAndClient(string botAppId, string expectedCallerId, string channelService, string expectedScope, int expectedAppCredentialsCount, int expectedClientCredentialsCount)
        {
            var claims = new List <Claim>();

            if (botAppId != null)
            {
                claims.Add(new Claim(AuthenticationConstants.AudienceClaim, botAppId));
                claims.Add(new Claim(AuthenticationConstants.AppIdClaim, botAppId));
                claims.Add(new Claim(AuthenticationConstants.VersionClaim, "1.0"));
            }

            var identity = new ClaimsIdentity(claims);

            var credentialProvider = new SimpleCredentialProvider {
                AppId = botAppId
            };
            var serviceUrl = "https://smba.trafficmanager.net/amer/";
            var callback   = new BotCallbackHandler((context, ct) =>
            {
                GetAppCredentialsAndAssertValues(context, botAppId, expectedScope, expectedAppCredentialsCount);
                GetConnectorClientsAndAssertValues(
                    context,
                    botAppId,
                    expectedScope,
                    new Uri(serviceUrl),
                    expectedClientCredentialsCount);

                var scope = context.TurnState.Get <string>(BotAdapter.OAuthScopeKey);
                Assert.Equal(expectedCallerId, context.Activity.CallerId);
                return(Task.CompletedTask);
            });

            var sut = new BotFrameworkAdapter(credentialProvider, new SimpleChannelProvider(channelService));
            await sut.ProcessActivityAsync(
                identity,
                new Activity("test")
            {
                ChannelId  = Channels.Emulator,
                ServiceUrl = serviceUrl
            },
                callback,
                CancellationToken.None);
        }
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback)
        {
            var timeout = (int)this.Timeout;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                timeout = int.MaxValue;
            }

            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter((int)timeout);
            IActivity replyActivity = await adapter.GetNextReplyAsync(cts.Token).ConfigureAwait(false);

            if (replyActivity != null)
            {
                ValidateReply((Activity)replyActivity);
                return;
            }
        }
        public async Task ProcessActivity(DirectMessageEvent obj, BotCallbackHandler callback)
        {
            TurnContext context = null;

            try
            {
                var activity = RequestToActivity(obj);
                BotAssert.ActivityNotNull(activity);

                context = new TurnContext(this, activity);

                await RunPipelineAsync(context, callback, default).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await OnTurnError(context, ex);

                throw;
            }
        }
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback)
        {
            if (this.Activity == null)
            {
                throw new Exception("You must define one of Text or Activity properties");
            }

            var activity = ObjectPath.Clone(this.Activity);

            activity.ApplyConversationReference(adapter.Conversation, isIncoming: true);

            if (!string.IsNullOrEmpty(this.User))
            {
                activity.From      = ObjectPath.Clone(activity.From);
                activity.From.Id   = this.User;
                activity.From.Name = this.User;
            }

            await adapter.ProcessActivityAsync(this.Activity, callback, default(CancellationToken)).ConfigureAwait(false);
        }
        private TestFlow CreateFlow(BotCallbackHandler handler, string locale = null)
        {
            var storage    = new MemoryStorage();
            var convoState = new ConversationState(storage);
            var userState  = new UserState(storage);

            var adapter = new TestAdapter(TestAdapter.CreateConversation(MethodBase.GetCurrentMethod().ToString()));

            adapter
            .UseStorage(storage)
            .UseBotState(userState, convoState)
            .Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));

            if (!string.IsNullOrEmpty(locale))
            {
                adapter.Locale = locale;
            }

            return(new TestFlow(adapter, handler));
        }
Example #23
0
            public async Task PollForTokenAsync(PollingParams pollingParams)
            {
                BotCallbackHandler continueCallback = async(context, ctoken) =>
                {
                    // TODO: Should be using OAuthClient
                    //var oauthClient = context.TurnState.Get<OAuthClient>();
                    //var tokenResponse = await oauthClient.UserToken.GetTokenAsync(Activity.From.Id, pollingParams.ConnectionName, Activity.ChannelId, null, ctoken).ConfigureAwait(false);
                    var tokenResponse = await(Adapter as BotFrameworkAdapter).GetUserTokenAsync(context, pollingParams.ConnectionName, null, ctoken).ConfigureAwait(false);

                    if (tokenResponse != null)
                    {
                        // This can be used to short-circuit the polling loop.
                        if (tokenResponse.Properties != null)
                        {
                            tokenResponse.Properties.TryGetValue(TurnStateConstants.TokenPollingSettingsKey, out var tokenPollingSettingsToken);

                            var tokenPollingSettings = tokenPollingSettingsToken?.ToObject <TokenPollingSettings>();
                            if (tokenPollingSettings != null)
                            {
                                Logger.LogInformation($"PollForTokenAsync received new polling settings: timeout={tokenPollingSettings.Timeout}, interval={tokenPollingSettings.Interval}", tokenPollingSettings);
                                pollingParams.ShouldEndPolling = tokenPollingSettings.Timeout <= 0 ? true : pollingParams.ShouldEndPolling;                                                    // Timeout now and stop polling
                                pollingParams.PollingInterval  = tokenPollingSettings.Interval > 0 ? TimeSpan.FromMilliseconds(tokenPollingSettings.Interval) : pollingParams.PollingInterval; // Only overrides if it is set.
                            }
                        }

                        // once there is a token, send it to the bot and stop polling
                        if (tokenResponse.Token != null)
                        {
                            var tokenResponseActivityEvent = CreateTokenResponse(Activity.GetConversationReference(), tokenResponse.Token, pollingParams.ConnectionName);
                            await Adapter.ProcessActivityAsync(Identity, tokenResponseActivityEvent, Callback, ctoken).ConfigureAwait(false);

                            pollingParams.ShouldEndPolling = true;
                            pollingParams.SentToken        = true;

                            Logger.LogInformation("PollForTokenAsync completed with a token", Activity);
                        }
                    }
                };

                await Adapter.ContinueConversationAsync(Identity, Activity.GetConversationReference(), continueCallback, cancellationToken : CancellationToken).ConfigureAwait(false);
            }
Example #24
0
        public async Task ProcessActivityAsyncCreatesCorrectCredsAndClient()
        {
            var botAppId = "00000000-0000-0000-0000-000000000001";
            var claims   = new List <Claim>
            {
                new Claim(AuthenticationConstants.AudienceClaim, botAppId),
                new Claim(AuthenticationConstants.AppIdClaim, botAppId),
                new Claim(AuthenticationConstants.VersionClaim, "1.0")
            };
            var identity = new ClaimsIdentity(claims);

            var credentialProvider = new SimpleCredentialProvider()
            {
                AppId = botAppId
            };
            var serviceUrl = "https://smba.trafficmanager.net/amer/";
            var callback   = new BotCallbackHandler(async(context, ct) =>
            {
                GetCredsAndAssertValues(context, botAppId, AuthenticationConstants.ToChannelFromBotOAuthScope, 1);
                GetClientAndAssertValues(
                    context,
                    botAppId,
                    AuthenticationConstants.ToChannelFromBotOAuthScope,
                    new Uri(serviceUrl),
                    1);

                var scope = context.TurnState.Get <string>(BotAdapter.OAuthScopeKey);
                Assert.AreEqual(AuthenticationConstants.ToChannelFromBotOAuthScope, scope);
            });

            var sut = new BotFrameworkAdapter(credentialProvider);
            await sut.ProcessActivityAsync(
                identity,
                new Activity("test")
            {
                ChannelId  = Channels.Emulator,
                ServiceUrl = serviceUrl
            },
                callback,
                CancellationToken.None);
        }
        private async Task <ResourceResponse> ProcessActivityAsync(ClaimsIdentity claimsIdentity, string conversationId, string replyToActivityId, Activity activity, CancellationToken cancellationToken)
        {
            var conversationReference = await _conversationIdIdFactory.GetConversationReferenceAsync(conversationId, CancellationToken.None).ConfigureAwait(false);

            if (conversationReference == null)
            {
                throw new KeyNotFoundException();
            }

            var skillConversationReference = activity.GetConversationReference();

            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                turnContext.TurnState.Add(SkillConversationReferenceKey, skillConversationReference);

                activity.ApplyConversationReference(conversationReference);

                turnContext.Activity.Id = replyToActivityId;
                switch (activity.Type)
                {
                case ActivityTypes.EndOfConversation:
                    await _conversationIdIdFactory.DeleteConversationReferenceAsync(conversationId, cancellationToken).ConfigureAwait(false);
                    ApplyEoCToTurnContextActivity(turnContext, activity);
                    await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false);
                    break;

                case ActivityTypes.Event:
                    ApplyEventToTurnContextActivity(turnContext, activity);
                    await _bot.OnTurnAsync(turnContext, ct).ConfigureAwait(false);
                    break;

                default:
                    await turnContext.SendActivityAsync(activity, cancellationToken).ConfigureAwait(false);
                    break;
                }
            });

            await _adapter.ContinueConversationAsync(claimsIdentity, conversationReference, callback, cancellationToken).ConfigureAwait(false);

            return(new ResourceResponse(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)));
        }
        /// <summary>
        /// Primary adapter method for processing activities sent from calling bot.
        /// </summary>
        /// <param name="activity">The activity to process.</param>
        /// <param name="callback">The BotCallBackHandler to call on completion.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>The response to the activity.</returns>
        public async Task <InvokeResponse> ProcessActivityAsync(Activity activity, BotCallbackHandler callback, CancellationToken cancellationToken)
        {
            BotAssert.ActivityNotNull(activity);

            _botTelemetryClient.TrackTrace($"Received an incoming activity. ActivityId: {activity.Id}", Severity.Information, null);

            using (var context = new TurnContext(this, activity))
            {
                await RunPipelineAsync(context, callback, cancellationToken).ConfigureAwait(false);

                // We do not support Invoke in websocket transport
                if (activity.Type == ActivityTypes.Invoke)
                {
                    return(new InvokeResponse {
                        Status = (int)HttpStatusCode.NotImplemented
                    });
                }

                return(null);
            }
        }
        /// <inheritdoc/>
        public override async Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            var timeout = (int)Timeout;

            if (Debugger.IsAttached)
            {
                timeout = int.MaxValue;
            }

            using (var cts = new CancellationTokenSource())
            {
                cts.CancelAfter((int)timeout);
                var replyActivity = await adapter.GetNextReplyAsync(cts.Token).ConfigureAwait(false);

                if (replyActivity != null)
                {
                    ValidateReply((Activity)replyActivity);
                    return;
                }
            }
        }
Example #28
0
        /// <inheritdoc/>
        public async override Task ExecuteAsync(TestAdapter adapter, BotCallbackHandler callback, Inspector inspector = null)
        {
            if (Name == null)
            {
                throw new InvalidOperationException("You must define the event name.");
            }

            var eventActivity = adapter.MakeActivity();

            eventActivity.Type  = ActivityTypes.Event;
            eventActivity.Name  = Name;
            eventActivity.Value = Value;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            await adapter.ProcessActivityAsync(eventActivity, callback, default).ConfigureAwait(false);

            sw.Stop();
            Trace.TraceInformation($"[Turn Ended => {sw.ElapsedMilliseconds} ms processing CustomEvent: {Name} ]");
        }
Example #29
0
        public async Task OAuthPromptInNotSupportedChannelShouldAddSignInCard()
        {
            var convoState  = new ConversationState(new MemoryStorage());
            var dialogState = convoState.CreateProperty <DialogState>("dialogState");

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(convoState));

            // Create new DialogSet
            var dialogs = new DialogSet(dialogState);

            dialogs.Add(new OAuthPrompt("OAuthPrompt", new OAuthPromptSettings()));

            BotCallbackHandler botCallbackHandler = async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);

                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.PromptAsync("OAuthPrompt", new PromptOptions(), cancellationToken : cancellationToken);
                }
            };

            var initialActivity = new Activity()
            {
                ChannelId = Channels.Skype,
                Text      = "hello"
            };

            await new TestFlow(adapter, botCallbackHandler)
            .Send(initialActivity)
            .AssertReply(activity =>
            {
                Assert.Single(((Activity)activity).Attachments);
                Assert.Equal(SigninCard.ContentType, ((Activity)activity).Attachments[0].ContentType);
            })
            .StartTestAsync();
        }
Example #30
0
        private async Task TestActivityCallback(Activity activity)
        {
            BotCallbackHandler botCallback = null;

            _mockAdapter.Setup(x => x.ContinueConversationAsync(It.IsAny <ClaimsIdentity>(), It.IsAny <ConversationReference>(), It.IsAny <string>(), It.IsAny <BotCallbackHandler>(), It.IsAny <CancellationToken>()))
            .Callback <ClaimsIdentity, ConversationReference, string, BotCallbackHandler, CancellationToken>((identity, reference, audience, callback, cancellationToken) =>
            {
                botCallback = callback;
                Console.WriteLine("blah");
            });

            var sut = CreateSkillHandlerForTesting();

            var activityId = Guid.NewGuid().ToString("N");

            activity.ApplyConversationReference(_conversationReference);

            await sut.TestOnReplyToActivityAsync(_claimsIdentity, _conversationId, activityId, activity, CancellationToken.None);

            Assert.IsNotNull(botCallback);
            await botCallback.Invoke(new TurnContext(_mockAdapter.Object, activity), CancellationToken.None);
        }