//This function call LifeExpectancy API public static async Task <RootLifeExpectancy> CallLifeExpectancyAPI(TraceWriter log) { var watch = Stopwatch.StartNew(); // Request headers HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;v=1")); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Globals.subsricptionKeyLifeExpectancy); client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); var uri = "https://hymans-labs.co.uk/lifeexpectancydev/"; // Post request body var body = new StringContent("{\"personA\": {\"age\": " + Globals.userAge + ",\"gender\": \"" + Globals.userGender + "\",\"healthRelativeToPeers\": \"" + Globals.userHealth + "\",\"postcodeProxy\": \"171001411\"}}", Encoding.UTF8, "application/json"); log.Info(body.ToString()); var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = body }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var postResponse = await client.SendAsync(request); var getAcceptHeader = "application/hal+json;v=1"; client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(getAcceptHeader)); var getUrl = postResponse.Headers.Location.AbsoluteUri; Thread.Sleep(100); var getResponse = await client.GetAsync(getUrl); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); RootLifeExpectancy deserializedJson = JsonConvert.DeserializeObject <RootLifeExpectancy>(getResponseBody); while (deserializedJson.Status == "InProgress") { Thread.Sleep(100); getResponse = await client.GetAsync(getUrl); getResponseBody = await getResponse.Content.ReadAsStringAsync(); deserializedJson = JsonConvert.DeserializeObject <RootLifeExpectancy>(getResponseBody); } watch.Stop(); log.Info("Time used for life expectancy API: " + watch.ElapsedMilliseconds + " ms"); return(deserializedJson); }
public static async Task <SkillResponse> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)][FromBody] SkillRequest req, TraceWriter log) { //Find Request Type var requestType = req.GetRequestType(); //Keep deviceId and AccessToken for access user's location var accessToken = req.Context.System.ApiAccessToken; var deviceID = req.Context.System.Device.DeviceID; var apiEndPoint = req.Context.System.ApiEndpoint; var requestID = req.Request.RequestId; //Check intent request if (requestType == typeof(IntentRequest)) { //Store intent request and intent's name var intentRequest = req.Request as IntentRequest; var intentName = intentRequest.Intent.Name; var updatedIntent = new Intent(); //Check intent's name switch (intentName) { case "AMAZON.CancelIntent": return(ResponseBuilder.Tell("See you next time. Goodbye.")); case "AMAZON.HelpIntent": return(ResponseBuilder.Tell("You can try how long can I live ?")); case "AMAZON.StopIntent": return(ResponseBuilder.Tell("See you next time. Goodbye.")); case "SessionEndedRequest": return(ResponseBuilder.Tell("See you next time. Goodbye.")); case "LifeExpectancy": //Create updated intent updatedIntent.Name = "LifeExpectancy"; updatedIntent.ConfirmationStatus = "NONE"; updatedIntent.Slots = intentRequest.Intent.Slots; if (intentRequest.DialogState == "STARTED") { //Find User Location Globals.userPostcode = await GetUserLocations(deviceID, accessToken, apiEndPoint, log); if (Globals.userPostcode == "NoPermission") { //Ask for location permission IEnumerable <string> locationPermission = new string[] { "read::alexa:device:all:address:country_and_postal_code" }; return(ResponseBuilder.TellWithAskForPermissionConsentCard("Please allow me to access the location to find life expectancy. Please check permission request on your mobile.", locationPermission)); } log.Info(" postcode = " + Globals.userPostcode); //Call Postcode proxy API log.Info("Calling postcodeproxy API"); Globals.userPostcodeProxy = await CallPostCodeProxyAPI(log); log.Info("Postcode Proxy is " + Globals.userPostcodeProxy); log.Info("Current Dialogstate: " + intentRequest.DialogState); return(ResponseBuilder.DialogDelegate(updatedIntent)); } else if (intentRequest.DialogState != "COMPLETED") { log.Info("Current Dialogstate: " + intentRequest.DialogState); return(ResponseBuilder.DialogDelegate(updatedIntent)); } else { //Dialog already completed log.Info("Current Dialogstate: " + intentRequest.DialogState); //Store slot values into globals variables log.Info("Extract slots value"); GetSlotValues(intentRequest, log, updatedIntent); //Check valid/invalid value log.Info("Check slots value"); var isSlotsValid = CheckSlotsValue(); log.Info("Check slots value:" + isSlotsValid); if (!isSlotsValid) { return(InvalidSlotsResponse()); } //Call Life expectancy API RootLifeExpectancy lifeExpectancyResult = await CallLifeExpectancyAPI(log); var lifeExpectancyValue = lifeExpectancyResult.Data.LifeExpectancyPersonA; //Return response return(ResponseBuilder.Tell("Your life expectancy is " + lifeExpectancyValue + " years old. That's great.")); } case "DrawDown": //Create updated intent updatedIntent.Name = "DrawDown"; updatedIntent.ConfirmationStatus = "NONE"; updatedIntent.Slots = intentRequest.Intent.Slots; if (intentRequest.DialogState == "STARTED") { //Find User Location Globals.userPostcode = await GetUserLocations(deviceID, accessToken, apiEndPoint, log); if (Globals.userPostcode == "NoPermission") { //Ask for location permission IEnumerable <string> locationPermission = new string[] { "read::alexa:device:all:address:country_and_postal_code" }; return(ResponseBuilder.TellWithAskForPermissionConsentCard("Please allow me to access the location to find life expectancy. Please check permission request on your mobile.", locationPermission)); } log.Info(" postcode = " + Globals.userPostcode); //Call Postcode proxy API log.Info("Calling postcodeproxy API"); Globals.userPostcodeProxy = await CallPostCodeProxyAPI(log); log.Info("Postcode Proxy is " + Globals.userPostcodeProxy); log.Info("Current Dialogstate: " + intentRequest.DialogState); return(ResponseBuilder.DialogDelegate(updatedIntent)); } else if (intentRequest.DialogState != "COMPLETED") { CallDrawDownAPIBackground(log); log.Info("Current Dialogstate: " + intentRequest.DialogState); return(ResponseBuilder.DialogDelegate(updatedIntent)); } else { //Dialog already completed log.Info("Current Dialogstate: " + intentRequest.DialogState); //Store slot values into globals variables log.Info("Extract slot values"); GetSlotValues(intentRequest, log, updatedIntent); //Check valid/invalid value var isSlotsValid = CheckSlotsValue(); log.Info("Check slots valid:" + isSlotsValid); if (!isSlotsValid) { return(InvalidSlotsResponse()); } //Call Drawdown API log.Info("Calling Drawdown API"); RootDrawDown drawDownResult = await CallDrawDownAPI(log); var longestvityPercent = drawDownResult.Data.LongevityWeightedProbSuccess * 100; var lifeExpectancy = drawDownResult.Data.LifeExpectancyOutput.LifeExpectancyPersonA; //Return response if (longestvityPercent < 50) { return(ResponseBuilder.Tell("You life expectancy is " + lifeExpectancy + " years old. You have a chance " + longestvityPercent + " percent to achieve your goal. You might need to adjust your target to increase the chance.")); } else { return(ResponseBuilder.Tell("Wow! We have a great news. You life expectancy is " + lifeExpectancy + " years old. You have a chance " + longestvityPercent + " percent to achieve your goal.")); } } case "WhatHymans": var whatSpeech = "At Hymans Robertson, we provide independent pensions, investments, benefits and risk consulting services, as well as data and technology solutions, to employers, trustees and financial services institutions. For more information please visit www.hymans.co.uk"; var whatReprompt = "Let's try how long can I live."; return(CreateResponse(whatSpeech, whatReprompt)); case "WhyHymans": var whySpeech = "At the forefront of our industry, we’re influencing the way it works. Proud pioneers for the past 95 years, we’re at the vanguard of innovation. Our solutions give companies, trustees and members everything they need for brighter pensions prospects."; var whyReprompt = "Let's try how long can I live."; return(CreateResponse(whySpeech, whyReprompt)); case "WhereHymans": var whereSpeech = "We have offices located in London, Birmingham, Edinburgh, and Glasglow. If you want to contact us, please visit www.hymans.co.uk"; var whereReprompt = "Let's try how long can I live."; return(CreateResponse(whereSpeech, whereReprompt)); } } else if (requestType == typeof(LaunchRequest)) { return(CreateResponse("Welcome to Hymans Robertson. We can find life expectancy and success chance from your investment target. You can use command like How long can I live? or do I have enough money for retirement?", "Try how long can I live?")); } return(ResponseBuilder.Tell("Sorry, we don't know your command. Please try again.")); }