public SelectReactionActivity(TurnContext currentTurn, Player player, AttackEffect attackEffect)
     : base(currentTurn.Game.Log, player, "Select a reaction to use, click Done when finished.", SelectionSpecifications.SelectUpToXCards(1))
 {
     _currentTurn = currentTurn;
     _attackEffect = attackEffect;
     Specification.CardTypeRestriction = typeof (IReactionCard);
 }
示例#2
0
 public static ISelectCardsActivity DiscardCards(TurnContext context, Player player, int numberToDiscard)
 {
     return new SelectCardsActivity(
         context.Game.Log, player, string.Format("Select {0} card(s) to discard", numberToDiscard),
         SelectionSpecifications.SelectExactlyXCards(numberToDiscard))
     {
         AfterCardsSelected = cards => context.DiscardCards(player, cards)
     };
 }
示例#3
0
        public static IActivity GainOpponentsCardChoice(TurnContext context, Card card, Player cardOwner)
        {
            var activity = new ChoiceActivity(context, context.ActivePlayer,
                string.Format("Gain {0}'s {1}?", cardOwner.Name, card), Choice.Yes, Choice.No);

            activity.ActOnChoice = choice =>
            {
                if (choice == Choice.Yes)
                {
                    card.MoveTo(context.ActivePlayer.Discards);
                    context.Game.Log.LogGain(context.ActivePlayer, card);
                }
            };

            return activity;
        }
        public async Task Intents_ValidateEnablerOrder()
        {
            IntentRecognizerMiddleware m = new IntentRecognizerMiddleware();
            string shouldRun             = "first";

            /*
             *  Filters are required to run in reverse order. This code validates that by registering 3 filters and
             *  running a simple state machine across them.
             */
            m.OnEnabled(async(context) =>
            {
                Assert.IsTrue(shouldRun == "first", "1st enabler did not run first.");
                shouldRun = "second";
                return(true);
            });

            m.OnEnabled(async(context) =>
            {
                Assert.IsTrue(shouldRun == "second", "2nd enabler did not run second");
                shouldRun = "third";

                return(true);
            });

            m.OnEnabled(async(context) =>
            {
                Assert.IsTrue(shouldRun == "third", "3rd enabler did not run last");
                shouldRun = "done";

                return(true);
            });

            TurnContext bc = TestUtilities.CreateEmptyContext();

            shouldRun = "first";

            var resultingIntents = await m.Recognize(bc);

            Assert.IsTrue(shouldRun == "done", "Final recognizer did not run");
        }
示例#5
0
        /// <summary>
        /// Retrieve a signin link for a user based on the Connection Name. This is then used for the user to click and authenticate, generating a token returned back to the Token store.
        /// </summary>
        /// <param name="userId">The user id value.</param>
        /// <param name="credentialProvider">The credential provider value.</param>
        /// <param name="connectionName">The connection name value.</param>
        /// <param name="finalRedirect">The final redirect value.</param>
        /// <returns>Sign in link string value.</returns>
        public async Task <string> GetSignInLinkAsync(string userId, ICredentialProvider credentialProvider, string connectionName, string finalRedirect)
        {
            // The BotFramework Adapter, Bot ApplicationID and Bot Secret is required to access the Token APIs
            // These must match the Bot making use of the Linked Accounts feature.
            var adapter        = new BotFrameworkAdapter(credentialProvider);
            var botAppId       = ((ConfigurationCredentialProvider)credentialProvider).AppId;
            var botAppPassword = ((ConfigurationCredentialProvider)credentialProvider).Password;

            string link = null;

            using (var context = new TurnContext(adapter, new Microsoft.Bot.Schema.Activity
            {
                From = new ChannelAccount()
                {
                    Id = userId
                }
            }))
            {
                var connectorClient = new ConnectorClient(new Uri(TokenServiceUrl), botAppId, botAppPassword);
                context.TurnState.Add <IConnectorClient>(connectorClient);
                // Add BotIdentity
                context.TurnState.Add <IIdentity>(BotAdapter.BotIdentityKey, new ClaimsIdentity(new List <Claim>
                {
                    new Claim(AuthenticationConstants.AudienceClaim, botAppId),
                }));

                // Retrieve a signin link for a given Connection Name and UserId
                link = await adapter.GetOauthSignInLinkAsync(context, connectionName, userId, finalRedirect);

                // Add on code_challenge (SessionId) into the redirect
                var sessionId = SessionController.Sessions.FirstOrDefault(s => s.Key == userId).Value;

                if (!string.IsNullOrEmpty(sessionId))
                {
                    link += HttpUtility.UrlEncode($"&code_challenge={sessionId}");
                }
            }

            return(link);
        }
