public void BuildQueryTest() { var message = new ResponseBuilder() .SetHeader("header", "val1") .SetLocation("http://me.com") .SetParam("param1", "val") .SetStatusCode(200) .BuildQueryMessage(); Assert.AreEqual(null, message.ContentType); Assert.AreEqual(1, message.Headers.Count); Assert.AreEqual("header", message.Headers.ElementAt(0).Key); Assert.AreEqual("val1", message.Headers.ElementAt(0).Value); Assert.AreEqual(200, message.StatusCode); Assert.AreEqual("http://me.com?param1=val", message.LocationUri); }
public void BuildJsonTest() { var message = new ResponseBuilder() .SetHeader("header", "val1") .SetLocation("http://me.com") .SetParam("param1","val") .SetStatusCode(200) .BuildJsonMessage(); Assert.AreEqual(ContentType.Json, message.ContentType); Assert.AreEqual(1, message.Headers.Count); Assert.AreEqual("header", message.Headers.ElementAt(0).Key); Assert.AreEqual("val1", message.Headers.ElementAt(0).Value); Assert.AreEqual("http://me.com", message.LocationUri); Assert.AreEqual(200, message.StatusCode); Assert.IsTrue(message.Body.Contains("\"param1\":\"val\"")); }
private void AppMain_Loaded(object sender, RoutedEventArgs e) { Point Desktop = new Point(SystemParameters.WorkArea.Width, SystemParameters.WorkArea.Height); this.Left = 10; this.Top = Desktop.Y - (this.Height + 10); this.Topmost = false; RequestBuilder nipp = new RequestBuilder("http://www.nipponanime.net/forum/nisekoi/(one-shot)-nisekoi-ch-0-(lightning)/"); txtTest.Text = XHR.Connect(nipp).ToString(); nipp = new RequestBuilder("http://upic.me/i/f1/7bx12.jpg"); nipp.Referer = "http://www.nipponanime.net/forum/nisekoi"; XHR c = new XHR(nipp); ResponseBuilder a = new ResponseBuilder(); do { //File.WriteAllBytes("C:\\Users\\HaKko\\Desktop\\"+Path.GetRandomFileName() +".txt", c.ReceiveByte()); Console.WriteLine(XHR.BytesPerSecond(c.ReceivedData)); } while (c.ReceivedData > 0); }
private async Task AssertRegularResponse(bool disableDirectStreaming, Action<ResponseBuilder<RootNodeInfoResponse>> mutate = null) { var settings = disableDirectStreaming ? _settingsDisableDirectStream : _settings; var memoryStreamFactory = new TrackMemoryStreamFactory(); var requestData = new RequestData(HttpMethod.GET, "/", null, settings, null, memoryStreamFactory) { Node = new Node(new Uri("http://localhost:9200")) }; var responseBuilder = new ResponseBuilder<RootNodeInfoResponse>(requestData) { }; mutate?.Invoke(responseBuilder); var stream = new TrackDisposeStream(); responseBuilder.Stream = stream; var response = responseBuilder.ToResponse(); memoryStreamFactory.Created.Count().Should().Be(disableDirectStreaming ? 1 : 0); if (disableDirectStreaming) { var memoryStream = memoryStreamFactory.Created[0]; memoryStream.IsDisposed.Should().BeTrue(); } stream.IsDisposed.Should().BeTrue(); stream = new TrackDisposeStream(); responseBuilder.Stream = stream; response = await responseBuilder.ToResponseAsync(); memoryStreamFactory.Created.Count().Should().Be(disableDirectStreaming ? 2 : 0); if (disableDirectStreaming) { var memoryStream = memoryStreamFactory.Created[1]; memoryStream.IsDisposed.Should().BeTrue(); } stream.IsDisposed.Should().BeTrue(); }
/// <summary> /// The writeClose. /// </summary> /// <param name="state">The state<see cref="string"/>.</param> private void writeClose(string state = "close") { ResponseBuilder.AppendLine("Connection: " + state); ResponseBuilder.AppendLine(""); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { //-- Deserializing the json that alexa sent to us string json = await req.ReadAsStringAsync(); var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json); var requestType = skillRequest.GetRequestType(); SkillResponse response = null; if (requestType == typeof(LaunchRequest)) //-- Enter in this if when we tell to Alexa to open our skill: "Controllo Vocale" { if (videosUtteranceInovked != true && ShowTireInfoInvoked != true && ShowTireInvoked != true) { response = ResponseBuilder.Tell("Benvenuto in Pirelli Voice Control"); response.Response.ShouldEndSession = false; } else { response = ResponseBuilder.Tell("Ciao"); response.Response.ShouldEndSession = false; } await connection.StartAsync(); //-- Starting our SignalR connnection only one time at the opening of our skill. It will be closed only when user will invoke the "AMAZON.StopIntent" timer = 0; } else if (requestType == typeof(IntentRequest)) //-- Enter here if user invoked an Intent { var intentRequest = skillRequest.Request as IntentRequest; //categoryUtteranceInovked = false; switch (intentRequest.Intent.Name) { //RIGUARDRE I METODI CHE RICHIAMANO IL GESTORE BL PER FILTRARE PER ID E NOME case "ShowVideoIntent": if (intentRequest.Intent.Slots["numero"].Value == null) //-- Enter in this if when the user want to see 'All videos' section { messaggio = $"Ciao, se vuoi ti mostro qualche video. Quale vuoi vedere ?"; timer = 2000; await connection.InvokeAsync("sendAllVideo", GestoreBLL.GetAllVideos()); //-- this will send to the client (Front-End) a List of Media (but only Videos) videosUtteranceInovked = true; } else if (intentRequest.Intent.Slots["numero"].Value != null && videosUtteranceInovked == true) // ----- Enter here only when user can tell to alexa to play a video { timer = 0; if (int.Parse(intentRequest.Intent.Slots["numero"].Value) < 6 || int.Parse(intentRequest.Intent.Slots["numero"].Value) <= 0) { //FARMI INVIARE DA FRONT END CON SIGNALR UN BOOLEAN SE VIDEO ESISTE O NO messaggio = $"Buona visione"; await connection.InvokeAsync("sendVideo", int.Parse(intentRequest.Intent.Slots["numero"].Value)); } else { messaggio = $"Il Video " + int.Parse(intentRequest.Intent.Slots["numero"].Value) + "non è disponibile, quelli che puoi riprodurre sono sul display"; } } else { timer = 0; messaggio = $"Mi spiace non ho video da mostrarti in quest'area. Se vuoi vedere i filmati basta che mi dici :'Alexa, voglio vedere i video'"; } response = ResponseBuilder.Tell(messaggio); //-- response will contain the message that we want send to Alexa response.Response.ShouldEndSession = false; //-- ShouldEndSession is set to false because otherwise alexa will close our skill and user can't continue to interact and have to open again the skill break; case "ShowTireIntent": //RIGUARDARE IN CASO DI TIPOLOGIA GOMMA ERRATA if (GestoreBLL.TireTypeExist(intentRequest.Intent.Slots["TireType"].Value) != true) { var types = GestoreBLL.GetTiresType(); messaggio = "Hey potresti dirmi la tipologia dei pneumatici ? Te ne consiglio alcune : "; if (types.Count >= 1 || types.Count <= 4) { for (int i = 0; i < types.Count; i++) { messaggio += types[i] + " , "; } } else { for (int i = 0; i < 4; i++) { messaggio += types[i] + " , "; } } timer = 0; } else { messaggio = "Hey puoi dirmi che auto hai ? oppure che auto vorresti avere ?"; timer = 6000; ShowTireInvoked = true; videosUtteranceInovked = false; //messaggio = "Visuallizo le ruote per type"; await connection.InvokeAsync("SendTiresByType", GestoreBLL.GetTires(intentRequest.Intent.Slots["TireType"].Value)); } response = ResponseBuilder.Tell(messaggio); //-- response will contain the message that we want send to Alexa response.Response.ShouldEndSession = false; break; case "ShowTireInfoIntent": //RIGUARDARE GESTOREBL E DB if (ShowTireInvoked != false) { if (int.Parse(intentRequest.Intent.Slots["numero"].Value) <= 3 || int.Parse(intentRequest.Intent.Slots["numero"].Value) <= 0) { timer = 1000; messaggio = "In questa schermata puoi vedere tutte le informazioni sul pneumatico scelto. Ah se vuoi posso mostrarti qualche video, basta che mi dici quale vuoi vedere"; ShowTireInfoInvoked = true; ShowTireInvoked = false; videosUtteranceInovked = true; await connection.InvokeAsync("AskIdTire", int.Parse(intentRequest.Intent.Slots["numero"].Value)); } else { messaggio = "Mi spiace il numero del pneumatico che hai richiesto è errato. I numeri disponibili sono riportati sul display"; } //MANCA METODO CHE RESTITUISCE I VIDEO IN BASE ALLA GOMMA SCELTA E SE POSSIBILE ANCHE IN BASE ALL'AUTO. //await connection.InvokeAsync("sendTireAndVideos", GestoreBLL.GetTireById(int.Parse(intentRequest.Intent.Slots["ruote"].Resolution.Authorities[0].Values[0].Value.Id))); //Sending the tire selected to the front-end } else { messaggio = $"Non ho capito mi spiace"; } response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; //-- ShouldEndSession is set to false because otherwise alexa will close our skill and user can't continue to interact and have to open again the skill break; case "CarIntent": //RIGUARDARE GESTOREBL E DB if (ShowTireInvoked != false) { if (intentRequest.Intent.Slots["auto"].Resolution.Authorities[0].Values != null) { /* if (GestoreBLL.CarExists(intentRequest.Intent.Slots["auto"].Value)) * {*/ if (intentRequest.Intent.Slots["auto"].Resolution.Authorities[0].Values.Length > 1) { timer = 0; messaggio = "Potresti dirmi il modello della " + intentRequest.Intent.Slots["auto"].Value; var models = GestoreBLL.GetCarModels(intentRequest.Intent.Slots["auto"].Value); if (models.Count >= 3) { messaggio += " ? Ti consiglio alcuni modelli disponibili : " + models[0] + " ," + models[1] + " ," + models[2] + " ,"; } else { messaggio += " ? Sono disponibili questi due modelli : " + models[0] + " ," + models[1]; } } else { timer = 2000; carUtteranceInvoked = true; messaggio = "Sul display sono mostrate solo le ruote compatibili con la " + intentRequest.Intent.Slots["auto"].Resolution.Authorities[0].Values[0].Value.Name; await connection.InvokeAsync("SendTiresByType", GestoreBLL.GetTiresByCar(int.Parse(intentRequest.Intent.Slots["auto"].Resolution.Authorities[0].Values[0].Value.Id))); } //} } else { timer = 0; var car = GestoreBLL.GetCars(); messaggio = "La " + intentRequest.Intent.Slots["auto"].Value + " non è disponibile. Puoi dirmi il nome di un'altra auto ? Se vuoi puoi scegliere una tra queste : "; if (car.Count >= 3) { for (int i = 0; i < 3; i++) { messaggio += car[i].brand + " " + car[i].invokeName + " ,"; } } else if (car.Count == 2) { for (int i = 0; i < 2; i++) { messaggio += car[i].brand + " " + car[i].invokeName + " ,"; } } else { messaggio = "La " + intentRequest.Intent.Slots["auto"].Value + "non è disponibile. Per il momento è disponibile solo questa auto: " + car[0].brand + " " + car[0].invokeName; } } } else { messaggio = "Mi spiace ma non ho capito che cosa vuoi"; } response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; break; case "ReturnToSlideIntent": if (videosUtteranceInovked != false || ShowTireInvoked != false || ShowTireInfoInvoked != false) //Enter here when we are in other areas (Video gallery, Custom your car) and the user want to return to the slider { messaggio = $"Va bene, ritorno allo slider"; await connection.InvokeAsync("returnToSlide"); videosUtteranceInovked = false; ShowTireInfoInvoked = false; ShowTireInvoked = false; carUtteranceInvoked = false; } else //If user invokes "ReturnToSlideIntent" from the slider area { messaggio = $"Lo slider è gia sul display"; } timer = 0; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; //-- ShouldEndSession is set to false because otherwise alexa will close our skill and user can't continue to interact and have to open again the skill break; case "NextPageIntent": if (videosUtteranceInovked != false || ShowTireInfoInvoked != false) { await connection.InvokeAsync("sendPage", "next"); //messaggio = $"next"; } else { messaggio = $"Operazione non consentita"; } timer = 0; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; break; case "PreviousPageIntent": if (videosUtteranceInovked != false || ShowTireInfoInvoked != false) { await connection.InvokeAsync("sendPage", "previus"); //messaggio = $"previous"; } else { messaggio = $"Operazione non consentita"; } timer = 0; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; break; case "AMAZON.StopIntent": messaggio = $"Ciao, alla prossima"; timer = 0; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = true; //-- ShouldEndSession is set to true because the user want to close the skill await connection.StopAsync(); break; case "ZZZ": //-- Intent created for word that alexa can't undurstand or utterance that are not allowed in this skill ( In english version exist a built-in intent called AMAZON.Fallback for this feature) messaggio = $"Non ho capito, puoi ripetere perfavore ?"; timer = 0; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; break; default: messaggio = $"Non ho capito purtroppo"; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; break; } } else { messaggio = $"Non ho capito"; response = ResponseBuilder.Tell(messaggio); response.Response.ShouldEndSession = false; } System.Threading.Thread.Sleep(timer); return(new OkObjectResult(response)); //Send the response to alexa }
public JsonResult Help() { return(new JsonResult(ResponseBuilder.Ask(Messages.Help, null))); }
private void SendResponse() { // var request = Encoding.Default.GetString(buffer, 0, buffer.Length); // var requestParser = new RequestParser(request); // requestParser.Parse(); // Console.WriteLine(request); var html = "<html><title>Error</title><body>An error has occurred.</body></html>"; var response = new ResponseBuilder() .AddStatusCode("HTTP/1.1 200 OK") .AddHeader<string>("Content-Type", "text/html;charset=utf-8") .AddHeader<int>("Content-Length", html.Length) .AddContent(html) .Build(); var bytes = Encoding.ASCII.GetBytes(response); _networkStream.Write(bytes, 0, bytes.Length); _networkStream.Flush(); }
public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context) { context.Logger.LogLine("Request Type: " + input.GetRequestType().Name); if (input.GetRequestType() == typeof(LaunchRequest)) { SkillResponse response = ResponseBuilder.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, "https://s3-eu-west-1.amazonaws.com/rtg-dispatcher/streaming-test/Dispatcher_Ready_Question.wav", "token"); response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Playing" }; response.Response.ShouldEndSession = false; return(response); } else if (input.GetRequestType() == typeof(IntentRequest)) { IntentRequest request = input.Request as IntentRequest; return(request.Intent.Name == "AMAZON.YesIntent" ? ResponseBuilder.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, "https://s3-eu-west-1.amazonaws.com/rtg-dispatcher/streaming-test/Caller_Birth.wav", "token") : ResponseBuilder.Empty()); } return(ResponseBuilder.Empty()); }
//--- Methods --- public SkillResponse FunctionHandler(SkillRequest skill, ILambdaContext context) { // load adventure from S3 var game = GameLoader.Parse(ReadTextFromS3(_s3Client, _adventureFileBucket, _adventureFilePath)); // restore player object from session GamePlayer player; if (skill.Session.New) { // TODO: can we restore the player from DynamoDB? player = new GamePlayer(Game.StartPlaceId); } else { player = SessionLoader.Deserialize(game, skill.Session); } // decode skill request IEnumerable <AGameResponse> responses; IEnumerable <AGameResponse> reprompt = null; switch (skill.Request) { // skill was activated without an intent case LaunchRequest launch: LambdaLogger.Log($"*** INFO: launch\n"); responses = game.TryDo(player, GameCommandType.Restart); reprompt = game.TryDo(player, GameCommandType.Help); return(ResponseBuilder.Ask( ConvertToSpeech(responses), new Reprompt { OutputSpeech = ConvertToSpeech(reprompt) }, SessionLoader.Serialize(game, player) )); // skill was activated with an intent case IntentRequest intent: // check if the intent is an adventure intent if (Enum.TryParse(intent.Intent.Name, true, out GameCommandType command)) { LambdaLogger.Log($"*** INFO: adventure intent ({intent.Intent.Name})\n"); responses = game.TryDo(player, command); reprompt = game.TryDo(player, GameCommandType.Help); } else { switch (intent.Intent.Name) { // built-in intents case BuiltInIntent.Help: LambdaLogger.Log($"*** INFO: built-in help intent ({intent.Intent.Name})\n"); responses = game.TryDo(player, GameCommandType.Help); reprompt = game.TryDo(player, GameCommandType.Help); break; case BuiltInIntent.Stop: case BuiltInIntent.Cancel: LambdaLogger.Log($"*** INFO: built-in stop/cancel intent ({intent.Intent.Name})\n"); responses = game.TryDo(player, GameCommandType.Quit); break; // unknown & unsupported intents default: LambdaLogger.Log("*** WARNING: intent not recognized\n"); responses = new[] { new GameResponseNotUnderstood() }; reprompt = game.TryDo(player, GameCommandType.Help); break; } } // respond with serialized player state if (reprompt != null) { return(ResponseBuilder.Ask( ConvertToSpeech(responses), new Reprompt { OutputSpeech = ConvertToSpeech(reprompt) }, SessionLoader.Serialize(game, player) )); } return(ResponseBuilder.Tell(ConvertToSpeech(responses))); // skill session ended (no response expected) case SessionEndedRequest ended: LambdaLogger.Log("*** INFO: session ended\n"); return(ResponseBuilder.Empty()); // exception reported on previous response (no response expected) case SystemExceptionRequest error: LambdaLogger.Log("*** INFO: system exception\n"); LambdaLogger.Log($"*** EXCEPTION: skill request: {JsonConvert.SerializeObject(skill)}\n"); return(ResponseBuilder.Empty()); // unknown skill received (no response expected) default: LambdaLogger.Log($"*** WARNING: unrecognized skill request: {JsonConvert.SerializeObject(skill)}\n"); return(ResponseBuilder.Empty()); } }
/// <summary> /// The writeSuccess. /// </summary> /// <param name="content_type">The content_type<see cref="string"/>.</param> private void writeSuccess(string content_type = "text/html") { ResponseBuilder.AppendLine("HTTP/1.1 200 OK"); ResponseBuilder.AppendLine("Content-Type: " + content_type); }
internal SkillResponse SessionEnded(AudioSessionAttributes attributes) => ResponseBuilder.Empty();
public static SkillResponse NoEvent(bool dateRange = false) { var rangeText = dateRange ? "at that time" : "at the moment"; return(ResponseBuilder.Tell("I'm afraid I've no events for the meetup " + rangeText + ". If it's just been announced we may take a little while to update.")); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { string json = await req.ReadAsStringAsync(); var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json); //this is the language used to invoke the skill string language = skillRequest.Request.Locale; bool isValid = await ValidateRequest(req, log, skillRequest); if (!isValid) { return(new BadRequestResult()); } var requestType = skillRequest.GetRequestType(); SkillResponse response = null; if (requestType == typeof(LaunchRequest)) { response = ResponseBuilder.Ask("Hi Carlos! Thanks for the invite! Glad to help you with your session today!", new Reprompt()); } else if (requestType == typeof(IntentRequest)) { var intentRequest = skillRequest.Request as IntentRequest; if (intentRequest.Intent.Name == "namespaces") { var endpoint = $"{k8sServiceUri}/api/pods/namespaces"; var k8sresponse = await restClient.GetAsync(endpoint); if (k8sresponse.IsSuccessStatusCode) { var namespaces = await k8sresponse.Content.ReadAsAsync <string[]>(); var message = string.Join(",", namespaces); response = ResponseBuilder.Tell($"Found the following namespaces: {message}"); } } if (intentRequest.Intent.Name == "pods") { var endpoint = $"{k8sServiceUri}/api/pods"; var k8sresponse = await restClient.GetAsync(endpoint); if (k8sresponse.IsSuccessStatusCode) { var pods = await k8sresponse.Content.ReadAsAsync <string[]>(); var message = string.Join(",", pods); response = ResponseBuilder.Tell($"Found the following pods in the invaders namespace: {message}"); } } if (intentRequest.Intent.Name == "scale") { var endpoint = $"{k8sServiceUri}/api/pods/scale"; var replicas = intentRequest.Intent.Slots["replicas"].Value; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Patch, endpoint) { Content = new StringContent(replicas, Encoding.UTF8, "application/json") }; var k8sresponse = await restClient.SendAsync(request); if (k8sresponse.IsSuccessStatusCode) { response = ResponseBuilder.Tell($"Deployment scaled to {replicas} invaders"); } } else if (intentRequest.Intent.Name == "AMAZON.CancelIntent") { response = ResponseBuilder.Tell("I'm cancelling the request..."); } else if (intentRequest.Intent.Name == "AMAZON.HelpIntent") { response = ResponseBuilder.Tell("Sorry due you are on your own."); response.Response.ShouldEndSession = false; } else if (intentRequest.Intent.Name == "AMAZON.StopIntent") { response = ResponseBuilder.Tell("bye"); } } else if (requestType == typeof(SessionEndedRequest)) { log.LogInformation("Session ended"); response = ResponseBuilder.Empty(); response.Response.ShouldEndSession = true; } return(new OkObjectResult(response)); }
public JsonResult Welcome() { return(new JsonResult(ResponseBuilder.Ask(Messages.Welcome, null))); }
public JsonResult Exit() { return(new JsonResult(ResponseBuilder.Tell("Be sure to come back for updates from Suave Pirate!", null))); }
/// <summary> /// The writeDenied. /// </summary> private void writeDenied() { ResponseBuilder.AppendLine("HTTP/1.1 401.7 Access denied"); }
public async Task <IActionResult> GetStudentNumberAsync(int id) { int number = await _schoolsRepository.GetStudentNumberAsync(id); return(Ok(ResponseBuilder.AddData(new { number }).Build())); }
/// <summary> /// The writeFailure. /// </summary> private void writeFailure() { ResponseBuilder.AppendLine("HTTP/1.1 404 File not found"); }
public async Task ThenItShouldReturnLearnersFromServer() { var learner = new Learner { Ukprn = 12345678, LearnRefNumber = "ABC123", Uln = 9010000000, FamilyName = "User", GivenNames = "Test", DateOfBirth = DateTime.Today, NiNumber = "AB123456A", LearningDeliveries = new[] { new LearningDelivery { AimType = 99, LearnStartDate = DateTime.Today.AddDays(-10), LearnPlanEndDate = DateTime.Today.AddDays(-1), FundModel = 23, StdCode = 9658, DelLocPostCode = "AB12 3LK", EpaOrgId = "KSM63", CompStatus = 81, LearnActEndDate = DateTime.Today.AddDays(-2), WithdrawReason = 25, Outcome = 851, AchDate = DateTime.Today.AddDays(-63), OutGrade = "pass", ProgType = 54, }, }, }; _httpClientMock.SetDefaultResponse( ResponseBuilder.Json(new[] { learner }, new SystemTextMtwJsonSerializer())); var actual = await _apiClient.ListLearnersForProviderAsync("2021", 12345678, 1, CancellationToken.None); Assert.IsNotNull(actual); Assert.IsNotNull(actual.Items); Assert.AreEqual(1, actual.Items.Length); Assert.AreEqual(learner.Ukprn, actual.Items[0].Ukprn); Assert.AreEqual(learner.LearnRefNumber, actual.Items[0].LearnRefNumber); Assert.AreEqual(learner.Uln, actual.Items[0].Uln); Assert.AreEqual(learner.FamilyName, actual.Items[0].FamilyName); Assert.AreEqual(learner.GivenNames, actual.Items[0].GivenNames); Assert.AreEqual(learner.DateOfBirth, actual.Items[0].DateOfBirth); Assert.AreEqual(learner.NiNumber, actual.Items[0].NiNumber); Assert.IsNotNull(actual.Items[0].LearningDeliveries); Assert.AreEqual(1, actual.Items[0].LearningDeliveries.Length); Assert.AreEqual(learner.LearningDeliveries[0].AimType, actual.Items[0].LearningDeliveries[0].AimType); Assert.AreEqual(learner.LearningDeliveries[0].LearnStartDate, actual.Items[0].LearningDeliveries[0].LearnStartDate); Assert.AreEqual(learner.LearningDeliveries[0].LearnPlanEndDate, actual.Items[0].LearningDeliveries[0].LearnPlanEndDate); Assert.AreEqual(learner.LearningDeliveries[0].FundModel, actual.Items[0].LearningDeliveries[0].FundModel); Assert.AreEqual(learner.LearningDeliveries[0].StdCode, actual.Items[0].LearningDeliveries[0].StdCode); Assert.AreEqual(learner.LearningDeliveries[0].DelLocPostCode, actual.Items[0].LearningDeliveries[0].DelLocPostCode); Assert.AreEqual(learner.LearningDeliveries[0].EpaOrgId, actual.Items[0].LearningDeliveries[0].EpaOrgId); Assert.AreEqual(learner.LearningDeliveries[0].CompStatus, actual.Items[0].LearningDeliveries[0].CompStatus); Assert.AreEqual(learner.LearningDeliveries[0].LearnActEndDate, actual.Items[0].LearningDeliveries[0].LearnActEndDate); Assert.AreEqual(learner.LearningDeliveries[0].WithdrawReason, actual.Items[0].LearningDeliveries[0].WithdrawReason); Assert.AreEqual(learner.LearningDeliveries[0].Outcome, actual.Items[0].LearningDeliveries[0].Outcome); Assert.AreEqual(learner.LearningDeliveries[0].AchDate, actual.Items[0].LearningDeliveries[0].AchDate); Assert.AreEqual(learner.LearningDeliveries[0].OutGrade, actual.Items[0].LearningDeliveries[0].OutGrade); Assert.AreEqual(learner.LearningDeliveries[0].ProgType, actual.Items[0].LearningDeliveries[0].ProgType); }
/// <summary> /// The HandleDeniedRequest. /// </summary> public void HandleDeniedRequest() { writeDenied(); writeClose(); binSend = ResponseBuilder.ToString().ToBytes(CharEncoding.UTF8); }
public async Task <SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context) { // Skill currently only in German so set culture statical CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); skillRequest = input; progResponse = new ProgressiveResponse(skillRequest); this.context = context; settingsClient = new SettingsClient(input); session = input.Session; if (session.Attributes == null) { session.Attributes = new Dictionary <string, object>(); } if (input.Request is LaunchRequest) { return(ResponseBuilder.AskWithCard( Properties.Speech.Starter, Properties.Speech.StarterTitle, Properties.Speech.StarterContent, null, session )); } else if (input.Request is IntentRequest intentRequest) { var intent = intentRequest.Intent; context.Logger.LogLine($"IntentRequest {intent.Name}, Attributes: {string.Join(";", input.Session?.Attributes.Select(kp => $"{kp.Key}: {kp.Value}"))}"); context.Logger.LogLine($"Slots {string.Join(";", intent.Slots.Select(s => $"{s.Key}: {s.Value.Value}"))}"); if (intent.Name == Properties.Resources.TripSearchIntentName) { if (GetCounter(completeFailCounter) >= 2) { return(ResponseBuilder.Tell( Properties.Speech.CompleteFail )); } var sourceSlot = intent.Slots[Properties.Resources.TripSearchSrcSlotName]; var destintationSlot = intent.Slots[Properties.Resources.TripSearchDstSlotName]; var source = sourceSlot.Value; IEnumerable <Destination> foundSources = null; if (string.IsNullOrWhiteSpace(source)) { if (input.Context.Geolocation == null) { return(ResponseBuilder.TellWithAskForPermissionConsentCard( Properties.Speech.RequestGeoLocation, new[] { geoLocationPermission }.AsEnumerable(), session )); } else { var coords = input.Context.Geolocation.Coordinate; context.Logger.LogLine($"Geo lat: {coords.Latitude}, lon: {coords.Longitude}"); foundSources = await searcher.FindDestinationByGeo( coords.Latitude, coords.Longitude ); } } else { await progResponse.SendSpeech( string.Format(Properties.Speech.SearchingForDestinations, source) ); foundSources = await searcher.FindDestinationByName(source); } var destination = destintationSlot.Value; await progResponse.SendSpeech( string.Format(Properties.Speech.SearchingForDestinations, destination) ); var foundDestinations = await searcher.FindDestinationByName(destination); if (foundSources.Count() != 1 && foundDestinations.Count() != 1) { IncreaseCounter(completeFailCounter); return(ResponseBuilder.AskWithCard( string.Format(Properties.Speech.SourceAndDestinationNotFound, source, destination), Properties.Speech.SourceAndDestinationNotFoundTitle, string.Format("Die Orte {0} und {1} kenne ich nicht. Versuche es bitte noch einmal von vorne.", source, destination), null, session )); } else if (foundSources.Count() != 1) { input.Session.Attributes["destinationDst"] = foundDestinations.First(); if (string.IsNullOrWhiteSpace(source)) { return(ResponseBuilder.AskWithCard( string.Format(Properties.Speech.SourceGeoNotFound), Properties.Speech.SourceNotFoundTitle, "Den Startort konnte ich lieder nicht ermitteln. Versuche es vielleicht diesen explizit zu nennen.", null, session )); } else { return(ResponseBuilder.AskWithCard( string.Format(Properties.Speech.SourceNotFound, source, foundSources.First().Name), Properties.Speech.SourceNotFoundTitle, string.Format("Den Startort {0} kenne ich lieder nicht. Versuche es mit: Der Ort ist {1}.", source, foundSources.First().Name), null, session )); } } else if (foundDestinations.Count() != 1) { input.Session.Attributes["sourceDst"] = foundSources.First(); return(ResponseBuilder.AskWithCard( string.Format(Properties.Speech.DestinationNotFound, destination, foundDestinations.First().Name), Properties.Speech.DestinationNotFoundTitle, string.Format("Den Zielort {0} kenne ich leider nicht. Versuche es mit: Der Ort ist {1}.", destination, foundDestinations.First().Name), null, session )); } var time = DateTime.Now; return(await SearchForTrips(foundSources.First(), foundDestinations.First())); } else if (intent.Name == Properties.Resources.SpecifyLocationIntentName) { if (GetCounter(locationFailCounter) >= 2) { return(ResponseBuilder.Tell( Properties.Speech.LocationFail )); } var source = GetAttributeAs <Destination>("sourceDst"); var destination = GetAttributeAs <Destination>("destinationDst"); if (source == null && destination == null) { return(ResponseBuilder.Ask( Properties.Speech.WrongOrderSpecLoc, null )); } var locationSlot = intent.Slots[Properties.Resources.SpecifyLocationLocSlotName];; var location = locationSlot.Value; await progResponse.SendSpeech( string.Format(Properties.Speech.SearchingForDestinations, location) ); var foundLocations = await searcher.FindDestinationByName(location); if (foundLocations.Count() != 1) { IncreaseCounter(locationFailCounter); return(ResponseBuilder.AskWithCard( string.Format(Properties.Speech.DestinationNotFound, location, foundLocations.First().Name), source == null ? Properties.Speech.SourceNotFoundTitle : Properties.Speech.DestinationNotFoundTitle, string.Format("Den {0} {1} kenne ich leider nicht. Versuche es mit: Der Ort ist {2}.", source == null ? "Startort" : "Zielort", location, foundLocations.First().Name), null, session )); } else { if (source == null) { source = foundLocations.First(); } if (destination == null) { destination = foundLocations.First(); } var time = DateTime.Now; return(await SearchForTrips(source, destination)); } } else { // TODO Better response for unknown intent return(ResponseBuilder.Tell(Properties.Speech.InvalidRequest)); } } else { return(ResponseBuilder.Tell(Properties.Speech.InvalidRequest)); } }
public async Task <dynamic> Post([FromBody] SkillRequest input) { var speech = new Alexa.NET.Response.SsmlOutputSpeech(); var finalResponse = new SkillResponse(); finalResponse.Version = "1.0"; // check what type of a request it is like an IntentRequest or a LaunchRequest var requestType = input.GetRequestType(); if (requestType == typeof(IntentRequest)) { // do some intent-based stuff var intentRequest = input.Request as IntentRequest; // check the name to determine what you should do if (intentRequest.Intent.Name.Equals("GetPoints")) { try { long?points = 0; var client = new CustomApiClient(); var result = await client.QueryPointsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, "WALLET_DEFAULT", null, null, false, null, null, null); if (result != null) { foreach (var wallet in result.Wallets) { points = points + wallet.Points; } } //// create the speech response - cards still need a voice response //speech.Ssml = $"<speak>You currently have {points} loyalty points available in your account.</speak>"; //// create the card response //finalResponse = ResponseBuilder.TellWithCard(speech, "GetPoints", $"You currently have {points} loyalty points available in your account."); //_cache.sa // create the speech response - cards still need a voice response speech.Ssml = $"<speak>You currently have {points} loyalty points available in your account.</speak>"; // create the speech reprompt var repromptMessage = new PlainTextOutputSpeech(); repromptMessage.Text = "Anything else you might want to do?"; // create the reprompt var repromptBody = new Alexa.NET.Response.Reprompt(); repromptBody.OutputSpeech = repromptMessage; // create the response finalResponse = ResponseBuilder.AskWithCard(speech, "GetPoints", $"You currently have {points} loyalty points available in your account.", repromptBody); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "GetPoints Exception", $"Oh boy, something went very wrong. {e.Message}."); } } // check the name to determine what you should do if (intentRequest.Intent.Name.Equals("GetItems")) { try { string items = string.Empty; SessionData sessionData = null; var client = new CustomApiClient(); var result = await client.QueryAvailableItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, null, null, null, null); if (result != null) { //items = string.Join(", ", result.Items.Select(z => z.Name)); redeemableItems.AddRange(result.Items); items = string.Join(", ", redeemableItems.Select(z => z.Name)); var value = await _cache.GetStringAsync(input.Session.SessionId); if (value != null) { sessionData = JsonConvert.DeserializeObject <SessionData>(value); } if (sessionData != null) { sessionData.RedeemableItems = redeemableItems; } else { sessionData = new SessionData { SessionId = input.Session.SessionId, PurchaseItems = purchaseItems, RedeemableItems = redeemableItems }; } await _cache.SetStringAsync(input.Session.SessionId, JsonConvert.SerializeObject(sessionData)); } // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Here is the list of items available for you: {items}.</speak>"; // create the card response //finalResponse = ResponseBuilder.TellWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}."); // create the speech reprompt var repromptMessage = new PlainTextOutputSpeech(); repromptMessage.Text = "Would you like to add any of these to your shoping cart?"; // create the reprompt var repromptBody = new Alexa.NET.Response.Reprompt(); repromptBody.OutputSpeech = repromptMessage; // create the response finalResponse = ResponseBuilder.AskWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}.", repromptBody); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "GetItems Exception", $"Oh boy, something went very wrong. {e.Message}."); } } // check the name to determine what you should do if (intentRequest.Intent.Name.Equals("AddToBasket")) { try { SessionData sessionData = null; RedeemableItem itemR = null; PurchaseOrderItem itemP = null; string itemName = string.Empty; int itemNo = int.Parse(intentRequest.Intent.Slots["Item"].Value); var value = await _cache.GetStringAsync(input.Session.SessionId); if (value != null) { sessionData = JsonConvert.DeserializeObject <SessionData>(value); } if (sessionData != null) { if (sessionData.RedeemableItems != null && sessionData.RedeemableItems.Count > 0) { redeemableItems = sessionData.RedeemableItems; if ((itemNo - 1) > sessionData.RedeemableItems.Count || (itemNo - 1) < 0) { throw new Exception("Sorry, you don't have that item."); } itemR = redeemableItems[itemNo - 1]; if (sessionData.PurchaseItems != null) { purchaseItems = sessionData.PurchaseItems; purchaseItems.Add(new PurchaseOrderItem { DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = new WalletType { ExternalCode = "WALLET_DEFAULT" } }); } //else //{ // purchaseItems.Add(new PurchaseOrderItem { DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = null }); //} } else { throw new Exception("Please query for your ityems first."); } } else { sessionData = new SessionData { SessionId = input.Session.SessionId, PurchaseItems = purchaseItems, RedeemableItems = redeemableItems }; } await _cache.SetStringAsync(input.Session.SessionId, JsonConvert.SerializeObject(sessionData)); purchaseItems.Add(new PurchaseOrderItem { DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = null }); // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Your item, {itemR.Name}, was successfully added to shopping cart.</speak>"; // create the speech reprompt var repromptMessage = new PlainTextOutputSpeech(); repromptMessage.Text = "Shall I proceed and buy the items in the shoping cart? You can add more items as well."; // create the reprompt var repromptBody = new Alexa.NET.Response.Reprompt(); repromptBody.OutputSpeech = repromptMessage; // create the response finalResponse = ResponseBuilder.AskWithCard(speech, "AddToBasket", $"Your item, {itemR.Name}, was successfully added to shopping cart.", repromptBody); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "AddToBasket Exception", $"Oh boy, something went very wrong. {e.Message}."); } } // check the name to determine what you should do if (intentRequest.Intent.Name.Equals("PurchaseBasket")) { try { SessionData sessionData = null; string status = string.Empty; var value = await _cache.GetStringAsync(input.Session.SessionId); if (value != null) { sessionData = JsonConvert.DeserializeObject <SessionData>(value); } if (sessionData != null && sessionData.PurchaseItems != null && sessionData.PurchaseItems.Count > 0) { purchaseItems = sessionData.PurchaseItems; } else { throw new Exception("Your shoping cart is empty. Add some items first."); } await _cache.RemoveAsync(input.Session.SessionId); var client = new CustomApiClient(); // var result = await client.RedeemItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, purchaseItems.ToArray(), null, null, null); var result = await client.RedeemItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, purchaseItems.ToArray(), null, null, null); if (result != null) { status = result.Status.ToString(); } // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Your order completed with {status}. Thank you for using our services.</speak>"; // create the response finalResponse = ResponseBuilder.TellWithCard(speech, "PurchaseBasket", $"Your order completed with {status}. Thank you for using our services."); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "PurchaseBasket Exception", $"Oh boy, something went very wrong. {e.Message}."); } } if (intentRequest.Intent.Name.Equals("AMAZON.CancelIntent")) { try { await _cache.RemoveAsync(input.Session.SessionId); List <string> myList = new List <string> { "OK,I'll shut up.", "Sure, I'll cleanup everything.", "Oh boy, that escalated quickly! I'm outa here!" }; // add items to the list Random r = new Random(); int index = r.Next(myList.Count); // create the speech response - cards still need a voice response speech.Ssml = $"<speak>{myList[index]}</speak>"; // create the response finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"{myList[index]}"); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"Oh boy, something went very wrong. {e.Message}."); } } if (intentRequest.Intent.Name.Equals("Hello")) { try { await _cache.RemoveAsync(input.Session.SessionId); List <string> myList = new List <string> { "Hi there!", "Hi, how are you.", "Hi and goodby. get back to work" }; // add items to the list Random r = new Random(); int index = r.Next(myList.Count); // create the speech response - cards still need a voice response speech.Ssml = $"<speak>{myList[index]}</speak>"; // create the response finalResponse = ResponseBuilder.TellWithCard(speech, "Hello", $"{myList[index]}"); } catch (Exception e) { // create the speech response - cards still need a voice response speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>"; // create the card response finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"Oh boy, something went very wrong. {e.Message}."); } } } else if (requestType == typeof(Alexa.NET.Request.Type.LaunchRequest)) { // default launch path executed } else if (requestType == typeof(AudioPlayerRequest)) { // do some audio response stuff } return(finalResponse); }
private async Task <GetOverviewInput> SelectCinema(SkillRequest skillRequest, GetOverviewInput input, KinoheldUser user) { var request = (IntentRequest)skillRequest.Request; var cinemaPreferenceForCity = user?.CityCinemaAssignments.FirstOrDefault(p => p.City == input.SelectedCity); if (cinemaPreferenceForCity != null) { m_logger.LogDebug("Taking cinema from the preferences"); input.SelectedCinema = JsonHelper.Deserialize <Cinema>(cinemaPreferenceForCity.Cinema); return(input); } var cinemaSelection = request.Intent.GetSlot(Slots.CinemaSelection); if (string.IsNullOrEmpty(cinemaSelection) || !int.TryParse(cinemaSelection, out var cinemaSelectionInt)) { m_logger.LogDebug("Getting cinemas near the selected city to choose from"); var kinos = await m_kinoheldService.GetCinemas(input.SelectedCity).ConfigureAwait(false); if (!kinos.Any()) { input.PendingResponse = ResponseBuilder.Tell(string.Format(m_messages.ErrorNoCinemaInCity, input.SelectedCity)); return(input); } if (kinos.Count == 1) { input.SelectedCinema = kinos.First(); return(input); } input.PendingResponse = GetResponseCinemaSelection(input, kinos); return(input); } if (!skillRequest.Session.Attributes.ContainsKey(Constants.Session.Cinemas)) { input.PendingResponse = ResponseBuilder.Tell(string.Format(m_messages.ErrorMissingSessionCinemaObject, Constants.Session.Cinemas)); } m_logger.LogDebug("Getting cinemas from session data"); var jsonCinemas = JArray.Parse(skillRequest.Session.Attributes[Constants.Session.Cinemas].ToString()); var cinemas = jsonCinemas.ToObject <IEnumerable <Cinema> >().ToList(); if (cinemas.Count < cinemaSelectionInt) { input.PendingResponse = GetResponseCinemaSelection(input, cinemas); return(input); } m_logger.LogDebug("Taking the chosen cinema from the list"); input.SelectedCinema = cinemas[cinemaSelectionInt - 1]; var savePreference = request.Intent.GetSlot(Slots.SaveCinemaToPreferences); if (string.IsNullOrEmpty(savePreference)) { m_logger.LogDebug("Asking user if he wishes to save the cinema selection for upcoming requests"); input.PendingResponse = GetResponseCinemaSaveToPreference(input, skillRequest.Session); return(input); } if (savePreference.Equals("Ja", StringComparison.OrdinalIgnoreCase)) { m_logger.LogDebug("Saving cinema selection for future requests"); var cinemaData = JsonHelper.Serialize(input.SelectedCinema); await m_dbAccess.SaveCityCinemaPreferenceAsync(skillRequest.Session.User.UserId, input.SelectedCity, cinemaData).ConfigureAwait(false); } return(input); }
private void SendReponseError() { const string ErrorText = "<html><title>Error</title><body>An error has occurred.</body></html>"; var response = new ResponseBuilder() .AddStatusCode("HTTP/1.1 200 OK") .AddHeader<string>("Content-Type", "text/html;charset=utf-8") .AddHeader<int>("Content-Length", ErrorText.Length) .AddContent(ErrorText) .Build(); var bytes = Encoding.ASCII.GetBytes(response); _networkStream.Write(bytes, 0, bytes.Length); _networkStream.Flush(); }
/// <summary> /// Add the expected response object for an HTTP Status Code /// </summary> /// <param name="httpStatusCode"> /// The http status code. /// </param> /// <param name="response"> /// The response. /// </param> /// <returns> /// The <see cref="OperationBuilder"/>. /// </returns> public OperationBuilder Response(string httpStatusCode, Action<ResponseBuilder> response) { if (this.responses == null) { this.responses = new Dictionary<string, Response>(); } var builder = new ResponseBuilder(); response(builder); this.responses.Add(httpStatusCode, builder.Build()); return this; }
public void ShouldCreateARequestWithHttpUrlScheme() { var pairs = HoverflyDsl.Service("http://www.my-test.com").Get("/").WillReturn(ResponseBuilder.Response()).RequestResponsePairs; Assert.Equal(1, pairs.Count); var pair = pairs.First(); Assert.Equal("www.my-test.com", pair.Request.Destination.ExactMatch); Assert.Equal("http", pair.Request.Scheme.ExactMatch); }
public JsonResult BlogPosts(List <BlogPost> posts) { var output = HttpUtility.HtmlDecode($"Here are the latest posts: {string.Join(", ", posts.Take(4).Select(p => p.Title).ToList())} - be sure to check back regularly for new content from Alex!"); return(new JsonResult(ResponseBuilder.Tell(output, null))); }
public void ShouldCreateDeleteRequest() { var pairs = HoverflyDsl.Service("www.my-test.com").Delete("/").WillReturn(ResponseBuilder.Response()).RequestResponsePairs; Assert.Equal(1, pairs.Count); var pair = pairs.First(); Assert.Equal("DELETE", pair.Request.Method.ExactMatch); }
public override SkillResponse HandleSyncRequest(AlexaRequestInformation <APLSkillRequest> information) { return(ResponseBuilder.Tell(string.Empty)); }