public async Task <IEnumerable <Cotizacion> > Get(string idCiudad, string fechaHoraRetiro, string fechaHoraDevolucion)
        {
            try
            {
                _logger.LogInformation("Inicio");

                var client = new TinyRestClient(new HttpClient(), _config["url_api_proveedor"]);

                List <Cotizacion> arregloVacio = new List <Cotizacion>();

                var cotizaciones = await client.

                                   GetRequest("Vehiculos/cotizar").
                                   AddQueryParameter("idCiudad", idCiudad).
                                   AddQueryParameter("fechaHoraRetiro", fechaHoraRetiro).
                                   AddQueryParameter("fechaHoraDevolucion", fechaHoraDevolucion).
                                   WithOAuthBearer(await AuthorizationHelper.ObtenerAccessToken()).
                                   ExecuteAsync <List <Cotizacion> >();

                Console.WriteLine("string cotizaciones:", cotizaciones);
                if (cotizaciones == null)
                {
                    return(arregloVacio);
                }
                else
                {
                    return(cotizaciones);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.Message);
                return(null);
            }
        }
        bool isVPN(string ip, Entity player)
        {
            ignoredPlayers = System.IO.File.ReadAllLines(ignoredPlayersTxt);
            foreach (string ignoredPlayer in ignoredPlayers)
            {
                if (player.Name == ignoredPlayer)
                {
                    WriteLog.Info($"{player.Name} has a VPN but they have been ignored.");
                    return(false);
                }
            }

            var client = new TinyRestClient(new HttpClient(), "http://v2.api.iphub.info");

            var response = client.GetRequest($"ip/{ip}")
                           .AddHeader("X-Key", API_KEY)
                           .ExecuteAsStringAsync();

            Dictionary <string, object> result = JsonConvert.DeserializeObject <Dictionary <string, object> >(response.Result);

            if (result["block"].ToString() == "1")
            {
                return(true);
            }
            else
            {
                addToPlayersInGame(player);
                return(false);
            }
        }
예제 #3
0
        public async Task <IEnumerable <Ciudad> > Get()
        {
            try
            {
                _logger.LogInformation("Inicio");

                // Consumir API Proveedor
                // Creamos una instancia de Client TinyRestClient,
                // indicando la url base de la API que queremos consumir
                var client = new TinyRestClient(new HttpClient(), _config["url_api_proveedor"]);
                // El metodo GetRequest prepara el request HTTP a
                // la API en cuestion, en este caso /ciudades
                var ciudades = await client.
                               // El metodo GetRequest prepara el request HTTP a la API en cuestion, en este caso /ciudades
                               GetRequest("Ciudades").
                               //Para agregar parametros en el request
                               AddQueryParameter("name", "valor").
                               //Agregamos el Token OAuth 2.0
                               WithOAuthBearer(await AuthorizationHelper.ObtenerAccessToken()).
                               // El metodo ExecuteAsync ejecuta la peticio HTTP y con la
                               // respuesta construye una lista de Ciudades (List<Ciudad>)
                               ExecuteAsync <List <Ciudad> >();

                return(ciudades);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.Message);
                return(null);
            }
        }
예제 #4
0
        private static async Task SendRequestAsync()
        {
            await Console.Out.WriteLineAsync("Sending request...");

            var client = new TinyRestClient(Client, "http://paycortaxcredintfnquarterly.trafficmanager.net/api");

            client.Settings.DefaultHeaders.AddBearer(BearerToken.Value);

            var response = await client.PostRequest("v1/manualrequest")
                           .AddContent(
                new ManualRequest
            {
                Id         = Guid.NewGuid(),
                EventType  = "Payroll.Payrun.Distributed",
                ClientId   = 207002,
                PlannerUid = 15184521809082
            })
                           .AllowAnyHttpStatusCode()
                           .ExecuteAsync <HttpResponseMessage>();

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                BearerToken = new Lazy <string>(() => GetBearerTokenAsync().Result);
            }
            else
            {
                Debug.Assert(response.IsSuccessStatusCode);
            }
        }
예제 #5
0
        public async Task <IEnumerable <ReservasData> > Get()
        {
            try
            {
                _logger.LogInformation("Inicio");

                var client = new TinyRestClient(new HttpClient(), _config["url_api_proveedor"]);

                var reservas = await client.

                               GetRequest("Reservas").
                               WithOAuthBearer(await AuthorizationHelper.ObtenerAccessToken()).
                               ExecuteAsync <List <Reserva> >();

                List <ScanCondition> condiciones      = new List <ScanCondition>();
                List <ReservasData>  reservas_cliente = await _context.ScanAsync <ReservasData>(condiciones).GetRemainingAsync();


                return(reservas_cliente);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.Message);
                return(null);
            }
        }