示例#6
0
        public async Task TestAdapter_SignOutAll()
        {
            TestAdapter adapter   = new TestAdapter();
            string      channelId = "directline";
            string      userId    = "testUser";
            string      token     = "abc123";
            Activity    activity  = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            adapter.AddUserToken("ABC", channelId, userId, token);
            adapter.AddUserToken("DEF", channelId, userId, token);

            var tokenResponse = await adapter.GetUserTokenAsync(turnContext, "ABC", null, CancellationToken.None);

            Assert.IsNotNull(tokenResponse);
            Assert.AreEqual(token, tokenResponse.Token);
            Assert.AreEqual("ABC", tokenResponse.ConnectionName);

            tokenResponse = await adapter.GetUserTokenAsync(turnContext, "DEF", null, CancellationToken.None);

            Assert.IsNotNull(tokenResponse);
            Assert.AreEqual(token, tokenResponse.Token);
            Assert.AreEqual("DEF", tokenResponse.ConnectionName);

            await adapter.SignOutUserAsync(turnContext, null, userId);

            tokenResponse = await adapter.GetUserTokenAsync(turnContext, "ABC", null, CancellationToken.None);

            Assert.IsNull(tokenResponse);
            tokenResponse = await adapter.GetUserTokenAsync(turnContext, "DEF", null, CancellationToken.None);

            Assert.IsNull(tokenResponse);
        }
        public async Task Intents_MutateIntentResult()
        {
            string targetName   = Guid.NewGuid().ToString();
            string replacedName = Guid.NewGuid().ToString();

            IntentRecognizerMiddleware m = new IntentRecognizerMiddleware();

            m.OnRecognize(async(context) =>
            {
                return(new List <Intent>
                {
                    new Intent()
                    {
                        Name = targetName
                    },
                });
            });

            m.OnFilter(async(context, intentList) =>
            {
                // When this code is called, the intent should already have been recognized. This code, as "filter code"
                // has the oppertunity to manipulate that intent.

                Assert.IsTrue(intentList.Count == 1, "Expecting exactly 1 intent");
                Assert.IsTrue(intentList.First().Name == targetName, $"Unexpected Intent Name. Expected {targetName}");

                // replace the name of the intent. Do this via the Context to vette paremeter passing
                intentList[0].Name = replacedName;
            });

            TurnContext bc = TestUtilities.CreateEmptyContext();

            // Test that the Intent comes back has been "filtered" to have the revised name

            var resultingIntents = await m.Recognize(bc);

            Assert.IsTrue(resultingIntents.Count == 1, "Expected exactly 1 intent");
            Assert.IsTrue(resultingIntents.First().Name == replacedName, $"Unexpected Intent Name. Expected {replacedName}");
        }
        public async Task TestConversationUpdateTeamsChannelCreated()
        {
            // Arrange
            var activity = new Activity
            {
                Type        = ActivityTypes.ConversationUpdate,
                ChannelData = new TeamsChannelData {
                    EventType = "channelCreated"
                },
            };
            var turnContext = new TurnContext(new NotImplementedAdapter(), activity);

            // Act
            var bot = new TestActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.AreEqual(2, bot.Record.Count);
            Assert.AreEqual("OnConversationUpdateActivityAsync", bot.Record[0]);
            Assert.AreEqual("OnTeamsChannelCreatedAsync", bot.Record[1]);
        }
示例#9
0
文件: Mine.cs 项目: vladdou/Dominion
            public override void Resolve(TurnContext context, ICard source)
            {
                if (context.ActivePlayer.Hand.OfType <ITreasureCard>().Any())
                {
                    var activity = new SelectCardsActivity(context, "Select a treasure card to mine",
                                                           SelectionSpecifications.SelectExactlyXCards(1), source);

                    activity.Specification.CardTypeRestriction = typeof(ITreasureCard);
                    activity.AfterCardsSelected = cardList =>
                    {
                        var cardToMine = cardList.Single();
                        context.Trash(context.ActivePlayer, cardToMine);
                        AddGainActivity(context.Game.Log, context.ActivePlayer, cardToMine.Cost + 3, source);
                    };

                    _activities.Add(activity);
                }
                else
                {
                    context.Game.Log.LogMessage("No treasure cards to trash.");
                }
            }
示例#10
0
        public static async Task Test(BotAdapter adapter)
        {
            using var turnContext = new TurnContext(adapter, new Activity());

            var activities = new[]
            {
                new Activity(ActivityTypes.Delay, value: 275),
                new Activity(ActivityTypes.Delay, value: 275L),
                new Activity(ActivityTypes.Delay, value: 275F),
                new Activity(ActivityTypes.Delay, value: 275D),
            };

            Stopwatch sw = new Stopwatch();

            sw.Start();

            await adapter.SendActivitiesAsync(turnContext, activities, default);

            sw.Stop();

            Assert.True(sw.Elapsed.TotalSeconds > 1, $"Delay only lasted {sw.Elapsed}");
        }
