public async Task Then_repository_update_print_status_is_called_for_delivered() { // Act _response = await _sut.Handle(_certificatePrintStatusUpdateRequestDelivered, new CancellationToken()); // Assert _certificateRepository.Verify(r => r.UpdatePrintStatus( It.Is <Certificate>(c => c.CertificateReference == _certificateReference2), _batch222, CertificateStatus.Delivered, _statusAt, string.Empty, true), Times.Once()); }
private IActionResult handleValidationTokenResponse(ValidationResponse response) { return(response.Status switch { ValidationStatus.Success => Ok(response), ValidationStatus.Unauthorized => Unauthorized(response), ValidationStatus.UnexepectedError => StatusCode(500, response), ValidationStatus.ValidationFailed => BadRequest(response), _ => StatusCode(500, response) });
public static ValidationResponse GetFake_ValidationFailed() { var validationErrorResponseList = new List <ValidationErrorResponse> { new ValidationErrorResponse("Code", "FieldName", "Validation description") }; var validationResponse = new ValidationResponse(nameof(Message.ValidationFailed), 422, Message.ValidationFailed, validationErrorResponseList); return(validationResponse); }
public void GetOrganisationDetailsWhenOrganisationUpdated() { var validationResponse = new ValidationResponse(); _validator.Setup(x => x.ValidatorUpdateEpaOrganisationRequest(It.IsAny <UpdateEpaOrganisationRequest>())) .Returns(validationResponse); _returnedOrganisationId = _updateEpaOrganisationHandler.Handle(_requestNoIssues, new CancellationToken()).Result; _returnedOrganisationId.Should().BeEquivalentTo(_expectedOrganisationNoIssues.OrganisationId); }
public ValidationResponse CheckSkuBundleStockLevel(long skuBundleId, int requiredQuantity) { if (skuBundleId > 0) { throw new NotSupportedException("Mertex does not support sku bundles."); } var vr = new ValidationResponse(); return(vr); }
public IActionResult GetPairing([FromQuery] ValidationResponse validationResponse) { // SaveCallbackLog(validationResponse); //await _context.SaveChangesAsync(); //if (validationResponse.Receipt.TxnName.Equals(TransactionType.purchase.ToString(), StringComparison.InvariantCultureIgnoreCase)) { // UpdateOrderAuthCode(validationResponse); //} // return Ok(validationResponse); return(Ok()); }
public ValidationResponse Validate(IValidator validator, IBaseDto dto) { var result = validator.Validate(dto); var response = new ValidationResponse { IsValid = result.IsValid }; result.Errors.ToList().ForEach(x => response.Errors.Add(x.ErrorMessage)); return(response); }
/// <summary> /// Validate when the the user is trying to add a square /// </summary> /// <param name="shape">String with all the shape information</param> /// <returns>Return all the information required to the other process</returns> public ValidationResponse SquareValidation(string shape) { var response = new ValidationResponse(); string[] square = shape.Split(); if (square[0] == null || !square[0].ToLower().Equals("square")) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid format. Format should be: square X Y length"; return(response); } try { var x = Convert.ToDouble(square[1]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the X axis"; return(response); } try { var y = Convert.ToDouble(square[2]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the Y axis"; return(response); } double length = 0.0; try { length = Convert.ToDouble(square[3]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the lenght of side"; return(response); } var shapeDto = new shapeDto() { name = square[0], coordinates = square[1] + " " + square[2] + " " + square[3] }; response.ShapeDto = shapeDto; response.Area = (length * length); response.ShapeArray = square; return(response); }
/// <summary> /// Validate when the the user is trying to add a circle /// </summary> /// <param name="shape">String with all the shape information</param> /// <returns>Return all the information required to the other process</returns> public ValidationResponse CircleValidation(string shape) { var response = new ValidationResponse(); string[] circle = shape.Split(); if (circle[0] == null || !circle[0].ToLower().Equals("circle")) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid format. Format should be: circle X Y Radius "; return(response); } try { var x = Convert.ToDouble(circle[1]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the X axis"; return(response); } try { var y = Convert.ToDouble(circle[2]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the Y axis"; return(response); } double radius = 0.0; try { radius = Convert.ToDouble(circle[3]); } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid value for the radius"; return(response); } var shapeDto = new shapeDto() { name = circle[0], coordinates = circle[1] + " " + circle[2] + " " + circle[3] }; response.ShapeDto = shapeDto; response.Area = Math.PI * (radius * radius); response.ShapeArray = circle; return(response); }
public IActionResult Delete(Guid id) { ValidationResponse<Product> validationResponse = _productService.Delete(id); if (validationResponse.Status == ValidationStatus.NotFound) { return NotFound(validationResponse.Message); } return Ok(validationResponse.Message); }
public IActionResult Delete(Guid id) { ValidationResponse <User> validationResponse = _userService.Delete(id); if (validationResponse.Status == ValidationStatus.NotFound) { return(NotFound(validationResponse.Message)); } return(Ok(validationResponse.Message)); }
public bool camposNotN() { ValidationResponse _validationResponse = checkCampos(); if (!_validationResponse._successful) { MessageBox.Show("El campo \"" + _validationResponse._element + "\" No puede estar vacio"); return(false); } return(true); }
public virtual ValidationResponse UpdateCourse(Course course) { ValidationResponse <Course> response = ValidateCourse(course); if (response.HasErrors) { return(response); } _courseRepository.Update(course); return(new ValidationResponse()); }
public IActionResult ValidateFiles(IEnumerable <IFormFile> postedFiles) { string postedFilesDirectory = HostingHelper.PostedFilesDirectory; // The ValidationUi Index view enforces a limit of one file at a time. IFormFile postedFile = postedFiles.FirstOrDefault(); ValidationResponse response = _validationUiService.ValidateFile(postedFile, postedFilesDirectory); return(Json(response)); }
public void GetOrganisationDetailsRepoIsCalledWhenHandlerInvoked() { var validationResponse = new ValidationResponse(); _validator.Setup(x => x.ValidatorUpdateEpaOrganisationRequest(It.IsAny <UpdateEpaOrganisationRequest>())) .Returns(validationResponse); var res = _updateEpaOrganisationHandler.Handle(_requestNoIssues, new CancellationToken()).Result; _registerRepository.Verify(r => r.UpdateEpaOrganisation(It.IsAny <EpaOrganisation>())); }
public void OnValidationResponse(ValidationResponse response) { if (response.accepted) { info.IsHost = response.isHost; info.Connection.State = (int)ClientConnectionState.Validated; } else { StopClient(); } }
public MessageSessionResponse Update(string language, string sessionId, UserRequest request) { AppUser admin = this.LoadUserWithSessionId(sessionId); ValidateSessionAndRight(language, admin, EnumData.AppModules.AppUser.ToString(), new List <string> { EnumData.RoleRight.all.ToString(), EnumData.RoleRight.account.ToString() }); ValidationResponse validationResponse = Validat <UserRequest>(_userValidator, request, language); if (validationResponse != null) { throw new MessagesException(validationResponse.Messages); } if (_work.EmailIsExist(request.Email)) { throw new TranslationException(_translator, language, ConstentMessages.EmailIsExist, null); } if (_work.UserNameIsExist(request.UserName)) { throw new TranslationException(_translator, language, ConstentMessages.UserNameIsExist, null); } string errorMessageKey = ""; try { errorMessageKey = ConstentMessages.ServerError; AppUser appUser = _work.LoadUserWithId(request.Id); if (appUser == null) { throw new TranslationException(_translator, language, ConstentMessages.UserNotExist, null); } UpdateUserFromUserRequest(appUser, request); if (request.UpdateTs != appUser.UpdateTs.ToJsTime()) { throw new TranslationException(_translator, language, ConstentMessages.UserIsChanged, null); } _work.UpdateAppUser(appUser); this.UpdateAdminSession(admin); return(new MessageSessionResponse { Message = "OK", SessionId = admin.Session.Id, SessionUpdateTs = admin.Session.UpdateTs.ToJsTime() }); } catch (TranslationException ex) { throw; } catch (Exception ex) { throw new TranslationException(_translator, language, errorMessageKey, ex); } }
public virtual ValidationResponse UpdateStudent(Student student) { ValidationResponse <Student> response = ValidateStudent(student); if (response.HasErrors) { return(response); } _studentRepository.Update(student); return(new ValidationResponse()); }
protected ValidationResponse ValidateSession(AppUser user, string language) { if (user == null || (DateTime.UtcNow - user.Session.UpdateTs).TotalSeconds > _appSetting.SessionDuration) { ValidationResponse response = new ValidationResponse { SessionInvalid = true }; response.Messages.Add(_translator[language, ConstentMessages.SessionIdIsInvalid]); return(response); } return(null); }
public async Task Arrange() { base.BaseArrange(); _response = await _sut.Handle(new CertificatePrintStatusUpdateRequest { BatchNumber = _batch111 + 999, CertificateReference = _certificateReference1, Status = CertificateStatus.Delivered, StatusAt = DateTime.UtcNow }, new CancellationToken()); }
public IActionResult Post4() { var errors = new[] { new ValidationError("required", new[] { "value" }, new Dictionary <string, object> { { "length", 3 } }) }; var response = new ValidationResponse("Validation", errors); return(BadRequest(response)); }
/// <summary> /// Verfiy an email address. /// </summary> public ValidationResponse <ValidatedEmailAddress> VerifyEmail(EmailAddress emailAddress) { var toReturn = new ValidationResponse <ValidatedEmailAddress> { IsValid = EmailObj.VerifyEmail(emailAddress.Address), StatusCodes = EmailObj.GetParsedResultCodes(), Data = GetEmailAddress(), BuildInfo = Version }; return(toReturn); }
public IActionResult GetById(Guid id) { ValidationResponse <Category> validationResponse = _categoryService.GetById(id); if (validationResponse.Status == ValidationStatus.NotFound) { return(NotFound(validationResponse.Message)); } CategoryResponseModel categoryResponse = _mapper.Map <Category, CategoryResponseModel>(validationResponse.ResponseData); return(Ok(categoryResponse)); }
public void CreateStudent_ReturnsValidationError_WhenNullPassed() { //Arrange StudentService studentService = new StudentService(null, null); //Act var result = studentService.CreateStudent(null); //Assert ValidationResponse <Student> expected = new ValidationResponse <Student>("student", "Student cannot be null"); expected.Should().BeEquivalentTo(result); }
public void CreateFailureMultipleErrors(int errorCount) { string[] errors = new string[errorCount]; for (int i = 0; i < errors.Length; i++) { errors[i] = $"error{i + 1}"; } var result = ValidationResponse <int> .CreateFailure(errors); Assert.AreEqual(false, result.IsValid, "Creating a failure delivers a valid ValidationResponse."); Assert.IsNotNull(result.Errors, "The error list of the ValidationInfo is wrongly null."); Assert.AreEqual(errorCount, result.Errors.Count, $"The ValidationInfo created with {errorCount} error(s) contains {result.Errors.Count} error(s)."); }
protected void ThrowIfInvalid() { if (_results.Count > 0) { var message = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); var errorMessage = new ValidationResponse { ErrorMessage = _results.Select(result => result.ErrorMessage).ToList() }; message.Content = new ObjectContent(errorMessage.GetType(), errorMessage, new JsonMediaTypeFormatter()); throw new HttpResponseException(message); } }
public void CheckAccessTokenValidation() { AuthorisationGrant authorisationGrant = GetAuthorisationGrant(); AccessToken accessToken = GetAccessToken(authorisationGrant); string accessTokenStr = JsonConvert.SerializeObject(accessToken); string encryptedAccessToken = SymmetricEncryption.Encrypt(accessTokenStr); ValidationResponse result = CheckAccessTokenValid(encryptedAccessToken); if (result == null) { Assert.Fail(); } }
public void CreateCourse_ReturnsValidationError_WhenNullPassed() { //Arrange CourseService courseService = new CourseService(null, null, null, null); //Act var createdCourse = courseService.CreateCourse(null); //Assert ValidationResponse <Course> expected = new ValidationResponse <Course>("course", "Course cannot be null"); expected.Should().BeEquivalentTo(createdCourse); }
public IActionResult GetById(Guid id) { ValidationResponse <Order> validationResponse = _orderService.GetById(id); if (validationResponse.Status == ValidationStatus.NotFound) { return(NotFound(validationResponse.Message)); } OrderResponseModel orderResponse = _mapper.Map <Order, OrderResponseModel>(validationResponse.ResponseData); return(Ok(orderResponse)); }
public void GetByIdUserNotFoundTest() { ValidationResponse <User> validationResponse = GetNotFoundValidationResponse(); _mockService .Setup(serv => serv.GetById(_userId)) .Returns(validationResponse); IActionResult actionResult = _controller.GetById(_userId); NotFoundObjectResult actual = (NotFoundObjectResult)actionResult; Assert.Equal(StatusCodes.Status404NotFound, actual.StatusCode); }
public object NearByPlaces(RequestNearByPlaces req) { ValidationResponse<List<Place>> nearPlacesResp = new ValidationResponse<List<Place>>(); if (string.IsNullOrEmpty(req.Place)) { nearPlacesResp.Errors.Add("place name", "place name can not be empty"); return Json(nearPlacesResp); } if (req.Distance < 0 || req.Distance > 10000) { nearPlacesResp.Errors.Add("distance limit", "distanse can be only between 0.1 and 10 km"); return Json(nearPlacesResp); } try { using (GooglePlacesClient placesClient = new GooglePlacesClient()) { ValidationResponse<List<Place>> placesResp = placesClient.GetPlacesByQuery(new ReqQueryPlaces() { query = req.Place }); if (!placesResp.Obj.IsNullOrEmpty()) { Place pl = placesResp.Obj.FirstOrDefault(); nearPlacesResp = placesClient.GetNearByPlaces(new ReqNearByPlaces() { location = pl.geometry.location.lat + "," + pl.geometry.location.lng, radius = req.Distance, // req.Rankby == RankBy.distance ? new Nullable<int>() : req.Distance, keyword = req.Keywords //rankby = req.Rankby.ToString() }); if (nearPlacesResp.IsValid && !nearPlacesResp.Obj.IsNullOrEmpty()) { return Json(new { IsValid = true, NearByPlaces = nearPlacesResp.Obj, CenterPlace = pl }); } } else { return Json(placesResp); } } } catch (Exception ex) { LogHandler.WriteLog("Place controller NearByPlaces error", "", ex, Level.Error); nearPlacesResp.Errors.Add("Unexpected error", "Unexpected error " + ex.Message); } return Json(nearPlacesResp); }
public object DetailsPlaces(RequestPlaceDetails req) { ValidationResponse<PlaceSummary> response = new ValidationResponse<PlaceSummary>(); if (string.IsNullOrEmpty(req.PlaceID)) { response.Errors.Add("placeID", "placeID can not be empty"); return Json(response); } if (string.IsNullOrEmpty(req.Lang)) { req.Lang = "en"; } try { response = PlaceSummaryCrawler.PrepareSummary(req.PlaceID, req.MainPlaceName, req.Lang); } catch (Exception ex) { LogHandler.WriteLog("Place controller PlacesDetails error", "", ex, Level.Error); response.Errors.Add("Unexpected error", "Unexpected error " + ex.Message); } return Json(response); }
public static ValidationResponse<PlaceSummary> PrepareSummary(string placeIDToSummarize, string mainPlaceNearByName, string lang = "en") { ValidationResponse<PlaceSummary> response = new ValidationResponse<PlaceSummary>(); if (string.IsNullOrEmpty(placeIDToSummarize)) { throw new ArgumentException("placeIDToSummarize"); } PlaceSummary summary; string cacheKey = "Summary-" + placeIDToSummarize + "-" + lang; if (HttpContext.Current.Cache[cacheKey] != null) { summary = HttpContext.Current.Cache[cacheKey] as PlaceSummary; if (summary != null) { response.Obj = summary; return response; } } summary = new PlaceSummary(placeIDToSummarize); // step 0 - gt place details from places api. using (GooglePlacesClient placesClient = new GooglePlacesClient()) { var placeRes = placesClient.GetPlacesDetails(new ReqPlaceDetails() { placeid = summary.PlaceIDToSummarize, language = lang }); if (placeRes.Obj != null) { summary.Place = placeRes.Obj; } else { foreach (var error in placeRes.Errors) { response.Errors.Add(error.Key, error.Value); } } } if (summary.Place != null) { // step 2 - Create summary summary.MainSummaryText = summary.Place.name; summary.MainSummarySources = new List<string>(); using (AylienClient summClient = new AylienClient()) { ReqSummarise summReq = new ReqSummarise(); summReq.sentences_number = 6; summReq.language = "auto"; List<string> summarizedArticles = new List<string>(); string SourcesToSummarizeNumberStr = System.Configuration.ConfigurationManager.AppSettings["SourcesToSummarizeNumber"]; short SourcesToSummarizeNumber; Int16.TryParse(SourcesToSummarizeNumberStr, out SourcesToSummarizeNumber); if (SourcesToSummarizeNumber == 0) { SourcesToSummarizeNumber = 3; } // Try to retrieve summary from place website if (!string.IsNullOrEmpty(summary.Place.website)) { summReq.url = summary.Place.website; var summResp = summClient.Summarise(summReq); if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0) { summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences)); summary.MainSummarySources.Add(summary.Place.website); } } // Try to retrieve summary from google search results // Google search List<Result> googleSearchResults = null; using (GoogleSearchClient clWebPages = new GoogleSearchClient()) { ReqGoogleSearch req = new ReqGoogleSearch(); req.q = summary.Place.name + ", " + mainPlaceNearByName; req.hl = lang; req.lr = "lang_" + lang; var googleSearchResultsResp = clWebPages.GetSearchResults(req); if (googleSearchResultsResp.Obj != null && googleSearchResultsResp.Obj.Items != null && googleSearchResultsResp.Obj.Items.Count > 0) { googleSearchResults = googleSearchResultsResp.Obj.Items.ToList(); } } // Summaries from search results if (googleSearchResults != null && googleSearchResults.Count > 0) { int maxResultsToSearchIn = 4; for (int i = 0; i < googleSearchResults.Count && i < maxResultsToSearchIn && summarizedArticles.Count < SourcesToSummarizeNumber && !summary.MainSummarySources.Contains(googleSearchResults[i].Link) ; i++) { summReq.url = googleSearchResults[i].Link; var summResp = summClient.Summarise(summReq); if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0) { summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences)); summary.MainSummarySources.Add(googleSearchResults[i].Link); } } } // Summarise all summaries to one big summary. if (summarizedArticles.Count > 0) { ReqSummarise summFuncReq = new ReqSummarise(); summFuncReq.title = summary.Place.name; summFuncReq.text = string.Join("\n\r\\s", summarizedArticles.OrderByDescending(s => s.Length)); // Combine all summarized articles. summFuncReq.sentences_number = 5; var summFuncResp = summClient.Summarise(summFuncReq); if (summFuncResp.Obj != null && summFuncResp.Obj.sentences != null && summFuncResp.Obj.sentences.Count > 0) { summary.MainSummaryText = string.Join(" ", summFuncResp.Obj.sentences); } else { // fallback just print combined text. summary.MainSummaryText = summFuncReq.text; } } } // step 3 - Retrieve images using (GoogleSearchClient clImages = new GoogleSearchClient()) { ReqGoogleSearch req = new ReqGoogleSearch(); req.q = summary.Place.name + ", " + mainPlaceNearByName; req.searchType = PlacesIR.GoogleSearch.ReqGoogleSearch.SearchTypeEnum.image; req.hl = lang; var imgResp = clImages.GetSearchResults(req); if (imgResp.Obj != null && imgResp.Obj.Items != null) { foreach (var item in imgResp.Obj.Items) { Image img = new Image(); img.title = item.Title; img.url = item.Link; img.thumb_url = item.Image.ThumbnailLink; summary.Images.Add(img); } } } // step 4 - Retrieve videos using (YouTubeClient YouTubeClient = new YouTubeClient()) { ReqSearch req = new ReqSearch(); req.q = summary.Place.name + ", " + mainPlaceNearByName; req.relevanceLanguage = lang; var youResp = YouTubeClient.GetSearchResults(req); if (youResp.Obj != null && youResp.Obj.items != null) { summary.Videos = youResp.Obj.items; } } // step 5 - get prices if available. // TODO Retrieve prices if available HttpRuntime.Cache.Insert(cacheKey, summary, null, DateTime.Now.AddHours(4), TimeSpan.Zero); } response.Obj = summary; return response; }
public UploadResponse(ValidationResponse validationResponse, string webUrl) { WebUrl = webUrl; ValidationResponse = validationResponse; }
public ValidationResponse Validate(FileItem fileItem) { ValidationResponse response = new ValidationResponse(); if (!File.Exists(fileItem.LocalFileName)) { response.Valid = false; response.Message = "Source file not found ! " + fileItem.LocalFileName; } if (string.IsNullOrEmpty(fileItem.DestinationFilename)) { response.Valid = false; response.Message = "No install location specified ! " + fileItem.LocalFileName; } if (!fileItem.DestinationFilename.Contains("%")) { response.Valid = false; response.Message = "No template in destination path specified ! " + fileItem.LocalFileName; } return response; }
/// <summary> /// Opportunity to set policy for handling requests with invalid signatures and/or timestamps /// </summary> /// <returns>Validation Response Object. Success will be true if tests pass</returns> public virtual ValidationResponse OnRequestValidation(ValidationRequest request) { var response = new ValidationResponse { ValidationResult = SpeechletRequestValidationResult.OK }; string chainUrl = null; if (!request.HttpRequest.Headers.Contains(Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER) || String.IsNullOrEmpty(chainUrl = request.HttpRequest.Headers.GetValues(Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER).First())) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.NoCertHeader; } string signature = null; if (!request.HttpRequest.Headers.Contains(Sdk.SIGNATURE_REQUEST_HEADER) || String.IsNullOrEmpty(signature = request.HttpRequest.Headers.GetValues(Sdk.SIGNATURE_REQUEST_HEADER).First())) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.NoSignatureHeader; } var alexaBytes = AsyncHelpers.RunSync<byte[]>(() => request.HttpRequest.Content.ReadAsByteArrayAsync()); //Debug.WriteLine(request.HttpRequest.ToLogString()); // attempt to verify signature only if we were able to locate certificate and signature headers if (response.ValidationResult == SpeechletRequestValidationResult.OK) { if (!SpeechletRequestSignatureVerifier.VerifyRequestSignature(alexaBytes, signature, chainUrl)) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.InvalidSignature; } } GetRequest(alexaBytes, ref response); // attempt to verify timestamp only if we were able to parse request body if (response.AlexaRequest != null) { if (!SpeechletRequestTimestampVerifier.VerifyRequestTimestamp(response.AlexaRequest, request.RequestTime)) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.InvalidTimestamp; } } response.Success = (response.ValidationResult == SpeechletRequestValidationResult.OK); return response; }
/// <summary> /// Takes HttpRequest.Context.Bytes and converts to an Alexa Request. /// The response is passed in as a reference object since updating multiple values. /// </summary> public virtual void GetRequest(byte[] alexaBytes, ref ValidationResponse response) { try { var alexaContent = UTF8Encoding.UTF8.GetString(alexaBytes); response.AlexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent); } catch (Newtonsoft.Json.JsonReaderException) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.InvalidJson; } catch (InvalidCastException) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.InvalidJson; } catch (SpeechletException) { response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.InvalidSpeechlet; } catch (Exception ex) { //TODO: Log Error response.ValidationResult = response.ValidationResult | SpeechletRequestValidationResult.Error; } }
public void RequestIsEmptyAlexaMessage() { var request = new ValidationRequest { HttpRequest = new HttpRequestMessage { Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }, Headers = { { Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER, "TestSignatureCertChainUrlValue" }, { Sdk.SIGNATURE_REQUEST_HEADER, "TestSignatureValue" } }, Content = new StringContent(string.Empty) } }; var alexaBytes = AsyncHelpers.RunSync(() => request.HttpRequest.Content.ReadAsByteArrayAsync()); var speechlet = new EmptySpeechlet(); var response = new ValidationResponse { ValidationResult = SpeechletRequestValidationResult.OK }; speechlet.GetRequest(alexaBytes, ref response); Assert.True((response.ValidationResult & SpeechletRequestValidationResult.InvalidSpeechlet) == SpeechletRequestValidationResult.InvalidSpeechlet); }
/// <summary> /// For Testing Purposes Override Request Validation to just convert Request to Alexa Response Object /// </summary> /// <param name="request"></param> /// <returns></returns> public override ValidationResponse OnRequestValidation(ValidationRequest request) { var response = new ValidationResponse { ValidationResult = SpeechletRequestValidationResult.OK, Success = true }; var alexaBytes = AsyncHelpers.RunSync(() => request.HttpRequest.Content.ReadAsByteArrayAsync()); GetRequest(alexaBytes, ref response); return response; }