//This function will call drawdown API public static async Task <RootDrawDown> CallDrawDownAPI(TraceWriter log) { var watch = Stopwatch.StartNew(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;v=1")); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Globals.subsricptionKeyDrawDown); client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); var uri = "https://hymans-labs.co.uk/decumulationincomeforlifedev/drawdown/assess/"; // Post request body var body = new StringContent("{\"memberData\": {\"personA\": {\"age\": " + Globals.userAge + ",\"gender\": \"" + Globals.userGender + "\",\"healthRelativeToPeers\": \"" + Globals.userHealth + "\",\"postcodeProxy\": \"171001411\"}},\"potData\": {\"potSizePounds\": " + Globals.userPotSize + ",\"potStrategy\": {\"assetClassMapping\": {\"ukEquity\": [" + Globals.userPotEquity + "],\"cash\": [" + Globals.userPotCash + "]}}},\"drawdownIncome\": {\"regularWithdrawal\": {\"amount\": [" + Globals.userWithdrawalAmount + "],\"increaseData\": {\"increaseType\": \"rpi\",\"increaseRate\": " + Globals.userPotIncreaseRate + "}}}}", Encoding.UTF8, "application/json"); var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = body }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); watch.Stop(); log.Info("Time before post response: " + watch.ElapsedMilliseconds); var watch2 = Stopwatch.StartNew(); var postResponse = await client.SendAsync(request); watch2.Stop(); log.Info("Time after post response: " + watch2.ElapsedMilliseconds); Thread.Sleep(100); var getAcceptHeader = "application/hal+json;v=1"; client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(getAcceptHeader)); var getUrl = postResponse.Headers.Location.AbsoluteUri; var getResponse = await client.GetAsync(getUrl); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); try { RootDrawDown deserializedJson = JsonConvert.DeserializeObject <RootDrawDown>(getResponseBody); while (deserializedJson.Status == "InProgress") { Thread.Sleep(100); getResponse = await client.GetAsync(getUrl); getResponseBody = await getResponse.Content.ReadAsStringAsync(); deserializedJson = JsonConvert.DeserializeObject <RootDrawDown>(getResponseBody); } return(deserializedJson); } catch { log.Info("Null error found."); throw new ArgumentNullException(); } }
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.")); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { /* * //TEST LifeExpectancy * 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", "ab05b31f579c4d92aa06bd61d4186b64"); * client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); * * var uri = "https://hymans-labs.co.uk/lifeexpectancydev/"; * * // Post request body * var body = new StringContent("{\"personA\": {\"age\": 50,\"gender\": \"male\",\"healthRelativeToPeers\": \"same\",\"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"); * */ //TEST Drawdown // Request headers var watch = Stopwatch.StartNew(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;v=1")); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "9a511111d99a41f5b298ed8f4f0e9ac3"); client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); var uri = "https://hymans-labs.co.uk/decumulationincomeforlifedev/drawdown/assess"; // Post request body var body = new StringContent("{\"memberData\": {\"personA\": {\"age\": 60,\"gender\": \"male\",\"healthRelativeToPeers\": \"same\",\"postcodeProxy\": \"161001411\"}},\"potData\": {\"potSizePounds\": 100000,\"potStrategy\": {\"assetClassMapping\": {\"ukEquity\": [0.5],\"cash\": [0.5]}}},\"drawdownIncome\": {\"regularWithdrawal\": {\"amount\": [5000],\"increaseData\": {\"increaseType\": \"rpi\",\"increaseRate\": 0.01}}}}", 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"); watch.Stop(); log.Info("Time before post response: " + watch.ElapsedMilliseconds); var watch2 = Stopwatch.StartNew(); var postResponse = await client.SendAsync(request); watch2.Stop(); log.Info("Time after post response: " + watch2.ElapsedMilliseconds); var getAcceptHeader = "application/hal+json;v=1"; client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(getAcceptHeader)); var getUrl = postResponse.Headers.Location.AbsoluteUri; var getResponse = await client.GetAsync(getUrl); var getResponseBody = await getResponse.Content.ReadAsStringAsync(); RootDrawDown deserializedJson = JsonConvert.DeserializeObject <RootDrawDown>(getResponseBody); while (deserializedJson.Status == "InProgress") { Thread.Sleep(100); getResponse = await client.GetAsync(getUrl); getResponseBody = await getResponse.Content.ReadAsStringAsync(); deserializedJson = JsonConvert.DeserializeObject <RootDrawDown>(getResponseBody); } var test = deserializedJson.Data.LongevityWeightedProbSuccess; /* * * //TEST GET POSTCODE PROXY * //Post Request headers * * HttpClient client = new HttpClient(); * client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;v=1")); * client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "ab05b31f579c4d92aa06bd61d4186b64"); * client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); * * var uri = "https://hymans-labs.co.uk/Longevity/postcode"; * * //Post request body * var body = new StringContent("{\"vitaCurvesVersion\": \"CV16v1_1214\",\"vitaSegmentsEdition\": \"LTG2014\",\"postcodes\": [\"EH144AS\"]}", Encoding.UTF8, "application/json"); * var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = body }; * request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); * var postResponse = await client.SendAsync(request); * * //Get request header and URL * var getAcceptHeader = "application/hal+json;v=1"; * client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(getAcceptHeader)); * var abURL = postResponse.Headers.Location.AbsoluteUri; * * string host = "https://postcodeproxy-dev.azurewebsites.net/longevitypostcodeproxy/postcodeproxy/"; * string id = abURL.Substring(host.Length,abURL.Length-host.Length); * * var getUrl = "https://hymans-labs.co.uk/Longevity/postcodeproxy/" + id; * Thread.Sleep(500); * //Get response * var getResponse = await client.GetAsync(getUrl); * var getResponseBody = await getResponse.Content.ReadAsStringAsync(); * var postcode = "EH144AS"; * var test2 = getResponseBody.Replace(postcode, "Postcode"); * var result = ""; * try * { * RootPostcodeProxy deserializedJson = JsonConvert.DeserializeObject<RootPostcodeProxy>(test2); * result = deserializedJson.MappedPostcodes[0].Postcode; * } * catch * { * result = "1234566"; * } */ /* * var watch = new Stopwatch(); * * //Post Request headers * HttpClient client = new HttpClient(); * client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;v=1")); * client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "9a511111d99a41f5b298ed8f4f0e9ac3"); * client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); * * var uri = "https://hymans-labs.co.uk/decumulationincomeforlifedev/drawdown/assess/"; * * //Post request body * var body = new StringContent("{\"memberData\": {\"personA\": {\"age\": 60,\"gender\": \"male\",\"healthRelativeToPeers\": \"same\",\"postcodeProxy\": \"171001411\"}},\"potData\": {\"potSizePounds\": 100000,\"potStrategy\": {\"assetClassMapping\": {\"ukEquity\": [0.5],\"cash\": [0.5]}}},\"drawdownIncome\": {\"regularWithdrawal\": {\"amount\": [5000],\"increaseData\": {\"increaseType\": \"rpi\",\"increaseRate\": 0.01}}}}", Encoding.UTF8, "application/json"); * var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = body }; * request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); * var postResponse = await client.SendAsync(request); * * //Get request header and URL * var getAcceptHeader = "application/hal+json;v=1"; * client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(getAcceptHeader)); * var getUrl = postResponse.Headers.Location.AbsoluteUri; * * //Get response * var getResponse = await client.GetAsync(getUrl); * * watch.Stop(); * log.Info("Time used for Drawdown API in background " + watch.ElapsedMilliseconds + " ms."); */ return(new OkObjectResult("passed")); }