示例#11
0
            public override void Resolve(TurnContext context, ICard source)
            {
                var cardCount = context.ActivePlayer.Hand.CardCount;
                var gainUtil  = new GainUtility(context, context.ActivePlayer);

                if (cardCount < 2)
                {
                    context.TrashAll(context.ActivePlayer, context.ActivePlayer.Hand);
                }
                else if (cardCount == 2)
                {
                    context.TrashAll(context.ActivePlayer, context.ActivePlayer.Hand);
                    gainUtil.Gain <Silver>(context.ActivePlayer.Hand);
                }
                else
                {
                    var activity = Activities.SelectXCardsToTrash(context, context.ActivePlayer, 2, source,
                                                                  () => gainUtil.Gain <Silver>(context.ActivePlayer.Hand));

                    _activities.Add(activity);
                }
            }
示例#12
0
        public async Task TestAdapter_GetSignInLinkWithNoUserId()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId
                }
            };
            TurnContext turnContext = new TurnContext(adapter, activity);


            var link = await adapter.GetOauthSignInLinkAsync(turnContext, connectionName, CancellationToken.None);

            Assert.IsNotNull(link);
            Assert.IsTrue(link.Length > 0);
        }
        public async Task TestInvokeActivity()
        {
            // Arrange
            var adapter  = new TestInvokeAdapter();
            var activity = new Activity
            {
                Type = ActivityTypes.Invoke
            };
            var turnContext = new TurnContext(adapter, activity);

            // Act
            var bot = new TestActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.AreEqual(2, bot.Record.Count);
            Assert.AreEqual(bot.Record[0], "OnInvokeActivityAsync");
            Assert.AreEqual(bot.Record[1], "OnInvokeAsync");
            Assert.IsNotNull(adapter.Activity);
            Assert.AreEqual((int)HttpStatusCode.OK, ((InvokeResponse)((Activity)adapter.Activity).Value).Status);
        }
示例#14
0
        public void UserAgentContainsProductVersion()
        {
            var application = new LuisApplication
            {
                EndpointKey   = "this-is-not-a-key",
                ApplicationId = "this-is-not-an-application-id",
                Endpoint      = "https://westus.api.cognitive.microsoft.com",
            };

            var clientHandler = new EmptyLuisResponseClientHandler();

            var recognizer = new LuisRecognizer(new LuisRecognizerOptionsV2(application), clientHandler: clientHandler);

            var adapter  = new NullAdapter();
            var activity = new Activity
            {
                Type         = ActivityTypes.Message,
                Text         = "please book from May 5 to June 6",
                Recipient    = new ChannelAccount(),        // to no where
                From         = new ChannelAccount(),        // from no one
                Conversation = new ConversationAccount(),   // on no conversation
            };

            var turnContext = new TurnContext(adapter, activity);

            var recognizerResult = recognizer.RecognizeAsync(turnContext, CancellationToken.None).Result;

            Assert.NotNull(recognizerResult);

            var userAgent = clientHandler.UserAgent;

            // Verify we didn't unintentionally stamp on the user-agent from the client.
            Assert.Contains("Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.LUISRuntimeClient", userAgent);

            // And that we added the bot.builder package details.
            var majorVersion = typeof(ConnectorClient).GetTypeInfo().Assembly.GetName().Version.Major;

            Assert.Contains($"microsoft.bot.builder.ai.luis/{majorVersion}", userAgent.ToLower());
        }
示例#15
0
        public async Task UpdateActivityAsyncShouldFailWithNullActivityConversation()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            slackApi.Setup(x => x.TestAuthAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult("mockedUserId"));

            var slackAdapter = new SlackAdapter(slackApi.Object);

            var activity = new Activity
            {
                Id           = "testId",
                Conversation = null,
            };

            using (var turnContext = new TurnContext(slackAdapter, activity))
            {
                await Assert.ThrowsAsync <ArgumentException>(async() =>
                {
                    await slackAdapter.UpdateActivityAsync(turnContext, activity, default);
                });
            }
        }
示例#16
0
        public override async Task ContinueConversationAsync(string botId, ConversationReference reference, BotCallbackHandler callback, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(botId))
            {
                throw new ArgumentNullException(nameof(botId));
            }

            if (reference == null)
            {
                throw new ArgumentNullException(nameof(reference));
            }

            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            using (var context = new TurnContext(this, reference.GetContinuationActivity()))
            {
                await RunPipelineAsync(context, callback, cancellationToken);
            }
        }