예제 #6
0
        private void DoGetRequest(String RouterPath = null)
        {
            Task.Run(action: async() =>
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;

                client = new TinyRestClient(new HttpClient(), ApiUrl);
                client.Settings.DefaultHeaders.Add("Accept", "application/json");
                client.Settings.DefaultHeaders.Add("User-Agent", "Admin Client 1.0");
                client.Settings.DefaultHeaders.AddBearer("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMiJ9.PbGhl-f91Mc537CmVSrCHnah0qB-ze7c3orXaKwshZk");
                // client.Settings.Formatters.OfType<JsonFormatter>().First().UseKebabCase();

                try
                {
                    // String response = await client.GetRequest(RouterPath).ExecuteAsStringAsync();
                    // JObject json = JObject.Parse(response);

                    JObject output = await client.GetRequest(RouterPath).ExecuteAsync <JObject>();
                    WriteToFile(output.ToString());
                }
                catch (HttpException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
                {
                    WriteToFile($"{ex.Message} {ex.ReasonPhrase}");
                }
                catch (HttpException ex) when(ex.StatusCode == HttpStatusCode.InternalServerError)
                {
                    WriteToFile($"{ex.Message} {ex.ReasonPhrase}");
                }
                catch (Exception ex)
                {
                    WriteToFile($"{ex.Message}");
                }
            });
        }
예제 #7
0
        private void DoFormPostRequest(String RouterPath = null)
        {
            Task.Run(action: async() =>
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;

                client = new TinyRestClient(new HttpClient(), ApiUrl);
                client.Settings.DefaultHeaders.Add("Accept", "application/json");
                client.Settings.DefaultHeaders.Add("User-Agent", "Admin Client 1.0");
                try
                {
                    Dictionary <String, String> FormData = new Dictionary <String, String>()
                    {
                        { "username", "davchezt" },
                        { "password", "4Bahagia4" },
                        { "login", "true" }
                    };

                    JObject output = await client.PostRequest(RouterPath)
                                     .AddFormParameters(FormData)
                                     .ExecuteAsync <JObject>();

                    WriteToFile(output.ToString());
                }
                catch (HttpException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
                {
                    WriteToFile($"{ex.Message} {ex.ReasonPhrase}");
                }
                catch (HttpException ex) when(ex.StatusCode == HttpStatusCode.InternalServerError)
                {
                    WriteToFile($"{ex.Message} {ex.ReasonPhrase}");
                }
            });
        }
예제 #8
0
 public Manager(ClientConfig config)
 {
     _config     = config;
     _log        = Log.Create("manager", config.BackupPath);
     _restClient = new TinyRestClient(new HttpClient(), _config.BaseEndpoint);
     _restClient.Settings.Formatters.OfType <JsonFormatter>().First().UseCamelCase();
     _restClient.Settings.DefaultTimeout = TimeSpan.FromSeconds(120);
     _downloadTaskStopwatch.Restart();
 }
예제 #9
0
        public async Task <IActionResult> Post([FromBody] ReservasResponse reservasResponse)
        {
            try
            {
                ReservasData reservasData = new ReservasData()
                {
                    CodigoReserva    = "123132",
                    idCotizacion     = "12331312",
                    FechaHoraReserva = "2020-09-12T00:00:00",
                    UsuarioReserva   = "12223",
                    TotalReserva     = "8787"
                };

                await _context.SaveAsync <ReservasData>(reservasData);

                _logger.LogInformation("Post Reserva");
                Pasajero pasajero1 = new Pasajero()
                {
                    Nombre   = "Juan",
                    Apellido = "Perez",
                    Dni      = "12312312",
                    Telefono = "351222522",
                    Email    = "*****@*****.**"
                };

                ReservasResponse reserva1 = new ReservasResponse()
                {
                    idCotizacion = "b7538f04-aace-4d6d-a108-7e31bb165c57",
                    pasajero     = pasajero1
                };


                var client = new TinyRestClient(new HttpClient(), _config["url_api_proveedor"]);

                _logger.LogInformation("Empieza acá... RESERVA1:", reserva1);
                Console.WriteLine("RESERFVA:", reserva1);

                var data = new { IdCotizacion = reserva1.idCotizacion, Pasajero = reserva1.pasajero };



                var response = await client.
                               PostRequest("Reservas", data).
                               WithOAuthBearer(await AuthorizationHelper.ObtenerAccessToken()).
                               ExecuteAsync <IActionResult>();



                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.Message);
                return(null);
            }
        }
예제 #10
0
        protected TinyRestClient GetClient()
        {
            lock (_toLock)
            {
                if (_client == null)
                {
                    _client = new TinyRestClient(Program.Client, _serverUrl);
                }
            }

            return(_client);
        }
예제 #11
0
        public static TinyRestClient GetClient()
        {
            lock (_toLock)
            {
                if (_client == null)
                {
                    _client = new TinyRestClient(Program.Client, _serverUrl);
                    _client.Settings.Listeners.AddPostman("tests");
                }
            }

            return(_client);
        }
