public void NotFoundObjectResult_InitializesStatusCode() { // Arrange & act var notFound = new NotFound <object>(null); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); }
protected override void NestedPackageSucceeds(PackageResolverVisitor <IPackageInfo> newResolver) { base.NestedPackageSucceeds(newResolver); Success.AddRange(((LoggingPackageVisitor)newResolver).Success); Fail.AddRange(((LoggingPackageVisitor)newResolver).Fail); NotFound.AddRange(((LoggingPackageVisitor)newResolver).NotFound); }
public void GenericResult_ShouldReturnNotFound_WhenInvalidFactoryCall() { NotFound expectedResult = new NotFound(); var result = Result <object> .Invalid(); Assert.True(result.Equals(expectedResult)); }
public void GenericResult_ShouldCustomizeMetaResult_WhenGiveDefaultCustomMetaResult() { NotFound expectedResult = new NotFound(); var result = new Result <object>().With <NotFound>(); Assert.True(result.Equals(expectedResult)); }
public void NotFoundObjectResult_InitializesStatusCodeAndResponseContent() { // Arrange & act var notFound = new NotFound <string>("Test Content"); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); Assert.Equal("Test Content", notFound.Value); }
public void ExecuteAsync_ThrowsArgumentNullException_WhenHttpContextIsNull() { // Arrange var result = new NotFound(); HttpContext httpContext = null; // Act & Assert Assert.ThrowsAsync <ArgumentNullException>("httpContext", () => result.ExecuteAsync(httpContext)); }
public void Result_ShouldReturnInvalidCustomResultType_WhenCallInvalidWhitCustomType() { NotFound expectedResult = new NotFound(); var result = Result <Ok> .Invalid(new CustomMetaResult()); Assert.Equal(typeof(CustomMetaResult), result.GetValueType()); Assert.True(result.Equals(expectedResult)); }
public void GetCustomer_IdIsZero_ReturnsNotFound() { //Act var result = _customerController.GetCustomer(0); NotFound notFound = new NotFound(); //Assert Assert.That(result, Is.TypeOf <NotFound>()); }
public static T SurelyFind <T>(this IRepository <T> repository, params object[] keys) where T : class { var entity = repository.Find(keys); if (entity == null) { throw NotFound.ExceptionFor <T>(keys); } return(entity); }
public void NotFoundObjectResult_ProblemDetails_SetsStatusCodeAndValue() { // Arrange & Act var obj = new HttpValidationProblemDetails(); var result = new NotFound <HttpValidationProblemDetails>(obj); // Assert Assert.Equal(StatusCodes.Status404NotFound, result.StatusCode); Assert.Equal(StatusCodes.Status404NotFound, obj.Status); Assert.Equal(obj, result.Value); }
public void SetUp() { var mediaType = new Mock <IMediaType>(); mediaType.SetupGet(mt => mt.Synonyms).Returns(new[] { "media-type" }); result = new NotFound { MediaType = mediaType.Object }; }
public async Task NotFoundObjectResult_ExecuteSuccessful() { // Arrange var httpContext = GetHttpContext(); var result = new NotFound(); // Act await result.ExecuteAsync(httpContext); // Assert Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); }
protected override bool VisitPackages(IEnumerable <IPackageInfo> matchingPackages) { if (_includePrePackages == false) { matchingPackages = matchingPackages.Where(_ => _.SemanticVersion.PreRelease == null && _.Dependencies.Any(dep => dep.Edge) == false); } if (!matchingPackages.Any()) { NotFound.Add(new CallStack(_currentNode)); } return(base.VisitPackages(matchingPackages)); }
private Proto.Msg.NotFound NotFoundToProto(NotFound msg) { var proto = new Proto.Msg.NotFound { Key = this.OtherMessageToProto(msg.Key) }; if (!ReferenceEquals(null, msg.Request)) { proto.Request = this.OtherMessageToProto(msg.Request); } return(proto); }
public void UpdateUser(UpdateUserCommand command) { EnsureIsValid(command); try { var user = _deps.Users.Find(command.UserId); if (user == null || user.Deleted) { throw NotFound.ExceptionFor <User>(command.UserId); } var paymentProfile = _deps.PaymentProfiles.Find(command.UserId); if (command.Role == UserClaim.Roles.Admin && paymentProfile != null) { _deps.PaymentProfiles.Delete(paymentProfile); } else if (command.Role == UserClaim.Roles.Customer && paymentProfile == null) { paymentProfile = _deps.UserPaymentProfileFactory.Create(user, command.Address, command.FullName); _deps.PaymentProfiles.Create(paymentProfile); } else if (command.Role == UserClaim.Roles.Customer) { Mapper.Map(command, paymentProfile); _deps.PaymentProfiles.Update(paymentProfile); } Mapper.Map(command, user); var role = UserClaim.CreateRole(command.UserId, command.Role); var existingRoles = user.Claims.Where(x => x.Type == ClaimTypes.Role).ToList(); foreach (var existingRole in existingRoles) { user.Claims.Remove(existingRole); } user.Claims.Add(role); if (command.ChangePassword) { user.UpdatePassword(command.Password); } Mapper.Map(command, user.Profile); Commit(); } catch (ServiceException) { throw; } catch (Exception ex) { throw new ServiceException("Can't update user.", ex); } }
private Task HandleExceptionAsync(HttpContext context, Exception exception) { // Response Error errorResponse; switch (exception) { case UnauthorizedException _: // 401 var unauthorizedException = (UnauthorizedException)exception; errorResponse = new Unauthorized(nameof(ErrorMessage.Unauthorized), unauthorizedException.Message); break; case ForbiddenException _: // 403 var forbiddenException = (ForbiddenException)exception; errorResponse = new Forbidden(nameof(ErrorMessage.Forbidden), forbiddenException.Message); break; case NotFoundException _: // 404 var notFoundException = (NotFoundException)exception; errorResponse = new NotFound(nameof(ErrorMessage.NotFound), notFoundException.Message); break; case ConflictException _: // 409 var conflictException = (ConflictException)exception; errorResponse = new Conflict(nameof(ErrorMessage.Conflict), conflictException.Message); break; default: // 500 errorResponse = new InternalServerError(nameof(ErrorMessage.InternalServerError), ErrorMessage.InternalServerError); // Log error _logger.LogSplunkError(exception); break; } var response = JsonConvert.SerializeObject(errorResponse, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List <JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter() } }); context.Response.ContentType = "application/json"; context.Response.StatusCode = errorResponse.Status; return(context.Response.WriteAsync(response)); }
public async Task <IActionResult> GetAsync(Guid id) { var data = await _service.GetAsync(id); if (data == null) { _loger.LogError("Data not found for id : " + id.ToString()); var error = new NotFound("Data not found for id : " + id.ToString(), new { id }); return(error.ReturnResponse()); } var result = new OK("Success get data by id = " + id.ToString(), data); return(result.ReturnResponse()); }
public void Update(TResult dto, NotFound <TResult> notFound = null) { if (dto == null) { throw new ArgumentNullException(nameof(dto)); } var entity = _dbSet.Find(GetKeyValues(dto)); if (entity == null) { (notFound ?? NotFound).Invoke(dto); return; } _rules.Apply(entity, DataAction.Update); Map(dto, entity); }
public async Task UpdateAsync(TResult dto, NotFound <TResult> notFound = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dto == null) { throw new ArgumentNullException(nameof(dto)); } var entity = await _dbSet.FindAsync(GetKeyValues(dto), cancellationToken); if (entity == null) { (notFound ?? NotFound).Invoke(dto); return; } _rules.Apply(entity, DataAction.Update); Map(dto, entity); }
public async Task <IActionResult> GetAsync(Guid id) { var data = await _service.GetAsync(id); data.ClientSecret = data.ClientSecret.ToBase64EncodeWithKey(_config["Security:EncryptKey"]); if (data == null) { _loger.LogError("Data not found for id : " + id.ToString()); var error = new NotFound("Data not found for id : " + id.ToString(), new { id }); return(error.ReturnResponse()); } var result = new OK("Success get data by id = " + id.ToString(), data); return(result.ReturnResponse()); }
public async Task <IActionResult> DeleteAsync(Guid id) { var data = await _service.GetAsync(id); if (data == null) { _loger.LogError("Not found data for id : " + id.ToString()); var error = new NotFound("Not found data for id : " + id.ToString(), new { id }); return(error.ReturnResponse()); } await _service.DeleteAsync(id); var result = new OK("Success delete data " + data.Name, new { id }); return(result.ReturnResponse()); }
public async Task RemoveRangeAsync(IEnumerable <TResult> dtos, NotFound <TResult, int> notFound = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dtos == null) { throw new ArgumentNullException(nameof(dtos)); } var dtoArray = dtos.ToArray(); var entities = new List <T>(dtoArray.Length); var hasError = false; var continuation = new Continuation(); for (var index = 0; index < dtoArray.Length; index++) { var dto = dtoArray[index]; var entity = await _dbSet.FindAsync(GetKeyValues(dto), cancellationToken); if (entity == null) { (notFound ?? NotFound).Invoke(dto, index, continuation); hasError = true; if (continuation.Yes) { continue; } break; } entities.Add(entity); } if (hasError) { return; } if (SoftDelete) { _rules.Apply(entities, DataAction.Remove); } else { _dbSet.RemoveRange(entities); } }
public static AppFunc OwinApp(IDictionary <string, object> startupEnv = null) { var app = new List <Func <AppFunc, AppFunc> >() .Use(H5bp.IeEdgeChromeFrameHeader()) .Use(H5bp.RemovePoweredBy()) .Use(H5bp.CrossDomainRules()) .Use(JsonBodyParser.Middleware()) .Use(UrlEncoded.Middleware()) .Use(MethodOverride.Middleware()); var router = new RegexRouter(app); var template = new RazorEngine.Templating.TemplateService(); router.Get("/", next => async env => { await env.GetResponseBody() .WriteStringAsync("hi"); }); template.Compile("Hi @Model.name", typeof(DynamicObject), "/hi"); router.Get(@"/hi/(?<name>((.)*))$", next => async env => { var routeParameters = env.GetSimpleOwinRouteParameters(); string html = template.Run("/hi", new { name = routeParameters["name"] }.ToDynamicObject()); await env.GetResponseBody() .WriteStringAsync(html); }); router.Get("/hello", next => async env => { await env.GetResponseBody() .WriteStringAsync("Hello"); }); router.All("*", NotFound.Middleware()); return(app.ToOwinApp()); }
public UserMessage UnlockUser(IdentityQuery <Guid> userId) { EnsureIsValid(userId); try { var user = _deps.Users.Find(userId.Id); if (user == null || user.Deleted) { throw NotFound.ExceptionFor <User>(userId.Id); } _deps.UserLockoutPolicy.Unblock(user); Commit(); return(UserMessage.Resource(() => Messages.UserSuccessfullyUnblocked)); } catch (Exception ex) { throw new ServiceException("Can't unblock user.", ex); } }
public static IActionResult ToActionResult(this Result result) { return(result switch { Success => new OkResult(), NotFound notFound => new NotFoundObjectResult(new { notFound.Errors, }), InvalidInput invalidInput => new BadRequestObjectResult(new { invalidInput.Errors, }), GeneralFail generalFail => new BadRequestObjectResult(new { generalFail.Errors, }), _ => new OkResult(), });
public async Task RemoveAsync(object[] keyValues, NotFound <TResult> notFound = null, CancellationToken cancellationToken = default(CancellationToken)) { if (keyValues == null) { throw new ArgumentNullException(nameof(keyValues)); } var entity = await _dbSet.FindAsync(keyValues); if (entity == null) { (notFound ?? NotFound).Invoke(null); return; } if (SoftDelete) { _rules.Apply(entity, DataAction.Remove); } else { _dbSet.Remove(entity); } }
public void Remove(object[] keyValues, NotFound <TResult> notFound = null) { if (keyValues == null) { throw new ArgumentNullException(nameof(keyValues)); } var entity = _dbSet.Find(keyValues); if (entity == null) { (notFound ?? NotFound).Invoke(null); return; } if (SoftDelete) { _rules.Apply(entity, DataAction.Remove); } else { _dbSet.Remove(entity); } }
public void LogApplicationAction(LogAppActionCommand command) { EnsureIsValid(command); try { var operation = _db.Operations.Find(command.OperationId); if (operation == null) { throw NotFound.ExceptionFor <Operation>(command.OperationId); } var appAction = ApplicationAction.Create( operation, command.Code, command.TimestampUtc, command.Description, command.Data); _db.AuditLogs.CreateAction(appAction); Commit(); } catch (Exception ex) { throw new ServiceException("Can't create application action.", ex); } }
public ByteResponse Execute(string str, string clientIp) { HttpRequest requestObject = null; HttpResponse httpResponse = null; try { requestObject = new HttpRequest(str); } catch { httpResponse = new NotFound().HttpResponse; } var virtualHost = VirtualHostList.GetVirtualHost(requestObject != null ? requestObject.Host : ""); var request = new Request(requestObject, virtualHost); var accessLogHandler = new AccessLogHandler(Path.Combine(DirectoryRoot, "logs", virtualHost.AccessLog), clientIp, requestObject != null ? requestObject.UserAgent : ""); if (httpResponse == null) { httpResponse = ChainControllerHandler.Execute(request).HttpResponse; } accessLogHandler.WriteInfo(request.Object.Method + " /" + request.Object.Uri.Url + " " + HttpResponseStatus.Get(httpResponse.HttpStatusCode)); httpResponse.Headers.Add("Server", HttpServer.HttpServerName); httpResponse.Headers.Add("Date", new HttpDate(DateTime.Now).ToString()); if (httpResponse.Content.IncludeBody && httpResponse.Content.Data == null) { httpResponse.Content.Data = GetErrorBody(httpResponse.HttpStatusCode); } return(new ByteResponse(httpResponse.GetBytes(), request.Object.KeepAlive)); }
public void UpdateRange(IEnumerable <TResult> dtos, NotFound <TResult, int> notFound = null) { if (dtos == null) { throw new ArgumentNullException(nameof(dtos)); } var dtoArray = dtos.ToArray(); var entities = new List <T>(dtoArray.Length); var hasError = false; var continuation = new Continuation(); for (var index = 0; index < dtoArray.Length; index++) { var dto = dtoArray[index]; var entity = _dbSet.Find(GetKeyValues(dto)); if (entity == null) { (notFound ?? NotFound).Invoke(dto, index, continuation); hasError = true; if (continuation.Yes) { continue; } break; } entities.Add(entity); } if (hasError) { return; } _rules.Apply(entities, DataAction.Update); _dbSet.UpdateRange(entities); }
public bool Equals(NotFound other) { return Equals(other.value, value); }