示例#17
0
        public async Task <IActionResult> PostV3ConversationsActivity(
            string conversationId,
            string activityId,
            CancellationToken cancellationToken)
        {
            // XXX 実装はアダプタの側にあるべきなんだろうな
            // XXX Validate
            string body;

            using (var sr = new StreamReader(Request.Body))
            {
                body = await sr.ReadToEndAsync();
            }
            var requestActivity = JsonConvert.DeserializeObject <Activity>(body);

            using (var turnContext = new TurnContext(_adapter, requestActivity))
            {
                var res = await _adapter.SendActivitiesAsync(turnContext, new Activity[] { requestActivity }, cancellationToken);

                return(Ok(res[0]));
            }
        }
        /// <summary>
        /// Creates a conversation on the specified channel.
        /// </summary>
        /// <param name="channelId">The ID for the channel.</param>
        /// <param name="serviceUrl">The channel's service URL endpoint.</param>
        /// <param name="credentials">The application credentials for the bot.</param>
        /// <param name="conversationParameters">The conversation information to use to
        /// create the conversation.</param>
        /// <param name="callback">The method to call for the resulting bot turn.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        /// <remarks>To start a conversation, your bot must know its account information
        /// and the user's account information on that channel.
        /// Most channels only support initiating a direct message (non-group) conversation.
        /// <para>The adapter attempts to create a new conversation on the channel, and
        /// then sends a <c>conversationUpdate</c> activity through its middleware pipeline
        /// to the <paramref name="callback"/> method.</para>
        /// <para>If the conversation is established with the
        /// specified users, the ID of the activity's <see cref="IActivity.Conversation"/>
        /// will contain the ID of the new conversation.</para>
        /// </remarks>
        public virtual async Task CreateConversation(string channelId, string serviceUrl, MicrosoftAppCredentials credentials, ConversationParameters conversationParameters, Func <ITurnContext, Task> callback)
        {
            var connectorClient = this.CreateConnectorClient(serviceUrl, credentials);

            var result = await connectorClient.Conversations.CreateConversationAsync(conversationParameters).ConfigureAwait(false);

            // Create a conversation update activity to represent the result.
            var conversationUpdate = Activity.CreateConversationUpdateActivity();

            conversationUpdate.ChannelId    = channelId;
            conversationUpdate.TopicName    = conversationParameters.TopicName;
            conversationUpdate.ServiceUrl   = serviceUrl;
            conversationUpdate.MembersAdded = conversationParameters.Members;
            conversationUpdate.Id           = result.ActivityId ?? Guid.NewGuid().ToString("n");
            conversationUpdate.Conversation = new ConversationAccount(id: result.Id);
            conversationUpdate.Recipient    = conversationParameters.Bot;

            using (TurnContext context = new TurnContext(this, (Activity)conversationUpdate))
            {
                await this.RunPipeline(context, callback).ConfigureAwait(false);
            }
        }
示例#19
0
        public Task ProcessActivity(Activity activity, Func <ITurnContext, Task> callback, CancellationTokenSource cancelToken = null)
        {
            lock (this.ConversationReference)
            {
                // ready for next reply
                if (activity.Type == null)
                {
                    activity.Type = ActivityTypes.Message;
                }
                activity.ChannelId    = this.ConversationReference.ChannelId;
                activity.From         = this.ConversationReference.User;
                activity.Recipient    = this.ConversationReference.Bot;
                activity.Conversation = this.ConversationReference.Conversation;
                activity.ServiceUrl   = this.ConversationReference.ServiceUrl;

                var id = activity.Id = (this._nextId++).ToString();
            }

            var context = new TurnContext(this, activity);

            return(base.RunPipeline(context, callback, cancelToken));
        }
示例#20
0
        public async Task TestAdapter_GetUserTokenAsyncReturnsTokenWithMagicCode()
        {
            TestAdapter adapter        = new TestAdapter();
            string      connectionName = "myConnection";
            string      channelId      = "directline";
            string      userId         = "testUser";
            string      token          = "abc123";
            string      magicCode      = "888999";
            Activity    activity       = new Activity()
            {
                ChannelId = channelId,
                From      = new ChannelAccount()
                {
                    Id = userId,
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            adapter.AddUserToken(connectionName, channelId, userId, token, magicCode);

            // First it's null
            var tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, null, CancellationToken.None);

            Assert.IsNull(tokenResponse);

            // Can be retreived with magic code
            tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, magicCode, CancellationToken.None);

            Assert.IsNotNull(tokenResponse);
            Assert.AreEqual(token, tokenResponse.Token);
            Assert.AreEqual(connectionName, tokenResponse.ConnectionName);

            // Then can be retreived without magic code
            tokenResponse = await adapter.GetUserTokenAsync(turnContext, connectionName, null, CancellationToken.None);

            Assert.IsNotNull(tokenResponse);
            Assert.AreEqual(token, tokenResponse.Token);
            Assert.AreEqual(connectionName, tokenResponse.ConnectionName);
        }
