Ejemplo n.º 1
0
        private static async Task <IActivity> ProcessActivity(string channelId, string channelDataTenantId, string conversationTenantId)
        {
            IActivity activity               = null;
            var       mockClaims             = new Mock <ClaimsIdentity>();
            var       mockCredentialProvider = new Mock <ICredentialProvider>();

            var sut = new BotFrameworkAdapter(mockCredentialProvider.Object);
            await sut.ProcessActivityAsync(
                mockClaims.Object,
                new Activity("test")
            {
                ChannelId   = channelId,
                ServiceUrl  = "https://smba.trafficmanager.net/amer/",
                ChannelData = new JObject
                {
                    ["tenant"] = new JObject
                    {
                        ["id"] = channelDataTenantId
                    },
                },
                Conversation = new ConversationAccount
                {
                    TenantId = conversationTenantId
                },
            },
                (context, token) =>
            {
                activity = context.Activity;
                return(Task.CompletedTask);
            },
                CancellationToken.None);

            return(activity);
        }
Ejemplo n.º 2
0
        public async Task ProcessContinueConversationEvent()
        {
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();
            var httpClient             = new HttpClient(mockHttpMessageHandler.Object);
            var adapter = new BotFrameworkAdapter(mockCredentialProvider.Object, customHttpClient: httpClient);

            ConversationReference cr = new ConversationReference
            {
                ActivityId = "activityId",
                Bot        = new ChannelAccount
                {
                    Id   = "channelId",
                    Name = "testChannelAccount",
                    Role = "bot",
                },
                ChannelId    = "testChannel",
                ServiceUrl   = "https://fake.service.url",
                Conversation = new ConversationAccount
                {
                    ConversationType = string.Empty,
                    Id      = "testConversationId",
                    IsGroup = false,
                    Name    = "testConversationName",
                    Role    = "user",
                },
                User = new ChannelAccount
                {
                    Id   = "channelId",
                    Name = "testChannelAccount",
                    Role = "bot",
                },
            };

            var activity = cr.GetContinuationActivity();

            activity.Value = "test";

            // Create ClaimsIdentity that represents Skill1-to-Skill1 communication
            var appId = "00000000-0000-0000-0000-000000skill1";

            var claims = new List <Claim>
            {
                new Claim(AuthenticationConstants.AudienceClaim, appId),
                new Claim(AuthenticationConstants.AppIdClaim, appId),
                new Claim(AuthenticationConstants.VersionClaim, "1.0")
            };
            var identity = new ClaimsIdentity(claims);

            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                var cr2        = turnContext.Activity.GetConversationReference();
                cr.ActivityId  = null; // activityids will be different...
                cr2.ActivityId = null;
                Assert.Equal(JsonConvert.SerializeObject(cr), JsonConvert.SerializeObject(cr2));
                Assert.Equal("test", (string)turnContext.Activity.Value);
            });

            await adapter.ProcessActivityAsync(identity, (Activity)activity, callback, default);
Ejemplo n.º 3
0
        protected override async Task <InvokeResponse> ProcessMessageRequestAsync(HttpRequestMessage request, BotFrameworkAdapter botFrameworkAdapter, Func <ITurnContext, Task> botCallbackHandler, CancellationToken cancellationToken)
        {
            var activity = await request.Content.ReadAsAsync <Activity>(BotMessageHandlerBase.BotMessageMediaTypeFormatters, cancellationToken);

            var invokeResponse = await botFrameworkAdapter.ProcessActivityAsync(
                request.Headers.Authorization?.ToString(),
                activity,
                botCallbackHandler,
                cancellationToken);

            return(invokeResponse);
        }
Ejemplo n.º 4
0
        public async Task PostAsync()
        {
            // Get the activity from the HTTP request.
            Activity activity = default(Activity);

            using (JsonTextReader bodyReader
                       = new JsonTextReader(new StreamReader(Request.Body, Encoding.UTF8)))
            {
                activity = BotMessageSerializer.Deserialize <Activity>(bodyReader);
            }

            // Create an adapter.
            var credentialProvider  = new SimpleCredentialProvider();
            var botFrameworkAdapter = new BotFrameworkAdapter(credentialProvider);

            botFrameworkAdapter.OnTurnError = async(turnContext, excepption) =>
            {
                // Code to run when the adapter catches an othwise unhandled exception.
                await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");

                Console.Error.WriteLine($"{excepption.GetType().Name} encountered:");
                Console.Error.WriteLine(excepption.Message);
                Console.Error.WriteLine(excepption.StackTrace);
            };

            // Use the adapter to authenticate and forward incoming activities.
            InvokeResponse invokeResponse = await botFrameworkAdapter.ProcessActivityAsync(
                Request.Headers["Authorization"],
                activity,
                OnTurnAsync,
                default(CancellationToken));

            if (invokeResponse == null)
            {
                // For non-invoke activities, acknowledge the activity.
                Response.StatusCode = (int)HttpStatusCode.OK;
            }
            else
            {
                // For invoke activities, include a response payload.
                Response.ContentType = "application/json";
                Response.StatusCode  = invokeResponse.Status;
                using (StreamWriter writer = new StreamWriter(Response.Body))
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
                    {
                        BotMessageSerializer.Serialize(jsonWriter, invokeResponse.Body);
                    }
            }
        }
