public void Init()
        {
            _fixture = new Fixture().Customize(new AutoRhinoMockCustomization());
            _storage = _fixture.Create<IStateStorage>();
            _target = _fixture.Create<object>();
            var targetIdentity = RuntimeHelpers.GetHashCode(_target);
            _storage.Stub(x => x.GetStorage(targetIdentity)).Return(new Dictionary<string, object>());

            _sut = new StateAccessor(_target, _storage);
        }
Esempio n. 2
0
        protected async Task <DialogTurnResult> ShowTicket(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

            bool firstDisplay = false;

            if (state.PageIndex == -1)
            {
                firstDisplay    = true;
                state.PageIndex = 0;
            }

            var management = ServiceManager.CreateManagement(Settings, state.Token);
            var urgencies  = new List <UrgencyLevel>();

            if (state.UrgencyLevel != UrgencyLevel.None)
            {
                urgencies.Add(state.UrgencyLevel);
            }

            var states = new List <TicketState>();

            if (state.TicketState != TicketState.None)
            {
                states.Add(state.TicketState);
            }

            var result = await management.SearchTicket(state.PageIndex, description : state.TicketDescription, urgencies : urgencies, number : state.TicketNumber, states : states);

            if (!result.Success)
            {
                return(await SendServiceErrorAndCancel(sc, result));
            }

            if (result.Tickets == null || result.Tickets.Length == 0)
            {
                if (firstDisplay)
                {
                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(TicketResponses.TicketShowNone)
                    };

                    return(await sc.PromptAsync(Actions.NavigateYesNoPrompt, options));
                }
                else
                {
                    var token = new StringDictionary()
                    {
                        { "Page", (state.PageIndex + 1).ToString() }
                    };

                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(TicketResponses.TicketEnd, token)
                    };

                    return(await sc.PromptAsync(Actions.NavigateYesNoPrompt, options));
                }
            }
            else
            {
                var cards = new List <Card>();
                foreach (var ticket in result.Tickets)
                {
                    cards.Add(new Card()
                    {
                        Name = GetDivergedCardName(sc.Context, "Ticket"),
                        Data = ConvertTicket(ticket)
                    });
                }

                var token = new StringDictionary()
                {
                    { "Page", (state.PageIndex + 1).ToString() }
                };

                var options = new PromptOptions()
                {
                    Prompt = ResponseManager.GetCardResponse(TicketResponses.TicketShow, cards, token)
                };

                // Workaround. In teams, HeroCard will be used for prompt and adaptive card could not be shown. So send them separatly
                if (Channel.GetChannelId(sc.Context) == Channels.Msteams)
                {
                    await sc.Context.SendActivityAsync(options.Prompt);

                    options.Prompt = null;
                }

                return(await sc.PromptAsync(Actions.NavigateYesNoPrompt, options));
            }
        }
