public void HandleAlexaRequestTest_HandlesSuccessCorrectly() { // arrange Word word = new Word { Id = 1, WordName = "test", PartOfSpeech = "noun", Definition = "a test", Example = " a moq uses a test" }; AlexaRequestPayload alexaRequestPayload = AlexaSkillProjectTestHelpers.GetAlexaRequestPayload("AlexaRequestPayloadSayWordIntent.json"); alexaRequestPayload.Session.Attributes.LastWord = word.WordName; alexaRequestPayload.Session.Attributes.LastWordDefinition = word.Definition; var cacheService = new Mock <ICacheService>(); cacheService.Setup(c => c.RetrieveAlexaRequest(alexaRequestPayload.Session.SessionId)).Returns(alexaRequestPayload); var wordOfTheDayIntentHandlerStrategy = new SayWordIntentHandlerStrategy(cacheService.Object); // act AlexaResponse alexaResponse = wordOfTheDayIntentHandlerStrategy.HandleAlexaRequest(alexaRequestPayload); // assert Assert.IsTrue(alexaResponse.Response.OutputSpeech.Ssml.Contains( Utility.GetDescriptionFromEnumValue(SuccessPhrases.Great))); }
public AlexaResponse ProcessAlexaRequest(AlexaRequestPayload alexaRequestPayload) { // validate request time stamp and app id // note that there is custom validation in the AlexaRequestValidationHandler SpeechletRequestValidationResult validationResult = _alexaRequestValidationService.ValidateAlexaRequest(alexaRequestPayload); if (validationResult == SpeechletRequestValidationResult.OK) { try { // transform request AlexaRequest alexaRequest = _alexaRequestMapper.MapAlexaRequest(alexaRequestPayload); // persist request and member _alexaRequestPersistenceService.PersistAlexaRequestAndMember(alexaRequest); // create a request handler strategy from the alexarequest IAlexaRequestHandlerStrategy alexaRequestHandlerStrategy = _alexaRequestHandlerStrategyFactory.CreateAlexaRequestHandlerStrategy(alexaRequestPayload); // use the handlerstrategy to process the request and generate a response AlexaResponse alexaResponse = alexaRequestHandlerStrategy.HandleAlexaRequest(alexaRequestPayload); // return response return(alexaResponse); } catch (Exception exception) { // todo: log the error return(new AlexaResponse("There was an error " + exception.Message)); //return new AlexaWordErrorResponse().GenerateCustomError(); } } return(null); }
/// <summary> /// This method implements retry logic to get a word (specific method implemented in base class) /// This method builds the response dictionary for the word and alexa response /// This method ensures caching for between session logic /// The WordOfTheDay and AnotherWord strategies implement this abstract class with different responses and word retrival logic /// </summary> /// <param name="alexaRequest"></param> /// <returns></returns> public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { // initialize variables used in case of retry Word word = null; // what word will we get - should never be null int retryCounter = 0; Dictionary <WordEnum, string> wordResponseDictionary = null; // this method must return populated dictionary string wordResponse = null; // get the word // get the response dictionary from the word // handle retry errors - get another word from the word service if invalid response dictionary try { // repeat api call and parse while (wordResponse == null) { // Get the word - implemented in base class if (retryCounter == 0) { word = GetWord(); } // Get random word - there was an issue with the first word else { word = _wordService.GetRandomWord(); } try { wordResponseDictionary = _dictionaryService.GetWordDictionaryFromString(word.WordName); } catch (Exception exception) { return(new AlexaResponse("Unable to build response dictionary for the word: " + word + " " + exception.Message)); } wordResponse = wordResponseDictionary[WordEnum.Word]; retryCounter += 1; } AlexaResponse alexaResponse = BuildAlexaResponse(alexaRequest, wordResponseDictionary); // assign word to request for caching the request between intents alexaRequest.Session.Attributes = new AlexaRequestPayload.SessionCustomAttributes(); alexaRequest.Session.Attributes.LastWord = word.WordName; // use the word from the db as it is saved in intent slots alexaRequest.Session.Attributes.LastWordDefinition = wordResponseDictionary[WordEnum.WordDefinition]; // cache the request and its above added session attributes _cacheService.CacheAlexaRequest(alexaRequest); return(alexaResponse); } catch (Exception exception) { // todo - log the exception return(new AlexaWordErrorResponse().GenerateCustomError()); } }
private bool VerifyRequestTimestamp(AlexaRequestPayload alexaRequest, DateTime referenceTimeUtc) { // verify timestamp is within tolerance var diff = referenceTimeUtc - alexaRequest.Request.Timestamp; return(Math.Abs((decimal)diff.TotalSeconds) <= AlexaSdk.TIMESTAMP_TOLERANCE_SEC); }
public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { var response = new AlexaResponse("Thanks for using Grammar Tool. You can also visit Grammar Tool App dot com for more information. I hope to see you again soon."); response.Response.ShouldEndSession = true; return(response); }
public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { var response = new AlexaResponse("You can ask What is the Word of the Day. You can also visit Grammar Tool App dot com for more information."); response.Response.ShouldEndSession = false; return(response); }
public void CacheAlexaRequest(AlexaRequestPayload alexaRequest) { // use set to add sessionid/request to memory cache // http://stackoverflow.com/questions/8868486/whats-the-difference-between-memorycache-add-and-memorycache-set MemoryCache.Default.Set(alexaRequest.Session.SessionId, alexaRequest, new CacheItemPolicy() ); }
public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { var response = new AlexaResponse("Welcome to Grammar Tool. You can start by asking What is the word of the day?"); response.Response.Card.Title = ConfigurationSettings.AppSettings["AppTitle"]; response.Response.Card.Content = "Welcome to Grammar Tool"; response.Response.Reprompt.OutputSpeech.Text = "Please ask What is the Word of The Day?"; response.Response.ShouldEndSession = false; return(response); }
/// <summary> /// This method gets the word spoken by the user (using the slots and intents) /// See the LIST_OF_WORDS.txt in speech assets /// The word spoken is compared to the latest word given (and cached using session id) /// </summary> /// <param name="alexaRequest"></param> /// <returns></returns> public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { // get the word said back to alexa string wordSaid = null; var slots = alexaRequest.Request.Intent.GetSlots(); foreach (var slot in slots) { if (slot.Key.Equals("Word")) { wordSaid = slot.Value; } } // compare with the last word given to user string lastWordGiven = null; string lastWordGivenDefinition = null; AlexaRequestPayload lastRequest = _cacheService.RetrieveAlexaRequest(alexaRequest.Session.SessionId); try { //AlexaRequestPayload lastRequest = (AlexaRequestPayload)MemoryCache.Default.Get(alexaRequest.Session.SessionId); lastWordGiven = lastRequest.Session.Attributes.LastWord; lastWordGivenDefinition = lastRequest.Session.Attributes.LastWordDefinition; } catch (Exception exception) { // log exception in the future - for now the words will remain null } // build the response speech string outputSpeech = null; if (wordSaid.Equals(lastWordGiven)) { outputSpeech = BuildSuccessResponse(wordSaid, lastWordGiven, lastWordGivenDefinition); } else { outputSpeech = BuildErrorResponse(wordSaid, lastWordGiven); } // build the alexaresponse AlexaResponse alexaResponse = new AlexaResponse(); alexaResponse.Response.OutputSpeech.Ssml = string.Format("<speak>{0}</speak>", outputSpeech); alexaResponse.Response.Reprompt.OutputSpeech.Ssml = string.Format("<speak><p>You can say</p><p>The word of the day is {0} </p></speak>", lastWordGiven); alexaResponse.Response.ShouldEndSession = false; alexaResponse.Response.OutputSpeech.Type = "SSML"; return(alexaResponse); }
public AlexaRequestPayload RetrieveAlexaRequest(string alexaRequestSessionId) { AlexaRequestPayload lastRequestPayload = null; try { lastRequestPayload = (AlexaRequestPayload)MemoryCache.Default.Get(alexaRequestSessionId); } catch (Exception exception) { return(null); } return(lastRequestPayload); }
public static AlexaRequestPayload GetAlexaRequestPayload(string filename) { var dir = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName); var path = string.Format("{0}\\{1}", dir, filename); AlexaRequestPayload alexaRequestPayload = null; // deserialize JSON directly from a file using (StreamReader file = File.OpenText(path)) { JsonSerializer serializer = new JsonSerializer(); alexaRequestPayload = (AlexaRequestPayload)serializer.Deserialize(file, typeof(AlexaRequestPayload)); } return(alexaRequestPayload); }
public void HandleAlexaRequestTest() { // arrange Word word = new Word { Id = 1, WordName = "test", PartOfSpeech = "noun", Definition = "a test", Example = " a moq uses a test" }; var wordService = new Mock <IWordService>(); wordService.Setup(w => w.GetRandomWord()).Returns(word); Dictionary <WordEnum, string> mockDictionary = new Dictionary <WordEnum, string>(); mockDictionary[WordEnum.Word] = word.WordName; mockDictionary[WordEnum.WordPartOfSpeech] = word.PartOfSpeech; mockDictionary[WordEnum.WordDefinition] = word.Definition; mockDictionary[WordEnum.WordExample] = word.Example; var dictionaryService = new Mock <IDictionaryService>(); dictionaryService.Setup(w => w.GetWordDictionaryFromString(word.WordName)).Returns(mockDictionary); var cacheService = new Mock <ICacheService>(); var wordOfTheDayIntentHandlerStrategy = new WordOfTheDayIntentHandlerStrategy(wordService.Object, dictionaryService.Object, cacheService.Object); AlexaRequestPayload alexaRequestPayload = AlexaSkillProjectTestHelpers.GetAlexaRequestPayload("AlexaRequestPayloadTest.json"); alexaRequestPayload.Request.Type = "IntentRequest"; alexaRequestPayload.Request.Intent.Name = "WordOfTheDayIntent"; // act AlexaResponse alexaResponse = wordOfTheDayIntentHandlerStrategy.HandleAlexaRequest(alexaRequestPayload); // assert Assert.IsTrue(alexaResponse.Response.OutputSpeech.Ssml.Contains("<speak><p>The Word is test</p>")); Assert.AreEqual(alexaRequestPayload.Session.Attributes.LastWord, word.WordName); Assert.AreEqual(alexaRequestPayload.Session.Attributes.LastWordDefinition, word.Definition); }
public void WordOfTheDayTest() { // arrange AlexaRequestPayload alexaRequestPayload = new AlexaRequestPayload(); var alexaRequestService = new Mock <IAlexaRequestService>(); alexaRequestService.Setup(s => s.ProcessAlexaRequest(alexaRequestPayload)).Returns(new AlexaResponse("hello")); AlexaController controller = new AlexaController(alexaRequestService.Object); // act AlexaResponse result = controller.WordOfTheDay(alexaRequestPayload); // assert Assert.AreEqual(result.Response.OutputSpeech.Text, "hello"); }
public IAlexaRequestHandlerStrategy CreateAlexaRequestHandlerStrategy(AlexaRequestPayload alexaRequest) { switch (alexaRequest.Request.Type) { case "LaunchRequest": case "SessionEndedRequest": IAlexaRequestHandlerStrategy strategy = _availableStrategies .FirstOrDefault(s => s.SupportedRequestType == alexaRequest.Request.Type); return(strategy); case "IntentRequest": IAlexaRequestHandlerStrategy intentStrategy = _availableStrategies .FirstOrDefault(s => s.SupportedRequestIntentName == alexaRequest.Request.Intent.Name); return(intentStrategy); default: throw new NotImplementedException(); } }
public AlexaRequest MapAlexaRequest(AlexaRequestPayload alexaRequestInputModel) { AlexaRequest alexaRequest = new AlexaRequest { AlexaMemberId = (alexaRequestInputModel.Session.Attributes == null) ? 0 : alexaRequestInputModel.Session.Attributes.MemberId, Timestamp = alexaRequestInputModel.Request.Timestamp, Intent = (alexaRequestInputModel.Request.Intent == null) ? "" : alexaRequestInputModel.Request.Intent.Name, AppId = alexaRequestInputModel.Session.Application.ApplicationId, RequestId = alexaRequestInputModel.Request.RequestId, SessionId = alexaRequestInputModel.Session.SessionId, UserId = alexaRequestInputModel.Session.User.UserId, IsNew = alexaRequestInputModel.Session.New, Version = alexaRequestInputModel.Version, Type = alexaRequestInputModel.Request.Type, SlotsList = alexaRequestInputModel.Request.Intent.GetSlots(), DateCreated = DateTime.UtcNow }; return alexaRequest; }
/// <summary> /// Builds the response from the request and retrieved word properties /// </summary> /// <param name="alexaRequest"></param> /// <param name="wordResponseDictionary"></param> /// <returns></returns> protected AlexaResponse BuildAlexaResponse(AlexaRequestPayload alexaRequest, Dictionary <WordEnum, string> wordResponseDictionary) { AlexaResponse alexaResponse = new AlexaResponse(); alexaResponse.Response.OutputSpeech.Ssml = string.Format("<speak>{0}</speak>", BuildOutputSpeech(wordResponseDictionary)); alexaResponse.Response.Card.Title = ConfigurationSettings.AppSettings["AppTitle"]; alexaResponse.Response.Card.Content = BuildOutputCardContent(wordResponseDictionary); alexaResponse.Response.Reprompt.OutputSpeech.Ssml = string.Format("<speak><p>You can say</p><p>The word is {0}</p><p>Or you can say</p><p>Get another word</p></speak>", wordResponseDictionary[WordEnum.Word]); alexaResponse.Response.ShouldEndSession = false; alexaResponse.Response.OutputSpeech.Type = "SSML"; alexaResponse.Response.Reprompt.OutputSpeech.Type = "SSML"; return(alexaResponse); }
public SpeechletRequestValidationResult ValidateAlexaRequest(AlexaRequestPayload alexaRequest) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; if (!ConfigurationSettings.AppSettings["Mode"].Equals("Debug")) { // check timestamp if (!VerifyRequestTimestamp(alexaRequest, DateTime.UtcNow)) { validationResult = SpeechletRequestValidationResult.InvalidTimestamp; throw new Exception(validationResult.ToString()); } // check app id if (!VerifyApplicationIdHeader(alexaRequest)) { validationResult = SpeechletRequestValidationResult.InvalidAppId; throw new Exception(validationResult.ToString()); } } return(validationResult); }
public void HandleAlexaRequestTest_HandlesFailureCorrectly() { // arrange Word word = new Word { Id = 1, WordName = "test", PartOfSpeech = "noun", Definition = "a test", Example = " a moq uses a test" }; // get the example payload and set the session attributes AlexaRequestPayload alexaRequestPayload = AlexaSkillProjectTestHelpers.GetAlexaRequestPayload("AlexaRequestPayloadSayWordIntent.json"); alexaRequestPayload.Session.Attributes.LastWord = "Incorrect"; alexaRequestPayload.Session.Attributes.LastWordDefinition = "Incorrect definition"; // these will be the attributes returned by the mock cache service var cacheService = new Mock <ICacheService>(); cacheService.Setup(c => c.RetrieveAlexaRequest(alexaRequestPayload.Session.SessionId)).Returns(alexaRequestPayload); var wordOfTheDayIntentHandlerStrategy = new SayWordIntentHandlerStrategy(cacheService.Object); // reset the session attributes to not match the cached session alexaRequestPayload.Session.Attributes.LastWord = word.WordName; alexaRequestPayload.Session.Attributes.LastWord = word.Definition; // act AlexaResponse alexaResponse = wordOfTheDayIntentHandlerStrategy.HandleAlexaRequest(alexaRequestPayload); // assert Assert.IsTrue(alexaResponse.Response.OutputSpeech.Ssml.Contains( Utility.GetDescriptionFromEnumValue(ErrorPhrases.Incorrect))); }
public dynamic WordOfTheDay(AlexaRequestPayload alexaRequestInput) { return(_alexaRequestService.ProcessAlexaRequest(alexaRequestInput)); }
public dynamic YourRoute(AlexaRequestPayload alexaRequestInput) { return(_alexaRequestService.ProcessAlexaRequest(alexaRequestInput)); }
public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { return(new AlexaResponse("Hello Andy")); }
public AlexaResponse HandleAlexaRequest(AlexaRequestPayload alexaRequest) { return(null); }
private bool VerifyApplicationIdHeader(AlexaRequestPayload alexaRequest) { string alexaApplicationId = ConfigurationSettings.AppSettings["AlexaApplicationId"]; return(alexaRequest.Session.Application.ApplicationId.Equals(alexaApplicationId)); }
public dynamic Test(AlexaRequestPayload alexaRequestInput) { return(new AlexaResponse("Non db call working")); }
public void ProcessAlexaRequestTest() { // arrange AlexaRequestPayload alexaRequestPayload = AlexaSkillProjectTestHelpers.GetAlexaRequestPayload("AlexaRequestPayloadTest.json"); var alexaRequestMapper = new Mock <IAlexaRequestMapper>(); var alexaRequestPersistenceService = new Mock <IAlexaRequestPersistenceService>(); Word word = new Word { Id = 1, WordName = "test", PartOfSpeech = "noun", Definition = "a test", Example = " a moq uses a test" }; var wordService = new Mock <IWordService>(); wordService.Setup(w => w.GetRandomWord()).Returns(word); var cacheService = new Mock <ICacheService>(); //cacheService.Setup(c => c.CacheAlexaRequest(alexaRequestPayload)) Dictionary <WordEnum, string> mockDictionary = new Dictionary <WordEnum, string>(); mockDictionary[WordEnum.Word] = word.WordName; mockDictionary[WordEnum.WordPartOfSpeech] = word.PartOfSpeech; mockDictionary[WordEnum.WordDefinition] = word.Definition; mockDictionary[WordEnum.WordExample] = word.Example; var dictionaryService = new Mock <IDictionaryService>(); dictionaryService.Setup(w => w.GetWordDictionaryFromString(word.WordName)).Returns(mockDictionary); var wordOfTheDayIntentHandlerStrategy = new WordOfTheDayIntentHandlerStrategy(wordService.Object, dictionaryService.Object, cacheService.Object); var alexaRequestHandlerStrategyFactory = new Mock <IAlexaRequestHandlerStrategyFactory>(); alexaRequestHandlerStrategyFactory.Setup(x => x.CreateAlexaRequestHandlerStrategy(alexaRequestPayload)).Returns(wordOfTheDayIntentHandlerStrategy); var alexaRequestValidationService = new Mock <IAlexaRequestValidationService>(); alexaRequestValidationService.Setup(x => x.ValidateAlexaRequest(alexaRequestPayload)).Returns(SpeechletRequestValidationResult.OK); var alexaRequestService = new AlexaRequestService( alexaRequestMapper.Object, alexaRequestPersistenceService.Object, alexaRequestHandlerStrategyFactory.Object, alexaRequestValidationService.Object ); alexaRequestPayload.Request.Type = "IntentRequest"; alexaRequestPayload.Request.Intent.Name = "WordOfTheDayIntent"; // act AlexaResponse alexaResponse = alexaRequestService.ProcessAlexaRequest(alexaRequestPayload); // assert Assert.IsTrue(alexaResponse.Response.OutputSpeech.Ssml.Contains("<speak><p>The Word is test</p>")); }