Ejemplo n.º 5
0
        protected override async Task <InvokeResponse> ProcessMessageRequestAsync(HttpRequestMessage request, BotFrameworkAdapter botFrameworkAdapter, BotCallbackHandler botCallbackHandler, CancellationToken cancellationToken)
        {
            var activity = await request.Content.ReadAsAsync <Activity>(BotMessageHandlerBase.BotMessageMediaTypeFormatters, cancellationToken).ConfigureAwait(false);

#pragma warning disable UseConfigureAwait // Use ConfigureAwait
            var invokeResponse = await botFrameworkAdapter.ProcessActivityAsync(
                request.Headers.Authorization?.ToString(),
                activity,
                botCallbackHandler,
                cancellationToken);

#pragma warning restore UseConfigureAwait // Use ConfigureAwait

            return(invokeResponse);
        }
Ejemplo n.º 6
0
        protected override async Task <InvokeResponse> ProcessMessageRequestAsync(HttpRequest request, BotFrameworkAdapter botFrameworkAdapter, Func <ITurnContext, Task> botCallbackHandler, CancellationToken cancellationToken)
        {
            var activity = default(Activity);

            using (var bodyReader = new JsonTextReader(new StreamReader(request.Body, Encoding.UTF8)))
            {
                activity = BotMessageHandlerBase.BotMessageSerializer.Deserialize <Activity>(bodyReader);
            }

            var invokeResponse = await botFrameworkAdapter.ProcessActivityAsync(
                request.Headers["Authorization"],
                activity,
                botCallbackHandler,
                cancellationToken);

            return(invokeResponse);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public async Task Post()
        {
            var activity = default(Activity);

            using (var bodyReader = new JsonTextReader(new StreamReader(Request.Body, Encoding.UTF8)))
            {
                activity = BotMessageSerializer.Deserialize <Activity>(bodyReader);
            }

            var options = new BotFrameworkOptions();

            var botFrameworkAdapter = new BotFrameworkAdapter(options.CredentialProvider);

            await botFrameworkAdapter.ProcessActivityAsync(
                Request.Headers["Authorization"],
                activity,
                OnTurnAsync,
                default(CancellationToken));
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
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);
        }
        public async Task DeliveryModeExpectReplies()
        {
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());

            var httpClient = new HttpClient(mockHttpMessageHandler.Object);
            var adapter    = new BotFrameworkAdapter(new SimpleCredentialProvider(), customHttpClient: httpClient);

            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 1"), ct);
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 2"), ct);
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 3"), ct);
            });

            var inboundActivity = new Activity
            {
                Type         = ActivityTypes.Message,
                ChannelId    = Channels.Emulator,
                ServiceUrl   = "http://tempuri.org/whatever",
                DeliveryMode = DeliveryModes.ExpectReplies,
                Text         = "hello world"
            };

            var invokeResponse = await adapter.ProcessActivityAsync(string.Empty, inboundActivity, callback, CancellationToken.None);

            Assert.AreEqual((int)HttpStatusCode.OK, invokeResponse.Status);
            var activities = ((ExpectedReplies)invokeResponse.Body).Activities;

            Assert.AreEqual(3, activities.Count);
            Assert.AreEqual("activity 1", activities[0].Text);
            Assert.AreEqual("activity 2", activities[1].Text);
            Assert.AreEqual("activity 3", activities[2].Text);
            mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Never(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());
        }
        public async Task DeliveryModeNormal()
        {
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(CreateInternalHttpResponse()));

            var httpClient = new HttpClient(mockHttpMessageHandler.Object);
            var adapter    = new BotFrameworkAdapter(new SimpleCredentialProvider(), customHttpClient: httpClient);

            var callback = new BotCallbackHandler(async(turnContext, ct) =>
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 1"), ct);
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 2"), ct);
                await turnContext.SendActivityAsync(MessageFactory.Text("activity 3"), ct);
            });

            var inboundActivity = new Activity
            {
                Type         = ActivityTypes.Message,
                ChannelId    = Channels.Emulator,
                ServiceUrl   = "http://tempuri.org/whatever",
                DeliveryMode = DeliveryModes.Normal,
                Text         = "hello world",
                Conversation = new ConversationAccount {
                    Id = "conversationId"
                }
            };

            var invokeResponse = await adapter.ProcessActivityAsync(string.Empty, inboundActivity, callback, CancellationToken.None);

            Assert.IsNull(invokeResponse);
            mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Exactly(3), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());
        }
Ejemplo n.º 13
0
        public async Task PostAsync()
        {
            var activity = default(Activity);

            using (var bodyReader = new JsonTextReader(new StreamReader(Request.Body, Encoding.UTF8)))
            {
                activity = BotMessageSerializer.Deserialize <Activity>(bodyReader);
            }

            var botFrameworkAdapter = new BotFrameworkAdapter(_credentialProvider, middleware: new AutoSaveStateMiddleware(Accessors.ConversationState));

            var invokeResponse = await botFrameworkAdapter.ProcessActivityAsync(
                Request.Headers["Authorization"],
                activity,
                OnTurnAsync,
                default(CancellationToken));

            if (invokeResponse == null)
            {
                Response.StatusCode = (int)HttpStatusCode.OK;
            }
            else
            {
                // Return the exception in the body of the response
                Response.ContentType = "application/json";
                Response.StatusCode  = invokeResponse.Status;

                using (var writer = new StreamWriter(Response.Body))
                {
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        BotMessageSerializer.Serialize(jsonWriter, invokeResponse.Body);
                    }
                }
            }
        }