示例#21
0
        public void Play(TurnContext context)
        {
            var activity = Activities.GainACardCostingUpToX(context.Game.Log, context.ActivePlayer, 4, this);

            activity.AfterCardGained = card =>
            {
                if (card is IActionCard)
                {
                    context.RemainingActions += 1;
                }
                if (card is ITreasureCard)
                {
                    context.AvailableSpend += 1;
                }
                if (card is IVictoryCard)
                {
                    context.DrawCards(1);
                }
            };

            context.AddSingleActivity(activity, this);
        }
        /// <summary>
        /// Enumerate the Linked Account status for a given UserId and return status information.
        /// </summary>
        /// <param name="userId">User Id value.</param>
        /// <param name="credentialProvider">The credential provider value.</param>
        /// <returns>Array of TokenStatus.</returns>
        public async Task <TokenStatus[]> GetTokenStatusAsync(string userId, ICredentialProvider credentialProvider)
        {
            // The BotFramework Adapter, Bot ApplicationID and Bot Secret is required to access the Token APIs
            // These must match the Bot making use of the Linked Accounts feature.
            var adapter        = new BotFrameworkAdapter(credentialProvider);
            var botAppId       = ((ConfigurationCredentialProvider)credentialProvider).AppId;
            var botAppPassword = ((ConfigurationCredentialProvider)credentialProvider).Password;

            TokenStatus[] tokenStatuses = null;

            using (var context = new TurnContext(adapter, new Microsoft.Bot.Schema.Activity {
            }))
            {
                var connectorClient = new ConnectorClient(new Uri(TokenServiceUrl), botAppId, botAppPassword);
                context.TurnState.Add <IConnectorClient>(connectorClient);

                // Retrieve the Token Status
                tokenStatuses = await adapter.GetTokenStatusAsync(context, userId);
            }

            return(tokenStatuses);
        }
示例#23
0
        public void Play(TurnContext context)
        {
            var    gainUtility = new GainUtility(context, context.ActivePlayer);
            Action gainSilver  = () => gainUtility.Gain <Silver>(context.ActivePlayer.Hand);
            Action gainGold    = () => gainUtility.Gain <Gold>(context.ActivePlayer.Hand);

            if (context.ActivePlayer.Hand.OfType <Province>().Any())
            {
                var activity = Activities.ChooseYesOrNo(
                    context.Game.Log,
                    context.ActivePlayer,
                    "Reveal a Province to gain a Gold?",
                    this,
                    gainGold,
                    gainSilver);
                context.AddSingleActivity(activity, this);
            }
            else
            {
                gainSilver();
            }
        }
示例#24
0
        public async Task TestCommandActivityType()
        {
            // Arrange
            var activity = new Activity
            {
                Type  = ActivityTypes.Command,
                Name  = "application/test",
                Value = new CommandValue <object> {
                    CommandId = "Test", Data = new { test = true }
                }
            };
            var turnContext = new TurnContext(new NotImplementedAdapter(), activity);

            // Act
            var bot = new TestActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.Single(bot.Record);
            Assert.Equal("OnCommandActivityAsync", bot.Record[0]);
        }
示例#25
0
        public async Task <GoogleResponseBody> 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
                {
                    GoogleResponseBody response = null;
                    var activities = Responses.ContainsKey(key) ? Responses[key] : new List <Activity>();
                    response = CreateResponseFromLastActivity(activities, context);
                    return(response);
                }
                finally
                {
                    if (Responses.ContainsKey(key))
                    {
                        Responses.Remove(key);
                    }
                }
            }
            catch (Exception ex)
            {
                await OnTurnError(context, ex);

                throw;
            }
        }
        public async Task TestInvokeAsync()
        {
            // Arrange
            var activity = new Activity
            {
                Type = ActivityTypes.Invoke,
                Name = "some.random.invoke",
            };

            var adapter     = new TestInvokeAdapter();
            var turnContext = new TurnContext(adapter, activity);

            // Act
            var bot = new TestActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.Single(bot.Record);
            Assert.Equal("OnInvokeActivityAsync", bot.Record[0]);
            Assert.Equal(200, ((InvokeResponse)((Activity)adapter.Activity).Value).Status);
        }