Esempio n. 3
0
 private void populateRTypeExecutors()
 {
     RTypeExecutors = new Dictionary <RTypeFunction, Action <RTypeInstruction, IStateAccessor> >
     {
         { RTypeFunction.Add, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, (uint)(((int)StateAccessor.ReadRegister(r.Rs)) + (int)(StateAccessor.ReadRegister(r.Rt))));
           } },
         { RTypeFunction.UnsignedAdd, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, StateAccessor.ReadRegister(r.Rs) + StateAccessor.ReadRegister(r.Rt));
           } },
         { RTypeFunction.BitwiseAnd, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, StateAccessor.ReadRegister(r.Rs) & StateAccessor.ReadRegister(r.Rt));
           } },
         { RTypeFunction.Break, (r, StateAccessor) => {
               StateAccessor.SetEpc(StateAccessor.GetPc());
               StateAccessor.SetPc(0x3c);
               StateAccessor.Skip();
           } },
         { RTypeFunction.Divide, (r, StateAccessor) => {
               var dividend = (int)StateAccessor.ReadRegister(r.Rs);
               var divisor  = (int)StateAccessor.ReadRegister(r.Rt);
               StateAccessor.SetHi((uint)(dividend % divisor));
               StateAccessor.SetLo((uint)(dividend / divisor));
           } },
         { RTypeFunction.UnsignedDivide, (r, StateAccessor) => {
               var dividend = StateAccessor.ReadRegister(r.Rs);
               var divisor  = StateAccessor.ReadRegister(r.Rt);
               StateAccessor.SetHi(dividend % divisor);
               StateAccessor.SetLo(dividend / divisor);
           } },
         { RTypeFunction.JumpAndLinkRegister, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, StateAccessor.GetPc() + 4);
               StateAccessor.SetPc(StateAccessor.ReadRegister(r.Rs));
           } },
         { RTypeFunction.JumpRegister, (r, StateAccessor) => {
               StateAccessor.SetPc(StateAccessor.ReadRegister(r.Rs));
           } },
         { RTypeFunction.MoveFromHi, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, StateAccessor.GetHi());
           } },
         { RTypeFunction.MoveFromLo, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, StateAccessor.GetLo());
           } },
         { RTypeFunction.MoveToHi, (r, StateAccessor) => {
               StateAccessor.SetHi(StateAccessor.ReadRegister(r.Rs));
           } },
         { RTypeFunction.MoveToLo, (r, StateAccessor) => {
               StateAccessor.SetLo(StateAccessor.ReadRegister(r.Rs));
           } },
         { RTypeFunction.Multiply, (r, StateAccessor) => {
               var  a      = (long)(int)StateAccessor.ReadRegister(r.Rs);
               var  b      = (long)(int)StateAccessor.ReadRegister(r.Rt);
               long result = a * b;
               StateAccessor.SetLo((uint)((int)result));
               StateAccessor.SetHi((uint)(result >> 32));
           } },
         { RTypeFunction.UnsignedMultiply, (r, StateAccessor) => {
               var a      = (ulong)StateAccessor.ReadRegister(r.Rs);
               var b      = (ulong)StateAccessor.ReadRegister(r.Rt);
               var result = a * b;
               StateAccessor.SetLo((uint)result);
               StateAccessor.SetHi((uint)(result >> 32));
           } },
         { RTypeFunction.BitwiseNor, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, ~(StateAccessor.ReadRegister(r.Rs) | StateAccessor.ReadRegister(r.Rt)));
           } },
         { RTypeFunction.BitwiseOr, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, (StateAccessor.ReadRegister(r.Rs) | StateAccessor.ReadRegister(r.Rt)));
           } },
         { RTypeFunction.ShiftLeftLogical, (r, StateAccessor) => {
               var a = StateAccessor.ReadRegister(r.Rt);
               var b = (int)r.Sa;
               StateAccessor.WriteRegister(r.Rd, a << b);
           } },
         { RTypeFunction.ShiftLeftLogicalVariable, (r, StateAccessor) => {
               var a = StateAccessor.ReadRegister(r.Rt);
               var b = (int)StateAccessor.ReadRegister(r.Rs);
               StateAccessor.WriteRegister(r.Rd, a << b);
           } },
         { RTypeFunction.SetOnLessThan, (r, StateAccessor) => {
               var a = (int)StateAccessor.ReadRegister(r.Rs);
               var b = (int)StateAccessor.ReadRegister(r.Rt);
               StateAccessor.WriteRegister(r.Rd, a < b ? 1u : 0u);
           } },
         { RTypeFunction.UnsignedSetOnLessThan, (r, StateAccessor) => {
               var a = StateAccessor.ReadRegister(r.Rs);
               var b = StateAccessor.ReadRegister(r.Rt);
               StateAccessor.WriteRegister(r.Rd, a < b ? 1u : 0u);
           } },
         { RTypeFunction.ShiftRightArithmetic, (r, StateAccessor) => {
               var a = (int)StateAccessor.ReadRegister(r.Rt);
               var b = (int)r.Sa;
               StateAccessor.WriteRegister(r.Rd, (uint)(a >> b));
           } },
         { RTypeFunction.ShiftRightArithmeticVariable, (r, StateAccessor) => {
               var a = (int)StateAccessor.ReadRegister(r.Rt);
               var b = (int)StateAccessor.ReadRegister(r.Rs);
               StateAccessor.WriteRegister(r.Rd, (uint)(a >> b));
           } },
         { RTypeFunction.ShiftRightLogical, (r, StateAccessor) => {
               var a = StateAccessor.ReadRegister(r.Rt);
               var b = (int)r.Sa;
               StateAccessor.WriteRegister(r.Rd, a >> b);
           } },
         { RTypeFunction.ShiftRightLogicalVariable, (r, StateAccessor) => {
               var a = StateAccessor.ReadRegister(r.Rt);
               var b = (int)StateAccessor.ReadRegister(r.Rs);
               StateAccessor.WriteRegister(r.Rd, a >> b);
           } },
         { RTypeFunction.Subtract, (r, StateAccessor) => {
               var a = (int)StateAccessor.ReadRegister(r.Rs);
               var b = (int)StateAccessor.ReadRegister(r.Rt);
               StateAccessor.WriteRegister(r.Rd, (uint)(a - b));
           } },
         { RTypeFunction.UnsignedSubtract, (r, StateAccessor) => {
               var a = (int)StateAccessor.ReadRegister(r.Rs);
               var b = (int)StateAccessor.ReadRegister(r.Rt);
               StateAccessor.WriteRegister(r.Rd, (uint)(a - b));
           } },
         { RTypeFunction.Syscall, (r, StateAccessor) => {
               StateAccessor.SetEpc(StateAccessor.GetPc());
               StateAccessor.SetPc(0x3c);
               StateAccessor.Skip();
           } },
         { RTypeFunction.BitwiseExclusiveOr, (r, StateAccessor) => {
               StateAccessor.WriteRegister(r.Rd, (StateAccessor.ReadRegister(r.Rs) ^ StateAccessor.ReadRegister(r.Rt)));
           } },
     };
 }