예제 #12
0
        private UpdaterCourse()
        {
            dbContext    = new DataContext();
            serverAPIkey = ConfigurationSettings.AppSettings[API_KEY_NAME];
            var m_serverName = ConfigurationSettings.AppSettings[API_SERVER_KEY_NAME];

            if (string.IsNullOrEmpty(serverAPIkey) || string.IsNullOrEmpty(m_serverName))
            {
                throw new Exception("Server or key not found.");
            }

            restClient = new TinyRestClient(new HttpClient(), m_serverName);
        }
예제 #13
0
        public static TinyRestClient GetClientXML()
        {
            lock (_toLock)
            {
                if (_clientXML == null)
                {
                    _clientXML = new TinyRestClient(Program.Client, _serverUrl);

                    var xmlFormatter  = _clientXML.Settings.Formatters.Where(f => f is XmlFormatter).First();
                    var jsonFormatter = _clientXML.Settings.Formatters.Where(f => f is JsonFormatter).First();
                    _clientXML.Settings.Formatters.Add(new XmlFormatter(), true);
                    _clientXML.Settings.Formatters.Remove(jsonFormatter);
                    _clientXML.Settings.Formatters.Remove(xmlFormatter);
                }
            }

            return(_clientXML);
        }
예제 #14
0
        private static async Task <int> DownloadListToFile(Options opts)
        {
            using (var httpClientHandler = new HttpClientHandler())
            {
                httpClientHandler.ServerCertificateCustomValidationCallback = CertValidation.IsExpectedCert;
                using (var httpClient = new HttpClient(httpClientHandler))
                {
                    var client = new TinyRestClient(httpClient, ccUrl);

                    client.Settings.DefaultHeaders.AddBasicAuthentication(opts.User, opts.Password);
                    var list = await client.GetRequest().ExecuteAsStringAsync();

                    File.WriteAllText(opts.Output, list);
                }
            }

            return(ExitSuccess);
        }
예제 #15
0
        public async static Task <string> ObtenerAccessToken()
        {
            if (accessToken == null)
            {
                var clientOAuth = new TinyRestClient(new HttpClient(), "https://dev-utn-frc-iaew.auth0.com/oauth");

                var request = new OAuthRequest()
                {
                    audience      = "https://www.example.com/reservas",
                    client_id     = "Gd23b2IQ7awzx1PueJw2XhZSL9HAD6wT",
                    client_secret = "gao2QIPgFpmFRKRjRn6tfHwFTLQLmqin77wwC-XOM5Vi6P57KHV14nQIYITZaZr_",
                    grant_type    = "client_credentials"
                };

                accessToken = await clientOAuth.PostRequest("token", request).
                              ExecuteAsync <OAuthAccessToken>();
            }

            return(accessToken.access_token);
        }
        public async Task <IEnumerable <Ciudad> > Get()
        {
            try
            {
                _logger.LogInformation("Inicio");

                var client   = new TinyRestClient(new HttpClient(), _config["url_api_proveedor"]);
                var ciudades = await client.
                               GetRequest("Ciudades").
                               WithOAuthBearer(await AuthorizationHelper.ObtenerAccessToken()).
                               ExecuteAsync <List <Ciudad> >();

                return(ciudades);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.Message);
                return(null);
            }
        }
        public async static Task <string> ObtenerAccessToken()
        {
            if (accessToken == null)
            {
                var clientOAuth = new TinyRestClient(new HttpClient(), _config["OAuth0::UrlAuth0"]);

                var request = new OAuthRequest()
                {
                    audience      = _config["OAuth0::Audience"],
                    client_id     = _config["OAuth0::ClientId"],
                    client_secret = _config["OAuth0::ClientSecret"],
                    grant_type    = "client_credentials"
                };

                accessToken = await clientOAuth.PostRequest("token", request).
                              ExecuteAsync <OAuthAccessToken>();
            }

            return(accessToken.access_token);
        }
 public SalesforceApiWebService(IConfiguration configuration)
 {
     Configuration = configuration;
     Client        = new TinyRestClient(new HttpClient(), Configuration["WebServices:SalesforceApi:Endpoint"]);
     ConfigureClient();
 }
예제 #19
0
 public PostmanService()
 {
     Client = new TinyRestClient(new HttpClient(), "https://api.getpostman.com/");
     Client.Settings.DefaultHeaders.Add("X-Api-Key", "88d96b1dbe8946ecaecee62807879e86");
 }
예제 #20
0
 /// <inheritdoc/>
 public LaunchpadApiRepository()
 {
     this._client = new TinyRestClient(new HttpClient(), LaunchPadUri);
     this._client.Settings.Formatters.OfType <JsonFormatter>().First().UseSnakeCase();
 }
예제 #21
0
 public static void InitalizeClient()
 {
     ApiClient = new TinyRestClient(new HttpClient(), "https://vehiclelocations.azurewebsites.net/api/");
 }
 public ExchangeRateWebService(IConfiguration configuration)
 {
     Client = new TinyRestClient(new HttpClient(), configuration["WebServices:CurrencyExchangeRates:Endpoint"]);
 }