示例#27
0
        public void UserAgentContainsProductVersion()
        {
            var application = new LuisApplication
            {
                EndpointKey   = "this-is-not-a-key",
                ApplicationId = Guid.Empty.ToString(),
                Endpoint      = "https://westus.api.cognitive.microsoft.com",
            };

            var clientHandler = new EmptyLuisResponseClientHandler();

            var recognizer = new LuisRecognizer(application, new LuisRecognizerOptions {
                HttpClient = clientHandler
            });

            var adapter  = new NullAdapter();
            var activity = new Activity
            {
                Type         = ActivityTypes.Message,
                Text         = "please book from May 5 to June 6",
                Recipient    = new ChannelAccount(),        // to no where
                From         = new ChannelAccount(),        // from no one
                Conversation = new ConversationAccount(),   // on no conversation
            };

            var turnContext = new TurnContext(adapter, activity);

            var recognizerResult = recognizer.RecognizeAsync(turnContext, CancellationToken.None).Result;

            Assert.NotNull(recognizerResult);

            var userAgent = clientHandler.UserAgent;

            // And that we added the bot.builder package details.
            var majorVersion = typeof(ConnectorClient).GetTypeInfo().Assembly.GetName().Version.Major;

            Assert.Contains($"Microsoft.Bot.Builder.AI.Luis/{majorVersion}", userAgent);
        }
示例#28
0
        public async Task TestEntityRecognize()
        {
            var mockResult = new Result
            {
                Score = 0.9,
                Label = new Label
                {
                    Name = "mockLabel"
                }
            };

            var mockScore = new List <Result>()
            {
                mockResult
            };
            var mockResolver = new MockResolver(mockScore);
            var recognizer   = new OrchestratorAdaptiveRecognizer(string.Empty, string.Empty, mockResolver)
            {
                ModelPath    = new StringExpression("fakePath"),
                SnapshotPath = new StringExpression("fakePath")
            };

            recognizer.EntityRecognizers.Add(new NumberEntityRecognizer());

            TestAdapter adapter  = new TestAdapter(TestAdapter.CreateConversation("ds"));
            var         activity = MessageFactory.Text("12");
            var         context  = new TurnContext(adapter, activity);

            var dc     = new DialogContext(new DialogSet(), context, new DialogState());
            var result = await recognizer.RecognizeAsync(dc, activity, default);

            Assert.IsNotNull(result.Entities);
            Assert.AreEqual(result.Entities["number"][0], new JValue("12"));
            var resolution = result.Entities["$instance"]["number"][0]["resolution"];

            Assert.AreEqual(resolution["subtype"], new JValue("integer"));
            Assert.AreEqual(resolution["value"], new JValue("12"));
        }
        public async Task TestFileConsentDecline()
        {
            // Arrange
            var activity = new Activity
            {
                Type  = ActivityTypes.Invoke,
                Name  = "fileConsent/invoke",
                Value = JObject.FromObject(new FileConsentCardResponse
                {
                    Action     = "decline",
                    UploadInfo = new FileUploadInfo
                    {
                        UniqueId  = "uniqueId",
                        FileType  = "fileType",
                        UploadUrl = "uploadUrl",
                    },
                }),
            };

            Activity[] activitiesToSend = null;
            void CaptureSend(Activity[] arg)
            {
                activitiesToSend = arg;
            }

            var turnContext = new TurnContext(new SimpleAdapter(CaptureSend), activity);

            // Act
            var bot = new TestActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.IsNotNull(activitiesToSend);
            Assert.AreEqual(1, activitiesToSend.Length);
            Assert.IsInstanceOfType(activitiesToSend[0].Value, typeof(InvokeResponse));
            Assert.AreEqual(501, ((InvokeResponse)activitiesToSend[0].Value).Status);
        }
        public async Task Intents_DisableIntent()
        {
            string targetName = Guid.NewGuid().ToString();

            IntentRecognizerMiddleware m = new IntentRecognizerMiddleware();

            m.OnRecognize(async(context) =>
            {
                return(new List <Intent>
                {
                    new Intent()
                    {
                        Name = targetName
                    },
                });
            });
            bool enabled = false;

            m.OnEnabled(async(context) =>
            {
                return(enabled);
            });

            TurnContext bc = TestUtilities.CreateEmptyContext();

            // Test that the Intent comes back when the OnEnabled method returns true
            enabled = true;
            var resultingIntents = await m.Recognize(bc);

            Assert.IsTrue(resultingIntents.Count == 1, "Expected exactly 1 intent");
            Assert.IsTrue(resultingIntents.First().Name == targetName, $"Unexpected Intent Name. Expected {targetName}");

            // Test that NO Intent comes back when the OnEnabled method returns false
            enabled = false;
            var resultingIntents2 = await m.Recognize(bc);

            Assert.IsTrue(resultingIntents2.Count == 0, "Expected exactly 0 intent");
        }
        public async Task TestFileConsentBadAction()
        {
            // Arrange
            var activity = new Activity
            {
                Type  = ActivityTypes.Invoke,
                Name  = "fileConsent/invoke",
                Value = JObject.FromObject(new FileConsentCardResponse
                {
                    Action     = "this.is.a.bad.action",
                    UploadInfo = new FileUploadInfo
                    {
                        UniqueId  = "uniqueId",
                        FileType  = "fileType",
                        UploadUrl = "uploadUrl",
                    },
                }),
            };

            Activity[] activitiesToSend = null;
            void CaptureSend(Activity[] arg)
            {
                activitiesToSend = arg;
            }

            var turnContext = new TurnContext(new SimpleAdapter(CaptureSend), activity);

            // Act
            var bot = new TeamsActivityHandler();

            await((IBot)bot).OnTurnAsync(turnContext);

            // Assert
            Assert.NotNull(activitiesToSend);
            Assert.Single(activitiesToSend);
            Assert.IsType <InvokeResponse>(activitiesToSend[0].Value);
            Assert.Equal(400, ((InvokeResponse)activitiesToSend[0].Value).Status);
        }