Esempio n. 4
0
        private void populateITypeExecutors()
        {
            ITypeExecutors = new Dictionary <Opcode, Action <ITypeInstruction, IStateAccessor> >
            {
                { Opcode.AddImmediate, (r, StateAccessor) => {
                      var a = (int)StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, (uint)(a + ((short)r.Immediate)));
                  } },
                { Opcode.UnsignedAddImmediate, (r, StateAccessor) => {
                      var a = StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, (uint)(a + (short)r.Immediate));
                  } },
                { Opcode.BitwiseAndImmediate, (r, StateAccessor) => {
                      var a = StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, a & r.Immediate);
                  } },
                { Opcode.BranchOnEqual, (r, StateAccessor) => {
                      var rs = StateAccessor.ReadRegister(r.Rs);
                      var rt = StateAccessor.ReadRegister(r.Rt);
                      if (rs == rt)
                      {
                          StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                      }
                  } },
                { Opcode.Branch, (r, StateAccessor) => {
                      var rs = (int)StateAccessor.ReadRegister(r.Rs);
                      var rt = r.Rt;
                      switch (rt)
                      {
                      case 0:
                          if (rs < 0)
                          {
                              StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                          }
                          break;

                      case 1:
                          if (rs >= 0)
                          {
                              StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                          }
                          break;

                      case 16:
                          StateAccessor.WriteRegister(31, StateAccessor.GetPc() + 4);
                          if (rs < 0)
                          {
                              StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                          }
                          break;

                      case 17:
                          StateAccessor.WriteRegister(31, StateAccessor.GetPc() + 4);
                          if (rs >= 0)
                          {
                              StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                          }
                          break;

                      default:
                          throw new InvalidOperationException(String.Format("Invalid Branch {0}", rt));
                      }
                  } },
                { Opcode.BranchOnGreaterThanZero, (r, StateAccessor) => {
                      var rs = (int)StateAccessor.ReadRegister(r.Rs);
                      var rt = StateAccessor.ReadRegister(r.Rt);
                      if (rs > 0)
                      {
                          StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                      }
                  } },
                { Opcode.BranchOnLessThanOrEqualToZero, (r, StateAccessor) => {
                      var rs = (int)StateAccessor.ReadRegister(r.Rs);
                      var rt = StateAccessor.ReadRegister(r.Rt);
                      if (rs <= 0)
                      {
                          StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                      }
                  } },
                { Opcode.BranchOnNotEqual, (r, StateAccessor) => {
                      var rs = StateAccessor.ReadRegister(r.Rs);
                      var rt = StateAccessor.ReadRegister(r.Rt);
                      if (rs != rt)
                      {
                          StateAccessor.SetPc((uint)(StateAccessor.GetPc() + (short)(r.Immediate << 2)));
                      }
                  } },
                { Opcode.LoadByte, (r, StateAccessor) => {
                      var  ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      byte dt;
                      StateAccessor.GetMemoryData(ptr, out dt);
                      var data = (uint)((int)((sbyte)(dt)));
                      StateAccessor.WriteRegister(r.Rt, data);
                  } },
                { Opcode.UnsignedLoadByte, (r, StateAccessor) => {
                      var  ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      byte dt;
                      StateAccessor.GetMemoryData(ptr, out dt);
                      var data = (uint)dt;
                      StateAccessor.WriteRegister(r.Rt, data);
                  } },
                { Opcode.LoadHalfword, (r, StateAccessor) => {
                      var    ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      UInt16 dt;
                      StateAccessor.GetMemoryData(ptr, out dt);
                      var data = (uint)((int)((short)DataConverterUInt16(dt)));
                      StateAccessor.WriteRegister(r.Rt, data);
                  } },
                { Opcode.UnsignedLoadHalfword, (r, StateAccessor) => {
                      var    ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      UInt16 dt;
                      StateAccessor.GetMemoryData(ptr, out dt);
                      var data = DataConverterUInt16(dt);
                      StateAccessor.WriteRegister(r.Rt, data);
                  } },
                { Opcode.LoadUpperImmediate, (r, StateAccessor) => {
                      StateAccessor.WriteRegister(r.Rt, r.Immediate << 16);
                  } },
                { Opcode.LoadWord, (r, StateAccessor) => {
                      var    ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      UInt32 data;
                      StateAccessor.GetMemoryData(ptr, out data);
                      data = DataConverterUInt32(data);
                      StateAccessor.WriteRegister(r.Rt, data);
                  } },
                { Opcode.BitwiseOrImmediate, (r, StateAccessor) => {
                      var a = StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, a | r.Immediate);
                  } },
                { Opcode.StoreByte, (r, StateAccessor) => {
                      var ptr  = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      var data = (byte)(StateAccessor.ReadRegister(r.Rt));
                      StateAccessor.SetMemoryData(ptr, data);
                  } },
                { Opcode.SetOnLessThanImmediate, (r, StateAccessor) => {
                      var a = (int)StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, a < (short)r.Immediate ? 1u : 0u);
                  } },
                { Opcode.UnsignedSetOnLessThanImmediate, (r, StateAccessor) => {
                      var a = StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, a < r.Immediate ? 1u : 0u);
                  } },
                { Opcode.StoreHalfword, (r, StateAccessor) => {
                      var ptr = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      var dt  = (ushort)StateAccessor.ReadRegister(r.Rt);
                      dt = DataConverterUInt16(dt);
                      StateAccessor.SetMemoryData(ptr, (ushort)dt);
                  } },
                { Opcode.StoreWord, (r, StateAccessor) => {
                      var ptr  = (uint)(((short)r.Immediate) + (int)StateAccessor.ReadRegister(r.Rs));
                      var data = DataConverterUInt32(StateAccessor.ReadRegister(r.Rt));
                      StateAccessor.SetMemoryData(ptr, data);
                  } },
                { Opcode.BitwiseExclusiveOrImmediate, (r, StateAccessor) => {
                      var a = StateAccessor.ReadRegister(r.Rs);
                      StateAccessor.WriteRegister(r.Rt, a ^ r.Immediate);
                  } },
            };
        }
        private async Task <DialogTurnResult> ShowResultAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await StateAccessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken);

            GetEntityFromLuis(stepContext);
            var userInput = string.Empty;

            if (string.IsNullOrWhiteSpace(state.SearchEntityName))
            {
                userInput = stepContext.Context.Activity.Text ?? string.Empty;

                state.SearchEntityName = userInput;
                state.SearchEntityType = SearchResultModel.EntityType.Unknown;
            }

            var bingSearchKey       = Settings.BingSearchKey ?? throw new Exception("The BingSearchKey must be provided to use this dialog. Please provide this key in your Skill Configuration.");
            var bingAnswerSearchKey = Settings.BingAnswerSearchKey ?? throw new Exception("The BingSearchKey must be provided to use this dialog. Please provide this key in your Skill Configuration.");
            var client = new BingSearchClient(bingSearchKey, bingAnswerSearchKey);

            // https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cognitive-services/Labs/Answer-Search/overview.md
            var entitiesResult = await client.GetSearchResult(state.SearchEntityName, "en-us", state.SearchEntityType);

            var actionResult = new ActionResult(false);

            if (entitiesResult != null && entitiesResult.Count > 0)
            {
                actionResult.Url           = entitiesResult[0].Url;
                actionResult.Description   = entitiesResult[0].Description;
                actionResult.ActionSuccess = true;
            }

            Activity prompt = null;

            if (entitiesResult != null && entitiesResult.Count > 0)
            {
                var tokens = new Dictionary <string, object>()
                {
                    { "Name", entitiesResult[0].Name },
                };

                if (entitiesResult[0].Type == SearchResultModel.EntityType.Movie)
                {
                    var movieInfo = MovieHelper.GetMovieInfoFromUrl(entitiesResult[0].Url);
                    if (movieInfo != null)
                    {
                        actionResult.Description = movieInfo.Description;
                        tokens["Name"]           = movieInfo.Name;
                        var movieData = new MovieCardData()
                        {
                            Name          = movieInfo.Name,
                            Description   = StringHelper.EscapeCardString(movieInfo.Description),
                            Image         = movieInfo.Image,
                            Rating        = $"{movieInfo.Rating}",
                            GenreArray    = string.Join(" ▪ ", movieInfo.Genre),
                            ContentRating = movieInfo.ContentRating,
                            Duration      = movieInfo.Duration,
                            Year          = movieInfo.Year,
                        };

                        if (Channel.GetChannelId(stepContext.Context) == Channels.DirectlineSpeech || Channel.GetChannelId(stepContext.Context) == Channels.Msteams)
                        {
                            movieData.Image = ImageToDataUri(movieInfo.Image);
                        }

                        tokens.Add("Speak", StringHelper.EscapeCardString(movieInfo.Description));

                        prompt = TemplateManager.GenerateActivity(
                            SearchResponses.EntityKnowledge,
                            new Card(GetDivergedCardName(stepContext.Context, "MovieCard"), movieData),
                            tokens);
                    }
                    else
                    {
                        prompt = TemplateManager.GenerateActivity(SearchResponses.AnswerSearchResultPrompt, new Dictionary <string, object>()
                        {
                            { "Answer", StringHelper.EscapeCardString(entitiesResult[0].Description) },
                            { "Url", entitiesResult[0].Url }
                        });
                    }
                }
                else if (entitiesResult[0].Type == SearchResultModel.EntityType.Person)
                {
                    var celebrityData = new PersonCardData()
                    {
                        Name                  = entitiesResult[0].Name,
                        Description           = StringHelper.EscapeCardString(entitiesResult[0].Description),
                        IconPath              = entitiesResult[0].ImageUrl,
                        Title_View            = TemplateManager.GetString(CommonStrings.View),
                        Link_View             = entitiesResult[0].Url,
                        EntityTypeDisplayHint = entitiesResult[0].EntityTypeDisplayHint
                    };

                    if (Channel.GetChannelId(stepContext.Context) == Channels.DirectlineSpeech || Channel.GetChannelId(stepContext.Context) == Channels.Msteams)
                    {
                        celebrityData.IconPath = ImageToDataUri(entitiesResult[0].ImageUrl);
                    }

                    tokens.Add("Speak", StringHelper.EscapeCardString(entitiesResult[0].Description));

                    prompt = TemplateManager.GenerateActivity(
                        SearchResponses.EntityKnowledge,
                        new Card(GetDivergedCardName(stepContext.Context, "PersonCard"), celebrityData),
                        tokens);
                }
                else
                {
                    if (userInput.Contains("president"))
                    {
                        prompt = TemplateManager.GenerateActivity(SearchResponses.AnswerSearchResultPrompt, new Dictionary <string, object>()
                        {
                            { "Answer", TemplateManager.GetString(CommonStrings.DontKnowAnswer) },
                            { "Url", BingSiteUrl }
                        });

                        actionResult.Description   = TemplateManager.GetString(CommonStrings.DontKnowAnswer);
                        actionResult.Url           = BingSiteUrl;
                        actionResult.ActionSuccess = false;
                    }
                    else
                    {
                        prompt = TemplateManager.GenerateActivity(SearchResponses.AnswerSearchResultPrompt, new Dictionary <string, object>()
                        {
                            { "Answer", entitiesResult[0].Description },
                            { "Url", entitiesResult[0].Url }
                        });
                    }
                }
            }
            else
            {
                prompt = TemplateManager.GenerateActivity(SearchResponses.NoResultPrompt);
            }

            await stepContext.Context.SendActivityAsync(prompt, cancellationToken);

            if (state.IsAction == true)
            {
                return(await stepContext.NextAsync(actionResult, cancellationToken));
            }

            return(await stepContext.NextAsync(cancellationToken : cancellationToken));
        }
