public ApiReply RequisicaoHttp(string url, string parametros, string contentType) { var resposta = new ApiReply(); try { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; var cliente = new RestClient(url); var requisicao = new RestRequest(Method.GET) { RequestFormat = DataFormat.Json }; requisicao.AddHeader("Content-Type", contentType); requisicao.Parameters.Clear(); requisicao.AddParameter(contentType, JsonConvert.SerializeObject(parametros), ParameterType.RequestBody); var retornoApi = cliente.Execute(requisicao); resposta.Data = retornoApi.Content; resposta.StatusCode = (int)retornoApi.StatusCode; resposta.Sucesso = (resposta.StatusCode >= 200 && resposta.StatusCode < 210); } catch (Exception ex) { resposta.Mensagem = $"Erro na requisição: {ex.Message}"; } return(resposta); }
public async Task PutEntityTest() { Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock <object>(HttpStatusCode.OK, null); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); string json = JsonConvert.SerializeObject(new Card(), new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }); StringContent stringContent = new StringContent(json); responseMessage.Content = stringContent; mock.ResponseMessages.Push(responseMessage); ApiReply reply = await connector.PutAsync(card); TestApiReply(reply, true, null, HttpStatusCode.OK); HttpRequestMessage request = TestRequest(mock, "Cards", HttpMethod.Put, user.AccessToken); string requestBody = await request.Content.ReadAsStringAsync(); Card card1 = JsonConvert.DeserializeObject <Card>(requestBody); Assert.AreEqual(card.CardId, card1.CardId); }
public async Task <GeoLocation?> TryResolveLocationAsync(IPAddress ip) { HttpClient client = _clientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(3); client.DefaultRequestHeaders.Add("User-Agent", "Gatekeeper"); UriBuilder uriBuilder = new UriBuilder(); uriBuilder.Scheme = "https"; uriBuilder.Host = "geoip-services.gatekeeper.page"; uriBuilder.Path = ip.ToString(); Uri uri = uriBuilder.Uri; try { ApiReply reply = await client.GetFromJsonAsync <ApiReply>(uri); if (reply.Success) { GeoLocation geoLocation = new GeoLocation { City = reply.City, CountryCode = reply.CountryCode, }; return(geoLocation); } } catch { } return(null); }
public async Task PostErrorTest() { Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock(HttpStatusCode.InternalServerError, new NotifyException("test-error")); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply reply = await connector.PostAsync("test", card); TestApiReply(reply, false, "test-error", HttpStatusCode.InternalServerError); mock = CreateMock(HttpStatusCode.InternalServerError, new NotifyException("test-error")); connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply <Card> reply1 = await connector.PostAsync <Card>("test", card); TestApiReply(reply, false, "test-error", HttpStatusCode.InternalServerError); Assert.IsNull(reply1.Result); }
public async Task DoesRefreshExpiredTokenTest() { User newUser = new User() { UserId = user.UserId, AccessToken = GenerateAccessToken(user.UserId, DateTime.Today.AddDays(1)), RefreshToken = GenerateRefreshToken().Token }; Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock <object>(HttpStatusCode.OK, null); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; user.AccessToken = GenerateAccessToken(user.UserId, DateTime.Now.AddMilliseconds(100)); HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK); string json = JsonConvert.SerializeObject(new Card(), new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }); StringContent stringContent = new StringContent(json); responseMessage.Content = stringContent; mock.ResponseMessages.Push(responseMessage); responseMessage = new HttpResponseMessage(HttpStatusCode.OK); json = JsonConvert.SerializeObject(newUser, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }); stringContent = new StringContent(json); responseMessage.Content = stringContent; mock.ResponseMessages.Push(responseMessage); await Task.Delay(100); ApiReply <Card> reply = await connector.PutAsync(card); TestApiReply(reply, true, null, HttpStatusCode.OK); HttpRequestMessage request = TestRequest(mock, "Cards", HttpMethod.Put, newUser.AccessToken); string requestBody = await request.Content.ReadAsStringAsync(); Card card1 = JsonConvert.DeserializeObject <Card>(requestBody); Assert.AreEqual(card.CardId, card1.CardId); request = TestRequest(mock, "Users/RefreshToken", HttpMethod.Post, user.AccessToken); requestBody = await request.Content.ReadAsStringAsync(); RefreshRequest refreshRequest = JsonConvert.DeserializeObject <RefreshRequest>(requestBody); Assert.AreEqual(user.AccessToken, refreshRequest.AccessToken); Assert.AreEqual(user.RefreshToken, refreshRequest.RefreshToken); Assert.AreEqual(newUser.AccessToken, connector.CurrentUser.AccessToken); Assert.AreEqual(newUser.RefreshToken, connector.CurrentUser.RefreshToken); }
public async Task GetEntitiesTest() { Card card = new Card() { CardId = 1 }; List <Card> cards = new List <Card>() { card }; HttpClientFactoryMock mock = CreateMock(HttpStatusCode.OK, cards); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; Dictionary <string, object> parameters = new Dictionary <string, object>() { { "test", 1 } }; ApiReply <List <Card> > reply = await connector.GetAsync <Card>(parameters); TestApiReply(reply, true, null, HttpStatusCode.OK); Assert.AreEqual(card.CardId, reply.Result[0].CardId); HttpRequestMessage request = TestRequest(mock, "Cards", HttpMethod.Get, user.AccessToken); string requestBody = await request.Content.ReadAsStringAsync(); parameters = JsonConvert.DeserializeObject <Dictionary <string, object> >(requestBody); Assert.AreEqual((long)1, parameters["test"]); }
public string changeStore2(StoreViewModel model) { ApiReply reply = new ApiReply() { result = 1 }; var currentUser = (PersonalizedIdentity)User.Identity; try { using (AlmacenDBEntities db = new AlmacenDBEntities()) { var oUser = (from us in db.user where currentUser.id == us.id select us).FirstOrDefault(); var oStore = (from st in db.user_store where model.id == st.id_store && oUser.id == st.id_user select st).FirstOrDefault(); if (oStore == null) { reply.message = "Error de Sucursal"; return(JsonConvert.SerializeObject(reply)); } oUser.id_defaultStore = model.id; db.Entry(oUser).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } reply.result = 0; reply.message = "Cambio de Sucursal con exito"; return(JsonConvert.SerializeObject(reply)); } catch (Exception ex) { reply.message = "Error al Actualizar Almacen"; return(JsonConvert.SerializeObject(reply)); } }
///<inheritdoc/> public override async Task <bool> InitializeAsync() { bool result = await base.InitializeAsync(); if (!result) { return(false); } Dictionary <string, object> parameters = new Dictionary <string, object>() { { nameof(Card.DeckId), Entity.DeckId } }; ApiReply <List <PracticeHistoryEntry> > reply = await ApiConnector.GetAsync <PracticeHistoryEntry>(parameters); if (!reply.WasSuccessful) { NotificationMessageProvider.ShowErrorMessage(reply.ResultMessage); return(false); } PracticeHistoryEntries.AddRange(reply.Result); SelectableDisplayUnits.Add(EntityNameHelper.GetName <Deck>()); SelectableDisplayUnits.AddRange(Entity.Cards.Select(card => card.GetDisplayName())); foreach (Card card in Entity.Cards) { cardIdLookup.Add(card.GetDisplayName(), card.CardId); } SelectedDisplayUnit = SelectableDisplayUnits.First(); return(true); }
public ApiReply Helloworld() { ApiReply reply = new ApiReply(); reply.result = 400; reply.message = "Se ejecuto de manera correcta"; return(reply); }
public void Deve_retornar_metodo_quando_apireply_preenchido_options() { var command = new ApiReply(); var result = command.RetornarRestMethod("OPTIONS"); Assert.AreEqual(Method.OPTIONS, result); }
public void Deve_retornar_metodo_quando_apireply_preenchido_merge() { var command = new ApiReply(); var result = command.RetornarRestMethod("MERGE"); Assert.AreEqual(Method.MERGE, result); }
public void Deve_retornar_metodo_quando_apireply_preenchido_head() { var command = new ApiReply(); var result = command.RetornarRestMethod("HEAD"); Assert.AreEqual(Method.HEAD, result); }
public void Deve_retornar_metodo_quando_apireply_preenchido_post() { var command = new ApiReply(); var result = command.RetornarRestMethod("POST"); Assert.AreEqual(Method.POST, result); }
public void Deve_retornar_verdadeiro_quando_apireply_nao_preenchido() { var command = new ApiReply(); command.Validar(); Assert.IsTrue(command.Notifications.Any()); }
public HttpResponseMessage AddData() { ApiReply reply = new ApiReply(); reply.result = 400; reply.message = "Se ejecuto de manera correcta"; return(new HttpResponseMessage() { Content = new ObjectContent <ApiReply>(reply, new JsonMediaTypeFormatter(), "application/json") }); }
public async Task GetSingleEntityErrorTest() { HttpClientFactoryMock mock = CreateMock(HttpStatusCode.InternalServerError, new NotifyException("test-error")); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply <Card> reply = await connector.GetAsync <Card>(1); TestApiReply(reply, false, "test-error", HttpStatusCode.InternalServerError); Assert.IsNull(reply.Result); }
public void Deve_retornar_falso_quando_apireply_preenchido() { var command = new ApiReply() { Data = "2019-07-16", Mensagem = "Sucesso", StatusCode = 200, Sucesso = true }; command.Validar(); Assert.IsFalse(command.Notifications.Any()); }
private async Task DeleteCoreAsync(TEntity entity) { ApiReply reply = await ApiConnector.DeleteAsync(entity); if (reply.WasSuccessful) { NotificationMessageProvider.ShowSuccessMessage(Messages.EntityDeleted.FormatWith(entity.GetDisplayName())); OnDeletedAction?.Invoke(entity); } else { NotificationMessageProvider.ShowErrorMessage(reply.ResultMessage); } IsEnabled = true; }
/// <summary> /// Tries to sign up /// </summary> protected override async Task SubmitAsyncCore() { ApiReply <User> reply = await ApiConnector.PostAsync <User>("Users/Signup", User); if (reply.WasSuccessful) { await AuthenticationStateProvider.MarkUserAsAuthenticated(reply.Result); NavigationManager.NavigateTo("/"); } else { ErrorMessage = reply.ResultMessage; } }
public async Task DeleteEntityErrorTest() { Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock(HttpStatusCode.InternalServerError, new NotifyException("test-error")); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply reply = await connector.DeleteAsync(card); TestApiReply(reply, false, "test-error", HttpStatusCode.InternalServerError); }
public async Task GetEntitiesErrorTest() { HttpClientFactoryMock mock = CreateMock(HttpStatusCode.InternalServerError, new NotifyException("test-error")); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; Dictionary <string, object> parameters = new Dictionary <string, object>() { { "test", 1 } }; ApiReply <List <Card> > reply = await connector.GetAsync <Card>(parameters); TestApiReply(reply, false, "test-error", HttpStatusCode.InternalServerError); Assert.IsNull(reply.Result); }
public async Task GetSingleEntityTest() { Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock(HttpStatusCode.OK, card); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply <Card> reply = await connector.GetAsync <Card>(1); TestApiReply(reply, true, null, HttpStatusCode.OK); Assert.AreEqual(card.CardId, reply.Result.CardId); TestRequest(mock, "Cards/1", HttpMethod.Get, user.AccessToken); }
public async Task DeleteEntityTest() { Card card = new Card() { CardId = 1 }; HttpClientFactoryMock mock = CreateMock <object>(HttpStatusCode.OK, null); ApiConnector connector = new ApiConnector(mock) { CurrentUser = user }; ApiReply reply = await connector.DeleteAsync(card); TestApiReply(reply, true, null, HttpStatusCode.OK); HttpRequestMessage request = TestRequest(mock, "Cards", HttpMethod.Delete, user.AccessToken); string requestBody = await request.Content.ReadAsStringAsync(); Card card1 = JsonConvert.DeserializeObject <Card>(requestBody); Assert.AreEqual(card.CardId, card1.CardId); }
///<inheritdoc/> public override async Task <AuthenticationState> GetAuthenticationStateAsync() { string accessToken = await localStorageService.GetItemAsync <string>("accessToken"); string refreshToken = await localStorageService.GetItemAsync <string>("refreshToken"); ClaimsIdentity identity = new ClaimsIdentity(); apiConnector.CurrentUser = null; if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(refreshToken)) { ApiReply <User> reply = await apiConnector.PostAsync <User>("Users/GetUserByAccessToken", accessToken); if (reply.WasSuccessful) { User user = reply.Result; user.AccessToken = accessToken; user.RefreshToken = refreshToken; apiConnector.CurrentUser = reply.Result; identity = GetClaimsIdentity(reply.Result); } else { apiConnector.CurrentUser = null; } } if (apiConnector.CurrentUser == null) { navigationManager.NavigateTo("/Login"); } ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity); NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal))); return(new AuthenticationState(claimsPrincipal)); }
/// <summary> /// Loads the Entity /// </summary> protected virtual async Task <bool> LoadEntityAsync() { ApiReply <TEntity> reply = await ApiConnector.GetAsync <TEntity>(Id); if (reply.WasSuccessful) { Entity = reply.Result; return(true); } else { if (reply.StatusCode == System.Net.HttpStatusCode.NotFound) { NotificationMessageProvider.ShowErrorMessage( Errors.EntityDoesNotExist.FormatWith(EntityNameHelper.GetName <TEntity>(), Id)); } else { NotificationMessageProvider.ShowErrorMessage(reply.ResultMessage); } return(false); } }
public ApiReply getStore(int id_user, int id_store) { ApiReply reply = new ApiReply(); reply.result = 0; try { using (AlmacenDBEntities db = new AlmacenDBEntities()) { List <StoreViewModel> oStore = (from st in db.store from su in db.user_store where su.id_user == id_user && st.id == su.id_store && st.id != id_store select new StoreViewModel { id = st.id, name = st.name }).ToList(); //Envia respuesta a usuario reply.result = 0; if (oStore.Count > 0) { reply.message = "Tiendas disponibles"; reply.data = oStore; } else { reply.message = "Solo cuentas con el almacen actual"; } } } catch (Exception ex) { reply.message = "Ocurrio un error en el servidor"; } return(reply); }
private void TestApiReply(ApiReply reply, bool successful, string expectedMessage, HttpStatusCode statusCode) { Assert.AreEqual(successful, reply.WasSuccessful); Assert.AreEqual(expectedMessage, reply.ResultMessage); Assert.AreEqual(statusCode, reply.StatusCode); }