示例#32
0
        public async Task TestConversationStateBlobStorage()
        {
            if (StorageEmulatorHelper.CheckEmulator())
            {
                // Arrange
                var storage           = GetStorage();
                var conversationState = new ConversationState(storage);
                var propAccessor      = conversationState.CreateProperty <Prop>("prop");

                var adapter  = new TestStorageAdapter();
                var activity = new Activity
                {
                    ChannelId    = "123",
                    Conversation = new ConversationAccount {
                        Id = "abc"
                    },
                };

                // Act
                var turnContext1 = new TurnContext(adapter, activity);
                var propValue1   = await propAccessor.GetAsync(turnContext1, () => new Prop());

                propValue1.X = "hello";
                propValue1.Y = "world";
                await conversationState.SaveChangesAsync(turnContext1, force : true);

                var turnContext2 = new TurnContext(adapter, activity);
                var propValue2   = await propAccessor.GetAsync(turnContext2);

                // Assert
                Assert.Equal("hello", propValue2.X);
                Assert.Equal("world", propValue2.Y);

                await propAccessor.DeleteAsync(turnContext1);

                await conversationState.SaveChangesAsync(turnContext1);
            }
        }
示例#33
0
        public async Task TestAdapter_GetUserTokenAsyncReturnsNullWithCode()
        {
            TestAdapter adapter  = new TestAdapter();
            Activity    activity = new Activity()
            {
                ChannelId = "directline",
                From      = new ChannelAccount()
                {
                    Id = "testUser",
                },
            };
            TurnContext turnContext = new TurnContext(adapter, activity);

            var token = await adapter.GetUserTokenAsync(turnContext, "myConnection", "abc123", CancellationToken.None);

            Assert.Null(token);

            var oAuthAppCredentials = MicrosoftAppCredentials.Empty;

            token = await adapter.GetUserTokenAsync(turnContext, oAuthAppCredentials, "myConnection", "abc123", CancellationToken.None);

            Assert.Null(token);
        }
示例#34
0
 public virtual void OnTurnStarting(TurnContext context)
 {
     IsFinished = true;
 }
示例#35
0
        public static ISelectCardsActivity SelectActionToPlayMultipleTimes(TurnContext context, Player player, IGameLog log, ICard source, int count)
        {
            var activity = new SelectCardsActivity(
                log, player,
                string.Format("Select an action to play {0} times", count),
                SelectionSpecifications.SelectExactlyXCards(1), source);

            activity.Hint = ActivityHint.PlayCards;
            activity.Specification.CardTypeRestriction = typeof(IActionCard);
            activity.AfterCardsSelected = cards =>
            {
                var actionCard = cards.OfType<IActionCard>().Single();
                log.LogMessage("{0} selected {1} to be played {2} times.", player.Name, actionCard.Name, count);

                actionCard.MoveTo(context.ActivePlayer.PlayArea);

                count.Times(() => context.AddEffect(source, new PlayCardEffect(actionCard)));
            };

            return activity;
        }
示例#36
0
        public static IActivity ChooseWhetherToMillTopCard(TurnContext context, Player choosingPlayer, Player targetPlayer, ICard source)
        {
            var revealZone = new RevealZone(targetPlayer);
            targetPlayer.Deck.TopCard.MoveTo(revealZone);
            revealZone.LogReveal(context.Game.Log);

            var otherPlayerMessage = string.Format("Put {0}'s card in the discard pile?", targetPlayer.Name);
            var selfMessage = "Put your own card in the discard pile?";

            var activity = new ChooseBasedOnRevealedCardsActivity(
                context.Game.Log,
                choosingPlayer,
                revealZone,
                choosingPlayer == targetPlayer ? selfMessage : otherPlayerMessage,
                source,
                Choice.Yes,
                Choice.No
                );

            activity.ActOnChoice = choice =>
            {
                var card = revealZone.Single();
                string actionDescription;
                if (choice == Choice.Yes)
                {
                    actionDescription = "into the discard pile";
                    card.MoveTo(targetPlayer.Discards);
                }
                else
                {
                    actionDescription = "back on top";
                    targetPlayer.Deck.MoveToTop(card);
                }

                var message = string.Format("{0} put {1}'s {2} {3}.", context.ActivePlayer, targetPlayer, card.Name, actionDescription);
                context.Game.Log.LogMessage(message);
            };

            return activity;
        }