Esempio n. 6
0
        protected async Task <DialogTurnResult> ShowKnowledge(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

            bool firstDisplay = false;

            if (state.PageIndex == -1)
            {
                firstDisplay    = true;
                state.PageIndex = 0;
            }

            var management = ServiceManager.CreateManagement(Settings, sc.Result as TokenResponse, state.ServiceCache);

            var countResult = await management.CountKnowledge(state.TicketTitle);

            if (!countResult.Success)
            {
                return(await SendServiceErrorAndCancel(sc, countResult));
            }

            // adjust PageIndex
            int maxPage = Math.Max(0, (countResult.Knowledges.Length - 1) / Settings.LimitSize);

            state.PageIndex = Math.Max(0, Math.Min(state.PageIndex, maxPage));

            // TODO handle consistency with count
            var result = await management.SearchKnowledge(state.TicketTitle, state.PageIndex);

            if (!result.Success)
            {
                return(await SendServiceErrorAndCancel(sc, result));
            }

            if (result.Knowledges == null || result.Knowledges.Length == 0)
            {
                if (firstDisplay)
                {
                    if (!string.IsNullOrEmpty(ShowKnowledgeNoResponse))
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ShowKnowledgeNoResponse));
                    }

                    return(await sc.EndDialogAsync());
                }
                else
                {
                    // it is unlikely to happen now
                    var token = new StringDictionary()
                    {
                        { "Page", (state.PageIndex + 1).ToString() }
                    };

                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(ShowKnowledgeEndResponse, token)
                    };

                    return(await sc.PromptAsync(ShowKnowledgePrompt, options));
                }
            }
            else
            {
                if (firstDisplay)
                {
                    if (!string.IsNullOrEmpty(ShowKnowledgeHasResponse))
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ShowKnowledgeHasResponse));
                    }
                }

                var cards = new List <Card>();
                foreach (var knowledge in result.Knowledges)
                {
                    cards.Add(new Card()
                    {
                        Name = GetDivergedCardName(sc.Context, "Knowledge"),
                        Data = ConvertKnowledge(knowledge)
                    });
                }

                await sc.Context.SendActivityAsync(GetCardsWithIndicator(state.PageIndex, maxPage, cards));

                var options = new PromptOptions()
                {
                    Prompt = GetNavigatePrompt(sc.Context, ShowKnowledgeResponse, state.PageIndex, maxPage),
                };

                return(await sc.PromptAsync(ShowKnowledgePrompt, options));
            }
        }
