public async Task <ApiResponseResult> GetAllProducts(int?pageNumber = 1, int?pageSize = 10) { ApiResponseResult apiResponseResult = new ApiResponseResult(); paginationDTO <ProductModel> paginatedorders = new paginationDTO <ProductModel>(); try { var model = _productRepository.GetProducts(pageNumber, pageSize); paginatedorders.Paging = model.GetHeader(); //paginatedorders.pagedLinks = _categoryRepository.pageLinks(routname, pageNumber.Value, pageSize.Value, paginatedorders.Paging.TotalItems); paginatedorders.Items = await model.List; apiResponseResult.data = paginatedorders; //apiResponseResult.data = _productRepository.GetProducts(pageNumber, pageSize); apiResponseResult.message = "Products Get Successfully"; apiResponseResult.ErrorCode = (int)Constant.Error.NO_ERROR; apiResponseResult.status = true; } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.status = false; } return(apiResponseResult); }
private async Task <RefreshTokenStatus> RefreshTokens(CancellationToken cancellationToken) { if (string.IsNullOrEmpty(_tokenStorage.RefreshToken) || string.IsNullOrEmpty(_tokenStorage.Uid)) { return(RefreshTokenStatus.Unauthorized); } try { ApiResponseResult <RefreshTokenResponse> response = await _tokenClient.RefreshTokenAsync(cancellationToken); if (response.Success) { _tokenStorage.AccessToken = response.Value.AccessToken; _tokenStorage.RefreshToken = response.Value.RefreshToken; return(RefreshTokenStatus.Success); } } catch (ArgumentNullException e) { _logger.Error($"An error occurred when refreshing the auth token: {e.ParamName}"); } catch (HttpRequestException) { return(RefreshTokenStatus.Fail); } return(RefreshTokenStatus.Unauthorized); }
private async Task Handle() { if (DateTime.Now.Subtract(_lastCheck) < _checkInterval) { return; } _lastCheck = DateTime.Now; await Semaphore.WaitAsync(); try { ApiResponseResult <VpnInfoResponse> response = await _api.GetVpnInfoResponse(); if (response.Success) { _userStorage.StoreVpnInfo(response.Value); } } catch (HttpRequestException) { } finally { Semaphore.Release(); } }
public async Task <ApiResponseResult> UpdateCategory(CategoryModel category) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { var _categpry = await _context.Categories.Where(x => x.categoryId == category.categoryId).FirstOrDefaultAsync(); if (_categpry != null) { _categpry.categoryDesc = category.categoryDesc; _categpry.categoryName = category.categoryName; if (category.categoryImage != null && category.categoryImage != "") { _categpry.categoryImage = category.categoryImage; } await _context.SaveChangesAsync(); apiResponseResult.message = "Category Updated Successfully"; apiResponseResult.ErrorCode = (int)Constant.Error.NO_ERROR; } else { apiResponseResult.message = "No Category found"; apiResponseResult.ErrorCode = (int)Constant.Error.RECIEVE_DATA_NULL; } } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; } return(apiResponseResult); }
public async Task <ApiResponseResult> GetStudents() { ApiResponseResult apiResponse = new ApiResponseResult(); try { apiResponse.data = await studentService.GetAllStudents(); apiResponse.status = true; apiResponse.statusCode = 200; if (apiResponse.data != null) { apiResponse.message = "Students Get Successfully"; } else { apiResponse.message = "No Records found"; } } catch (Exception exc) { apiResponse.status = false; apiResponse.statusCode = 500; apiResponse.message = exc.Message; } return(apiResponse); }
private async Task <bool> ServerOffline() { PhysicalServer server = _serverManager.GetPhysicalServerByServer(_state.Server); if (server == null) { _logger.Info($"The server {_state.Server.Name} ({_state.Server.ExitIp}) was removed from the API."); return(true); } try { ApiResponseResult <PhysicalServerResponse> result = await _apiClient.GetServerAsync(server.Id); if (!result.Success) { return(false); } bool isServerUnderMaintenance = result.Value.Server.Status == 0; if (isServerUnderMaintenance) { _logger.Info($"The server {_state.Server.Name} ({_state.Server.ExitIp}) is under maintenance."); } return(isServerUnderMaintenance); } catch (HttpRequestException) { return(false); } }
public async Task <ApiResponseResult> DeleteProduct(int productId) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { var itemToRemove = _context.Products.SingleOrDefault(x => x.productId == productId); //returns a single item. if (itemToRemove != null) { _context.Products.Remove(itemToRemove); await _context.SaveChangesAsync(); apiResponseResult.message = "Product Deleted Successfully"; apiResponseResult.ErrorCode = (int)Constant.Error.NO_ERROR; } else { apiResponseResult.message = "No Product found"; apiResponseResult.ErrorCode = (int)Constant.Error.RECIEVE_DATA_NULL; } } catch (Exception exc) { throw exc; } return(apiResponseResult); }
public async Task TrafficShouldBeForwardedWhenUserLocationServiceReturns(string ip, string currentConnectedIP, bool expected) { // Arrange var response = ApiResponseResult <UserLocation> .Ok(new UserLocation { Ip = ip }); _vpnConfig.BlackHoleIps.Returns(new List <string> { "62.112.9.168", "104.245.144.186" }); _userLocationService.LocationAsync().Returns(response); var subject = new ForwardedTraffic(_userLocationService, _vpnConfig); await subject.OnVpnStateChanged(new VpnStateChangedEventArgs( VpnStatus.Connected, VpnError.None, GetConnectedServer(currentConnectedIP), false, VpnProtocol.Auto)); // Act var result = await subject.Value(); // Assert result.Forwarded.Should().Be(expected); }
public async Task SendAsync_ShouldRepeatRequest_WithRefreshedAccessToken() { // Arrange _tokenClient.RefreshTokenAsync(Arg.Any <CancellationToken>()) .Returns(ApiResponseResult <RefreshTokenResponse> .Ok( new RefreshTokenResponse { AccessToken = "New access token", RefreshToken = "New refresh token" })); var handler = new UnauthorizedResponseHandler(_tokenClient, _tokenStorage, _userStorage) { InnerHandler = _innerHandler }; var client = new HttpClient(handler) { BaseAddress = _baseAddress }; _innerHandler.Expect(HttpMethod.Get, "https://api.protonvpn.ch/logicals") .Respond(HttpStatusCode.Unauthorized); _innerHandler.Expect(HttpMethod.Get, "https://api.protonvpn.ch/logicals") .WithHeaders("Authorization", "Bearer New access token") .Respond(HttpStatusCode.OK); // Act var request = new HttpRequestMessage(HttpMethod.Get, "/logicals"); await client.SendAsync(request); // Assert _innerHandler.VerifyNoOutstandingExpectation(); }
public async Task SendAsync_ShouldSet_TokenStorage_Tokens() { // Arrange _tokenClient.RefreshTokenAsync(Arg.Any <CancellationToken>()) .Returns(ApiResponseResult <RefreshTokenResponse> .Ok( new RefreshTokenResponse { AccessToken = "New access token", RefreshToken = "New refresh token" })); var handler = new UnauthorizedResponseHandler(_tokenClient, _tokenStorage, _userStorage) { InnerHandler = _innerHandler }; var client = new HttpClient(handler) { BaseAddress = _baseAddress }; _innerHandler.Expect(HttpMethod.Get, "https://api.protonvpn.ch/logicals") .Respond(HttpStatusCode.Unauthorized); // Act var request = new HttpRequestMessage(HttpMethod.Get, "/logicals"); await client.SendAsync(request); // Assert _tokenStorage.AccessToken.Should().Be("New access token"); _tokenStorage.RefreshToken.Should().Be("New refresh token"); }
public async Task SendAsync_ShouldRaise_SessionExpired_WhenRefreshFailed() { // Arrange _tokenClient.RefreshTokenAsync(Arg.Any <CancellationToken>()) .Returns(ApiResponseResult <RefreshTokenResponse> .Fail(HttpStatusCode.BadRequest, "Refresh failed")); var handler = new UnauthorizedResponseHandler(_tokenClient, _tokenStorage, _userStorage) { InnerHandler = _innerHandler }; var client = new HttpClient(handler) { BaseAddress = _baseAddress }; _innerHandler.Expect(HttpMethod.Get, "https://api.protonvpn.ch/logicals") .Respond(HttpStatusCode.Unauthorized); using (var monitoredSubject = handler.Monitor()) { // Act var request = new HttpRequestMessage(HttpMethod.Get, "/logicals"); await client.SendAsync(request); // Assert monitoredSubject.Should().Raise(nameof(UnauthorizedResponseHandler.SessionExpired)); _innerHandler.VerifyNoOutstandingExpectation(); } }
public async Task <ApiResponseResult> Authenticate(AuthenticateRequest model) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { var response = await _userService.Authenticate(model); if (response == null) { apiResponseResult.ErrorCode = (int)Constant.Error.INVALID_USER; apiResponseResult.message = "Username or password is incorrect"; } else { apiResponseResult.data = response; apiResponseResult.ErrorCode = (int)Constant.Error.NO_ERROR; apiResponseResult.message = "Loged in"; } } catch (Exception exc) { apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.message = exc.Message; } return(apiResponseResult); }
public async Task DeleteProfiles() { ApiResponseResult <ProfilesResponse> profiles = await _api.GetProfiles(); foreach (Profile profile in profiles.Value.Profiles) { await _api.DeleteProfile(profile.Id); } }
private async Task <ApiResponseResult <CertificateResponseData> > MockOfRequestAuthCertificateAsync(CertificateRequestData arg) { if (arg.ClientPublicKey.IsNullOrEmpty() || _usedClientPublicKeys.Contains(arg.ClientPublicKey)) { return(ApiResponseResult <CertificateResponseData> .Fail(CreateClientPublicKeyConflictCertificateResponseData(), HttpStatusCode.BadRequest, string.Empty)); } _usedClientPublicKeys.Add(arg.ClientPublicKey); _certificateResponseData ??= CreateCertificateResponseData(); return(ApiResponseResult <CertificateResponseData> .Ok(_certificateResponseData)); }
public async Task Update(Profile profile) { Ensure.NotNull(profile, nameof(profile)); Ensure.IsTrue(!profile.IsPredefined, "Can't update predefined profile"); Ensure.IsTrue(profile.IsColorCodeValid()); ApiResponseResult <ProfileResponse> response = await HandleErrors( () => _apiClient.UpdateProfile(profile.ExternalId, ToApiProfile(profile))); UpdatePropertiesFromApiProfile(profile, response.Value.Profile); }
public void TestInitialize() { _tokenClient = Substitute.For <ITokenClient>(); _tokenClient.RefreshTokenAsync(Arg.Any <CancellationToken>()) .Returns(ApiResponseResult <RefreshTokenResponse> .Ok(new RefreshTokenResponse())); _tokenStorage = Substitute.For <ITokenStorage>(); _tokenStorage.AccessToken.Returns("Access token"); _tokenStorage.RefreshToken.Returns("Refresh token"); _tokenStorage.Uid.Returns(string.Empty); _innerHandler = new MockHttpMessageHandler(); }
public void TestInitialize() { _apiClient = Substitute.For <IApiClient>(); _userStorage = Substitute.For <IUserStorage>(); var result = ApiResponseResult <VpnInfoResponse> .Ok(new VpnInfoResponse { Code = 1000, Error = string.Empty }); _apiClient.GetVpnInfoResponse().Returns(Task.FromResult(result)); }
public async Task <ApiResponseResult> SaveGuestInfo(GuestInfoDTO Guest, AddressDTO address) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await _userRepository.SaveGuestInfo(Guest, address); } catch (Exception exc) { throw exc; } return(apiResponseResult); }
public async Task <ApiResponseResult> RegisterUser(User user) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await _userRepository.SaveUser(user); } catch (Exception exc) { apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.message = exc.Message; } return(apiResponseResult); }
private async Task UpdateUserInfo() { try { ApiResponseResult <VpnInfoResponse> result = await _api.GetVpnInfoResponse(); if (result.Success) { _userStorage.StoreVpnInfo(result.Value); } } catch (HttpRequestException) { } }
public async Task <ApiResponseResult> GetProductById(int productId) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await productService.GetProductById(productId); } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; } return(apiResponseResult); }
public async Task <ApiResponseResult> GetProductsByCategoryId(string search, int categoryId, int?pageNumber = 1, int?pageSize = 10) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await productService.SearchProduct(search, categoryId, pageNumber, pageSize); } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; } return(apiResponseResult); }
public async Task <ApiResponseResult> DeleteCategory(int categoryId) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await categoryService.DeleteCategory(categoryId); } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; } return(apiResponseResult); }
public async Task <ApiResponseResult> RegisterUser(User _user) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { return(await _userService.RegisterUser(_user)); } catch (Exception exc) { apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.message = exc.Message; } return(apiResponseResult); }
public async Task RefreshVpnInfo(Action <VpnInfoResponse> onSuccess) { try { ApiResponseResult <VpnInfoResponse> infoResult = await RefreshVpnInfo(); if (infoResult.Success) { onSuccess(infoResult.Value); } } catch (HttpRequestException ex) { _logger.Error(ex.Message); } }
public async Task <ApiResponseResult <VpnInfoResponse> > RefreshVpnInfo() { ApiResponseResult <VpnInfoResponse> vpnInfo = await _apiClient.GetVpnInfoResponse(); if (vpnInfo.Success) { if (!vpnInfo.Value.Vpn.Status.Equals(UserStatusVpnAccess)) { return(ApiResponseResult <VpnInfoResponse> .Fail(vpnInfo.StatusCode, "User has no vpn access.")); } _userStorage.StoreVpnInfo(vpnInfo.Value); } return(vpnInfo); }
public async Task <ApiResponseResult> GetNotifications(int?userId = 0, int?pageNumber = 1, int?pageSize = 10) { ApiResponseResult apiResponseResult = new ApiResponseResult(); try { apiResponseResult = await notificationService.GetNotifications(userId, pageNumber, pageSize); } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.status = false; } return(apiResponseResult); }
private void SetSessions(int number) { var sessions = new List <Session>(); for (var i = 0; i < number; i++) { sessions.Add(new Session()); } _apiClient.GetSessions().Returns(Task.FromResult(ApiResponseResult <SessionsResponse> .Ok(new SessionsResponse { Code = 1000, Error = string.Empty, Sessions = sessions }))); }
public async Task <ApiResponseResult> AddProduct(Dictionary <string, string> requestKeys, IFormFile file = null) { ApiResponseResult apiResponseResult = new ApiResponseResult(); ProductModel productModel = new ProductModel(); try { if (!await _userService.IsUserHasRights()) { apiResponseResult.message = "User has no permissions to perform this action"; apiResponseResult.ErrorCode = (int)Constant.Error.INVALID_PERMISSIONS; return(apiResponseResult); } string fileName = ""; string projectRootPath = _hostingEnvironment.ContentRootPath; if (file != null) { fileName = Utility.FileUpload(file, projectRootPath); } productModel.productBrand = requestKeys["productBrand"]; productModel.productDesc = requestKeys["productDesc"]; productModel.productImage = fileName; productModel.productName = requestKeys["productName"]; productModel.productWeight = requestKeys["productWeight"]; productModel.productPrice = (float)Convert.ToDouble(requestKeys["productPrice"]); if (requestKeys["categoryId"] != "undefined") { productModel.categoryId = Convert.ToInt32(requestKeys["categoryId"] ?? ""); } await _productRepository.Insert(productModel); apiResponseResult.message = "Product Saved Successfully"; apiResponseResult.ErrorCode = (int)Constant.Error.NO_ERROR; apiResponseResult.status = true; } catch (Exception exc) { apiResponseResult.message = exc.Message; apiResponseResult.ErrorCode = (int)Constant.Error.EXCEPTION; apiResponseResult.status = false; } return(apiResponseResult); }
public string GetLicense(Guid id) { ApiResponseResult result = new ApiResponseResult(); if (_context.Licenses.Any(c => c.Id == id)) { result.returnType = LicenseInformations.Enums.ReturnType.Confirm; result.Value = JsonConvert.SerializeObject(_context.Licenses.FirstOrDefault(c => c.Id == id)); return(EncrpytionTool.Encrypt(JsonConvert.SerializeObject(result))); } else { result.returnType = ReturnType.Error; result.Value = "Lisans Bulunamadı"; return(EncrpytionTool.Encrypt(JsonConvert.SerializeObject(result))); } }