示例#37
0
 public virtual void ExecuteTurn(TurnContext context)
 {
     CurrentUnitState.Handle(context).Execute();
 }
示例#38
0
        public static IActivity SelectACardToTrash(TurnContext context, Player player, ICard source, Action<ICard> afterTrash)
        {
            var activity = new SelectCardsActivity(context.Game.Log, player,
                "Select a card to trash.",
                 SelectionSpecifications.SelectExactlyXCards(1), source);

            activity.Hint = ActivityHint.TrashCards;
            activity.AfterCardsSelected = cards =>
            {
                foreach (var cardToTrash in cards)
                    context.Trash(activity.Player, cardToTrash);

                afterTrash(cards.Single());
            };

            return activity;
        }
示例#39
0
        public static IActivity SelectUpToXCardsToTrash(TurnContext context, Player player, int count, ICard source)
        {
            var activity = new SelectCardsActivity(context.Game.Log, player,    
                string.Format("Select up to {0} card(s) to trash", count),
                 SelectionSpecifications.SelectUpToXCards(count), source);

            activity.Hint = ActivityHint.TrashCards;
            activity.AfterCardsSelected = cards =>
            {
                foreach (var cardToTrash in cards)
                    context.Trash(activity.Player, cardToTrash);
            };

            return activity;
        }
示例#40
0
        public static IActivity DiscardCardsToDrawCards(TurnContext context, ICard source)
        {
            var activity = new SelectCardsActivity(
                   context,
                   "Select any number of cards to discard, you will draw 1 new card for each discard.",
                   SelectionSpecifications.SelectUpToXCards(context.ActivePlayer.Hand.CardCount), source);

            activity.AfterCardsSelected = cards =>
            {
                context.DiscardCards(activity.Player, cards);
                context.DrawCards(cards.Count());
            };

            return activity;
        }
示例#41
0
 public override void Resolve(TurnContext context, ICard source)
 {
     _card.Play(context);
 }
示例#42
0
 public ChoiceActivity(TurnContext context, Player player, string message, ICard source, params Choice[] options)
     : this(context.Game.Log, player, message, source, options)
 {
 }
示例#43
0
 public SelectCardsActivity(TurnContext context, string message, ISelectionSpecification specification)
     : this(context.Game.Log, context.ActivePlayer, message, specification)
 {
     
 }
示例#44
0
 public static ISelectCardsActivity PutCardFromHandOnTopOfDeck(TurnContext context, ICard source)
 {
     return PutCardFromHandOnTopOfDeck(context.Game.Log, context.ActivePlayer,
                                         "Select a card to put on top of the deck.", source);
 }
示例#45
0
 public static ISelectPileActivity SelectACardForOpponentToGain(TurnContext context, Player player, Player victim, CardCost cost, ICard source)
 {
     return new SelectPileActivity(context.Game.Log, player, string.Format("Select a card for {0} to gain of cost {1}.", victim.Name, cost),
                                   SelectionSpecifications.SelectPileCostingExactlyX(cost), source)
     {
         AfterPileSelected = pile =>
         {                    
             var card = pile.TopCard;
             card.MoveTo(victim.Discards);
             context.Game.Log.LogGain(victim, card);
         },
         Hint = ActivityHint.OpponentGainCards
     };
 }
 public ChooseBasedOnRevealedCardsActivity(TurnContext context, Player player, RevealZone revealZone, string message, ICard source, params Choice[] options) 
     : base(context, player, message, source, options)
 {
     RevealedCards = revealZone;                        
 }
示例#47
0
        public static IActivity SelectXCardsToTrash(TurnContext context, Player player, int count, ICard source, Action afterTrash)
        {
            var activity = new SelectCardsActivity(context.Game.Log, player,
                string.Format("Select {0} card(s) to trash.", count),
                SelectionSpecifications.SelectExactlyXCards(count), source);

            activity.Hint = ActivityHint.TrashCards;
            activity.AfterCardsSelected = cards =>
            {
                context.TrashAll(player, cards);
                afterTrash();
            };
            
            return activity;
        }