Esempio n. 7
0
        protected async Task <DialogTurnResult> ShowKnowledge(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

            bool firstDisplay = false;

            if (state.PageIndex == -1)
            {
                firstDisplay    = true;
                state.PageIndex = 0;
            }

            var management = ServiceManager.CreateManagement(Settings, state.Token);
            var result     = await management.SearchKnowledge(state.TicketDescription, state.PageIndex);

            if (!result.Success)
            {
                return(await SendServiceErrorAndCancel(sc, result));
            }

            if (result.Knowledges == null || result.Knowledges.Length == 0)
            {
                if (firstDisplay)
                {
                    if (!string.IsNullOrEmpty(ShowKnowledgeNoResponse))
                    {
                        await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ShowKnowledgeNoResponse));
                    }

                    return(await sc.EndDialogAsync());
                }
                else
                {
                    var token = new StringDictionary()
                    {
                        { "Page", (state.PageIndex + 1).ToString() }
                    };

                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(ShowKnowledgeEndResponse, token)
                    };

                    return(await sc.PromptAsync(ShowKnowledgePrompt, options));
                }
            }
            else
            {
                var cards = new List <Card>();
                foreach (var knowledge in result.Knowledges)
                {
                    cards.Add(new Card()
                    {
                        Name = GetDivergedCardName(sc.Context, "Knowledge"),
                        Data = ConvertKnowledge(knowledge)
                    });
                }

                var token = new StringDictionary()
                {
                    { "Page", (state.PageIndex + 1).ToString() }
                };

                var options = new PromptOptions()
                {
                    Prompt = ResponseManager.GetCardResponse(ShowKnowledgeResponse, cards, token)
                };

                // Workaround. In teams, HeroCard will be used for prompt and adaptive card could not be shown. So send them separatly
                if (Channel.GetChannelId(sc.Context) == Channels.Msteams)
                {
                    await sc.Context.SendActivityAsync(options.Prompt);

                    options.Prompt = null;
                }

                return(await sc.PromptAsync(ShowKnowledgePrompt, options));
            }
        }
 /// <summary>
 /// Declares what property holds the TInstance's state on the current instance of the state machine
 /// </summary>
 /// <param name="instanceStateProperty"></param>
 /// <remarks>Setting the state accessor more than once will cause the property managed by the state machine to change each time.
 /// Please note, the state machine can only manage one property at a given time per instance,
 /// and the best practice is to manage one property per machine.
 /// </remarks>
 protected void InstanceState(Expression <Func <TInstance, State> > instanceStateProperty)
 {
     _instanceStateAccessor = new InitialIfNullStateAccessor <TInstance>(instanceStateProperty,
                                                                         _stateCache[Initial.Name], _stateChangedObservable);
 }
Esempio n. 9
0
        private async Task <DialogTurnResult> ShowMenuCardAsync(WaterfallStepContext sc, CancellationToken cancellationToken)
        {
            var convState = await StateAccessor.GetAsync(sc.Context, () => new HospitalitySkillState(), cancellationToken);

            if (convState.FoodList.Count == 0)
            {
                Menu menu = HotelService.GetMenu(convState.LuisResult?.Entities?.Menu[0][0]);

                // get available items for requested menu
                List <Card> menuItems = new List <Card>();
                foreach (var item in menu.Items)
                {
                    var cardName = GetCardName(sc.Context, "MenuItemCard");

                    // workaround for webchat not supporting hidden items on cards
                    if (Channel.GetChannelId(sc.Context) == Channels.Webchat)
                    {
                        cardName += ".1.0";
                    }

                    menuItems.Add(new Card(cardName, item));
                }

                var prompt = TemplateManager.GenerateActivity(RoomServiceResponses.FoodOrder);
                if (sc.Context.Activity.ChannelId == "google")
                {
                    List <OptionItem> menuOptions = new List <OptionItem>();
                    foreach (MenuItem item in menu.Items)
                    {
                        var option = new OptionItem()
                        {
                            Title       = item.Name,
                            Description = item.Description + " " + item.Price,
                            OptionInfo  = new OptionItemInfo()
                            {
                                Key = item.Name, Synonyms = new List <string>()
                                {
                                }
                            }
                        };
                        menuOptions.Add(option);
                    }

                    var listAttachment = new ListAttachment(
                        menu.Type + ": " + menu.TimeAvailable,
                        menuOptions,
                        ListAttachmentStyle.List);
                    prompt.Attachments.Add(listAttachment);
                }
                else
                {
                    // show menu card
                    await sc.Context.SendActivityAsync(TemplateManager.GenerateActivity(null, new Card(GetCardName(sc.Context, "MenuCard"), menu), null, "items", menuItems), cancellationToken);
                }

                // prompt for order
                return(await sc.PromptAsync(DialogIds.FoodOrderPrompt, new PromptOptions()
                {
                    Prompt = prompt,
                    RetryPrompt = TemplateManager.GenerateActivity(RoomServiceResponses.RetryFoodOrder)
                }, cancellationToken));
            }

            return(await sc.NextAsync(cancellationToken: cancellationToken));
        }
Esempio n. 10
0
 public TransitionActivity(State <TInstance> toState, StateAccessor <TInstance> currentStateAccessor)
 {
     _toState = toState;
     _currentStateAccessor = currentStateAccessor;
 }
        /// <summary>
        ///     Transition a state machine instance to a specific state, producing any events related
        ///     to the transaction such as leaving the previous state and entering the target state
        /// </summary>
        /// <typeparam name="TInstance">The state instance type</typeparam>
        /// <param name="composer"></param>
        /// <param name="instance">The state instance</param>
        /// <param name="accessor"></param>
        /// <param name="state">The target state</param>
        public static void TransitionToState <TInstance>(Composer composer, TInstance instance, StateAccessor <TInstance> accessor,
                                                         State <TInstance> state)
            where TInstance : class
        {
            Activity <TInstance> activity = new TransitionActivity <TInstance>(state, accessor);

            activity.Execute(composer, instance);
        }
 public void Ctor_NullStorage_ShouldThrowException()
 {
     var sut = new StateAccessor(_target, null);
 }
 public void Ctor_NullTarget_ShouldThrowException()
 {
     var sut = new StateAccessor(null, _storage);
 }
Esempio n. 14
0
 override public void Start()
 {
     stateAccessor = StateAccessor.Instance;
     brain         = GameObject.Find(BRAIN_PARTS_NAME);
     base.Start();
 }
Esempio n. 15
0
        /// <summary>
        /// Declares the property to hold the instance's state as a string (the state name is stored in the property)
        /// </summary>
        /// <param name="instanceStateProperty"></param>
        protected void InstanceState(Expression <Func <TInstance, string> > instanceStateProperty)
        {
            var stateAccessor = new StringStateAccessor <TInstance>(this, instanceStateProperty, _stateObservers);

            _accessor = new InitialIfNullStateAccessor <TInstance>(_stateCache[Initial.Name], stateAccessor);
        }
Esempio n. 16
0
        private async Task <DialogTurnResult> MenuPromptAsync(WaterfallStepContext sc, CancellationToken cancellationToken)
        {
            var convState = await StateAccessor.GetAsync(sc.Context, () => new HospitalitySkillState(), cancellationToken);

            convState.FoodList = new List <FoodRequestClass>();
            await GetFoodEntitiesAsync(sc.Context, cancellationToken);

            var menu = convState.LuisResult?.Entities?.Menu;

            // didn't order, prompt if 1 menu type not identified
            if (convState.FoodList.Count == 0 && string.IsNullOrWhiteSpace(menu?[0][0]) && menu?.Length != 1)
            {
                var prompt = TemplateManager.GenerateActivity(RoomServiceResponses.MenuPrompt);

                // TODO what does this for ?
                if (sc.Context.Activity.ChannelId == "google")
                {
                    prompt.Text  = prompt.Text.Replace("*", string.Empty);
                    prompt.Speak = prompt.Speak.Replace("*", string.Empty);
                    var listAttachment = new ListAttachment(
                        "Select an option below",
                        new List <OptionItem>()
                    {
                        new OptionItem()
                        {
                            Title = "Breakfast",
                            Image = new OptionItemImage()
                            {
                                AccessibilityText = "Item 1 image", Url = "http://cdn.cnn.com/cnnnext/dam/assets/190515173104-03-breakfast-around-the-world-avacado-toast.jpg"
                            },
                            OptionInfo = new OptionItemInfo()
                            {
                                Key = "Breakfast", Synonyms = new List <string>()
                                {
                                    "first"
                                }
                            }
                        },
                        new OptionItem()
                        {
                            Title = "Lunch",
                            Image = new OptionItemImage()
                            {
                                AccessibilityText = "Item 2 image", Url = "https://simply-delicious-food.com/wp-content/uploads/2018/07/mexican-lunch-bowls-3.jpg"
                            },
                            OptionInfo = new OptionItemInfo()
                            {
                                Key = "Lunch", Synonyms = new List <string>()
                                {
                                    "second"
                                }
                            }
                        },
                        new OptionItem()
                        {
                            Title = "Dinner",
                            Image = new OptionItemImage()
                            {
                                AccessibilityText = "Item 3 image", Url = "https://cafedelites.com/wp-content/uploads/2018/06/Garlic-Butter-Steak-Shrimp-Recipe-IMAGE-1.jpg"
                            },
                            OptionInfo = new OptionItemInfo()
                            {
                                Key = "Dinner", Synonyms = new List <string>()
                                {
                                    "third"
                                }
                            }
                        },
                        new OptionItem()
                        {
                            Title = "24 Hour Options",
                            Image = new OptionItemImage()
                            {
                                AccessibilityText = "Item 4 image", Url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQvAkc_j44yfAhswKl9s5LKnwFL4MGAg4IwFM6lBVTs0W4o9fLB&s"
                            },
                            OptionInfo = new OptionItemInfo()
                            {
                                Key = "24 hour options", Synonyms = new List <string>()
                                {
                                    "fourth"
                                }
                            }
                        }
                    },
                        ListAttachmentStyle.Carousel);
                    prompt.Attachments.Add(listAttachment);
                }
                else
                {
                    var actions = new List <CardAction>()
                    {
                        new CardAction(type: ActionTypes.ImBack, title: "Breakfast", value: "Breakfast menu"),
                        new CardAction(type: ActionTypes.ImBack, title: "Lunch", value: "Lunch menu"),
                        new CardAction(type: ActionTypes.ImBack, title: "Dinner", value: "Dinner menu"),
                        new CardAction(type: ActionTypes.ImBack, title: "24 Hour", value: "24 hour menu")
                    };

                    // create hero card instead when channel does not support suggested actions
                    if (!Channel.SupportsSuggestedActions(sc.Context.Activity.ChannelId))
                    {
                        var hero = new HeroCard(buttons: actions);
                        prompt.Attachments.Add(hero.ToAttachment());
                    }
                    else
                    {
                        prompt.SuggestedActions = new SuggestedActions {
                            Actions = actions
                        };
                    }
                }

                return(await sc.PromptAsync(DialogIds.MenuPrompt, new PromptOptions()
                {
                    Prompt = prompt,
                    RetryPrompt = TemplateManager.GenerateActivity(RoomServiceResponses.ChooseOneMenu)
                }, cancellationToken));
            }

            return(await sc.NextAsync(cancellationToken: cancellationToken));
        }
        protected async Task <DialogTurnResult> ShowTicket(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await StateAccessor.GetAsync(sc.Context, () => new SkillState());

            state.InterruptedIntent = ITSMLuis.Intent.None;

            bool firstDisplay = false;

            if (state.PageIndex == -1)
            {
                firstDisplay    = true;
                state.PageIndex = 0;
            }

            var management = ServiceManager.CreateManagement(Settings, sc.Result as TokenResponse);

            var urgencies = new List <UrgencyLevel>();

            if (state.UrgencyLevel != UrgencyLevel.None)
            {
                urgencies.Add(state.UrgencyLevel);
            }

            var states = new List <TicketState>();

            if (state.TicketState != TicketState.None)
            {
                states.Add(state.TicketState);
            }

            var countResult = await management.CountTicket(query : state.TicketTitle, urgencies : urgencies, number : state.TicketNumber, states : states);

            if (!countResult.Success)
            {
                return(await SendServiceErrorAndCancel(sc, countResult));
            }

            // adjust PageIndex
            int maxPage = Math.Max(0, (countResult.Tickets.Length - 1) / Settings.LimitSize);

            state.PageIndex = Math.Max(0, Math.Min(state.PageIndex, maxPage));

            // TODO handle consistency with count
            var result = await management.SearchTicket(state.PageIndex, query : state.TicketTitle, urgencies : urgencies, number : state.TicketNumber, states : states);

            if (!result.Success)
            {
                return(await SendServiceErrorAndCancel(sc, result));
            }

            if (result.Tickets == null || result.Tickets.Length == 0)
            {
                if (firstDisplay)
                {
                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(TicketResponses.TicketShowNone)
                    };

                    return(await sc.PromptAsync(Actions.NavigateYesNoPrompt, options));
                }
                else
                {
                    // it is unlikely to happen now
                    var token = new StringDictionary()
                    {
                        { "Page", (state.PageIndex + 1).ToString() }
                    };

                    var options = new PromptOptions()
                    {
                        Prompt = ResponseManager.GetResponse(TicketResponses.TicketEnd, token)
                    };

                    return(await sc.PromptAsync(Actions.NavigateYesNoPrompt, options));
                }
            }
            else
            {
                var cards = new List <Card>();
                foreach (var ticket in result.Tickets)
                {
                    cards.Add(GetTicketCard(sc.Context, ticket));
                }

                await sc.Context.SendActivityAsync(GetCardsWithIndicator(state.PageIndex, maxPage, cards));

                var options = new PromptOptions()
                {
                    Prompt = GetNavigatePrompt(sc.Context, TicketResponses.TicketShow, state.PageIndex, maxPage),
                };

                return(await sc.PromptAsync(Actions.ShowNavigatePrompt, options));
            }
        }
        /// <summary>
        /// Look up the six hour forecast using Accuweather.
        /// </summary>
        private async Task <DialogTurnResult> GetWeatherResponseAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await StateAccessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken);

            var service = ServiceManager.InitService(Settings);

            if (!string.IsNullOrEmpty(state.Geography))
            {
                (state.Latitude, state.Longitude) = await service.GetCoordinatesByQueryAsync(state.Geography);
            }

            // The applicable query is specified as a comma separated string composed by latitude followed by longitude.
            // e.g. "47.641268,-122.125679".
            var qureyString = string.Format("{0},{1}", state.Latitude.ToString(), state.Longitude.ToString());

            string location = string.Empty;

            if (!double.IsNaN(state.Latitude) && !double.IsNaN(state.Longitude))
            {
                location = await service.GetLocationByQueryAsync(qureyString);
            }
            else
            {
                throw new Exception("Must have Geography or Latitude & Longitude!");
            }

            var oneDayForecast = await service.GetOneDayForecastAsync(qureyString);

            var twelveHourForecast = await service.GetTwelveHourForecastAsync(qureyString);

            bool useFile = Channel.GetChannelId(stepContext.Context) == Channels.Msteams;

            var forecastModel = new SixHourForecastCard()
            {
                Speak              = oneDayForecast.Forecasts[0].Day.ShortPhrase,
                Location           = location,
                DayIcon            = GetWeatherIcon(oneDayForecast.Forecasts[0].Day.IconCode, useFile),
                Date               = $"{DateTime.Parse(oneDayForecast.Forecasts[0].Date).DayOfWeek} {CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Parse(oneDayForecast.Forecasts[0].Date).Month)} {DateTime.Parse(oneDayForecast.Forecasts[0].Date).Day}",
                MinimumTemperature = Convert.ToInt32(oneDayForecast.Forecasts[0].Temperature.Minimum.Value),
                MaximumTemperature = Convert.ToInt32(oneDayForecast.Forecasts[0].Temperature.Maximum.Value),
                ShortPhrase        = oneDayForecast.Forecasts[0].Day.ShortPhrase,
                WindDescription    = $"Winds {oneDayForecast.Forecasts[0].Day.Wind.Speed.Value} {oneDayForecast.Forecasts[0].Day.Wind.Speed.Unit} {oneDayForecast.Forecasts[0].Day.Wind.Direction.LocalizedDescription}",
                Hour1              = DateTime.Parse(twelveHourForecast.Forecasts[0].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon1              = GetWeatherIcon(twelveHourForecast.Forecasts[0].IconCode, useFile),
                Temperature1       = Convert.ToInt32(twelveHourForecast.Forecasts[0].Temperature.Value),
                Hour2              = DateTime.Parse(twelveHourForecast.Forecasts[1].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon2              = GetWeatherIcon(twelveHourForecast.Forecasts[1].IconCode, useFile),
                Temperature2       = Convert.ToInt32(twelveHourForecast.Forecasts[1].Temperature.Value),
                Hour3              = DateTime.Parse(twelveHourForecast.Forecasts[2].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon3              = GetWeatherIcon(twelveHourForecast.Forecasts[2].IconCode, useFile),
                Temperature3       = Convert.ToInt32(twelveHourForecast.Forecasts[2].Temperature.Value),
                Hour4              = DateTime.Parse(twelveHourForecast.Forecasts[3].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon4              = GetWeatherIcon(twelveHourForecast.Forecasts[3].IconCode, useFile),
                Temperature4       = Convert.ToInt32(twelveHourForecast.Forecasts[3].Temperature.Value),
                Hour5              = DateTime.Parse(twelveHourForecast.Forecasts[4].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon5              = GetWeatherIcon(twelveHourForecast.Forecasts[4].IconCode, useFile),
                Temperature5       = Convert.ToInt32(twelveHourForecast.Forecasts[4].Temperature.Value),
                Hour6              = DateTime.Parse(twelveHourForecast.Forecasts[5].Date).ToString("h tt", CultureInfo.InvariantCulture),
                Icon6              = GetWeatherIcon(twelveHourForecast.Forecasts[5].IconCode, useFile),
                Temperature6       = Convert.ToInt32(twelveHourForecast.Forecasts[5].Temperature.Value)
            };

            if (state.IsAction)
            {
                var summary      = forecastModel.Speak;
                var actionResult = new ActionResult()
                {
                    Summary       = summary,
                    ActionSuccess = true
                };
                return(await stepContext.EndDialogAsync(actionResult, cancellationToken : cancellationToken));
            }

            var templateId = SharedResponses.SixHourForecast;
            var card       = new Card(GetDivergedCardName(stepContext.Context, "SixHourForecast"), forecastModel);
            var response   = TemplateManager.GenerateActivity(templateId, card, tokens: null);

            await stepContext.Context.SendActivityAsync(response, cancellationToken);

            return(await stepContext.NextAsync(cancellationToken : cancellationToken));
        }