private List <Product> GetProducts() { string endpoint = Startup.SettingFactory()["IGDB:endpoint"]; string userkey = Startup.SettingFactory()["IGDB:user-key"]; string url = "https://api-" + endpoint + ".apicast.io/games/"; Task <HttpResponse <string> > jsonResponse = Unirest.get(url + "?fields=id,name,cover,summary,first_release_date,updated_at,genres,rating,screenshots,release_dates,esrb&limit=30&order=rating:desc&filter[release_dates.platform][any]=6,48,49&filter[cover][exists]&filter[esrb.rating][eq]=6&filter[first_release_date][gt]=2013-01-01&filter[category][eq]=0") .header("user-key", userkey) .header("Accept", "application/json") .asJsonAsync <string>(); var x = jsonResponse.Result.Body; var model = JsonConvert.DeserializeObject <List <Product> >(jsonResponse.Result.Body); return(model); }
private void Detect(string filename) { mashapeAuthKey = ConfigurationSettings.AppSettings["MashapeAuthKey"]; byte[] data = File.ReadAllBytes(filename); HttpResponse <string> response = Unirest.post("https://lambda-face-recognition.p.mashape.com/detect") .header("X-Mashape-Authorization", mashapeAuthKey) .field("files", data) .asString(); string output = response.Body; MessageBox.Show(output); }
/// <summary> /// Deletes a label from a project. API Function request is by name, label has no ID field. /// </summary> /// <param name="_Config"></param> /// <param name="_Project"></param> /// <param name="_Label"></param> public static void Delete(Config _Config, Project _Project, Label _Label) { string URI = _Config.APIUrl + "projects/" + _Project.id.ToString() + "/labels/" + "?name=" + HttpUtility.UrlEncode(_Label.name); HttpResponse <string> R = Unirest.post(URI) .header("accept", "application/json") .header("PRIVATE-TOKEN", _Config.APIKey) .asString(); if (R.Code < 200 || R.Code >= 300) { throw new GitLabServerErrorException(R.Body, R.Code); } }
/// <summary> /// Uploads an image to imgur /// </summary> /// <param name="img">The image to be uploaded</param> /// <returns>The link to the image</returns> public static async Task <string> PostToImgur(byte[] buffer) { var r = Unirest.post("https://api.imgur.com/3/image") .header("authorization", $"Client-ID {Secret.ImgurClientId}") .field("image", buffer) .field("type", "file") .asJsonAsync <ImgurResponse <ImageDetails> >().Result; if (!r.Body.Success) { throw new Exception("Error when uploading imgur."); } return(r.Body.Data.Link); }
// GET: API public static Rootobject GetWeather(string lat, string lon) { string apiUrl = "https://simple-weather.p.mashape.com/weatherdata?"; string repUrl = apiUrl + "lat=" + lat + "&lng=" + lon; Task <HttpResponse <string> > response = Unirest.get(repUrl) .header("X-Mashape-Key", "MjvESZoQ1zmsh4mAPB13PdSiaFhkp1l6vHpjsnZm5dLZn4qD9b") .header("Accept", "application/json") .asJsonAsync <string>(); string r = response.Result.Body; var rootresult = JsonConvert.DeserializeObject <Rootobject>(r); return(rootresult); }
static void Main(string[] args) { var getStr = "https://karlroos-systemet.p.mashape.com/product?&order=ASC&order_by=price"; HttpResponse <string> response = Unirest.get(getStr) .header("X-Mashape-Key", "KlCvBh2xRUmshTOZHDrBJFDe410Pp1b8YU8jsnscTwJ8nGcDqL") .header("Accept", "application/json") .asJson <string>(); var json = response.Body; var serializer = new JavaScriptSerializer(); var drinks = serializer.Deserialize <RootObject[]>(json); Console.ReadLine(); }
public Recipe SearchRecipe(string diet, string excludeIngredients, string intolerances, int numberOfRecipes, string type, string query) { var response = Unirest.get("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/search?" + "diet=" + diet + "&excludeIngredients=" + System.Web.HttpUtility.UrlEncode(excludeIngredients) + "&intolerances=" + System.Web.HttpUtility.UrlEncode(intolerances) + "&number=" + numberOfRecipes + "&offset=0&type=" + System.Web.HttpUtility.UrlEncode(type) + "&query=" + System.Web.HttpUtility.UrlEncode(query)) .header("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "82e89ff980msh7da50a51185a3a1p10ddf2jsnc8633e45f495") .asJson <Recipe>().Body; return(response); }
/// <summary> /// List all webhooks for a project /// </summary> /// <param name="_Config"></param> /// <param name="_Project"></param> /// <returns></returns> public static List <Webhook> List(Config _Config, Project _Project) { List <Webhook> RetVal = new List <Webhook>(); try { int page = 1; List <Webhook> webhooks = new List <Webhook>(); do { webhooks.Clear(); string URI = _Config.APIUrl + "projects/" + _Project.id + "/hooks"; URI += "?per_page=100" + "&page=" + page.ToString(); HttpResponse <string> R = Unirest.get(URI) .header("accept", "application/json") .header("PRIVATE-TOKEN", _Config.APIKey) .asString(); if (R.Code < 200 || R.Code >= 300) { throw new GitLabServerErrorException(R.Body, R.Code); } else { dynamic Result = JsonConvert.DeserializeObject(R.Body); if (Result is JArray) { JArray ResultArray = (JArray)Result; foreach (JToken Token in ResultArray) { Webhook W = JsonConvert.DeserializeObject <Webhook>(Token.ToString()); webhooks.Add(W); } } } page++; RetVal.AddRange(webhooks); }while (webhooks.Count > 0 & page < 100); } catch (Exception ex) { throw ex; } return(RetVal); }
/// <summary> /// Query projects by name /// </summary> /// <param name="_Config"></param> /// <returns></returns> public static List <Project> Search(Config _Config, string Query) { List <Project> RetVal = new List <Project>(); try { int page = 1; List <Project> projects = new List <Project>(); do { projects.Clear(); HttpResponse <string> R = Unirest.get (_Config.APIUrl + "projects/search/" + HttpUtility.UrlEncode(Query) + "?per_page=100" + "&page=" + page.ToString()) .header("accept", "application/json") .header("PRIVATE-TOKEN", _Config.APIKey) .asString(); if (R.Code < 200 || R.Code >= 300) { throw new GitLabServerErrorException(R.Body, R.Code); } else { dynamic Result = JsonConvert.DeserializeObject(R.Body); if (Result is JArray) { JArray ResultArray = (JArray)Result; foreach (JToken Token in ResultArray) { Project P = JsonConvert.DeserializeObject <Project>(Token.ToString()); projects.Add(P); } } } page++; RetVal.AddRange(projects); }while (projects.Count > 0 & page < 100); } catch (Exception ex) { throw ex; } return(RetVal); }
/// <summary> /// List all users that the current user can see /// </summary> /// <param name="_Config">A GitLab.NET Configuration object</param> /// <returns></returns> public static List <User> List(Config _Config, GitLab _Parent = null) { List <User> RetVal = new List <User>(); try { int page = 1; List <User> users = new List <User>(); do { users.Clear(); string URI = _Config.APIUrl + "users?per_page=100" + "&page=" + page.ToString(); HttpResponse <string> R = Unirest.get(URI) .header("accept", "application/json") .header("PRIVATE-TOKEN", _Config.APIKey) .asString(); if (R.Code < 200 || R.Code >= 300) { throw new GitLabServerErrorException(R.Body, R.Code); } else { dynamic Result = JsonConvert.DeserializeObject(R.Body); if (Result is JArray) { JArray ResultArray = (JArray)Result; foreach (JToken Token in ResultArray) { User U = JsonConvert.DeserializeObject <User>(Token.ToString()); U.SetParent(_Parent); users.Add(U); } } } page++; RetVal.AddRange(users); }while (users.Count > 0 & page < 100); } catch (Exception ex) { throw ex; } return(RetVal); }
private AnimetricsEnrollResponse EnrollFace(KeyValuePair <string, AnimetricsDetectResponse> entry) { HttpResponse <string> response = Unirest.post(BaseUrl + "detect") .header("Accept", "application/json") .field("api_key", ApiKeys.GetCurrentKey()) .field("subject_id", entry.Key) .field("gallery_id", GalleryId) .field("image_id", entry.Value.images[0].image_id) .field("topLeftX", entry.Value.images[0].faces[0].topLeftX) .field("topLeftY", entry.Value.images[0].faces[0].topLeftY) .field("width", entry.Value.images[0].width) .field("height", entry.Value.images[0].height) .asString(); return(JsonConvert.DeserializeObject <AnimetricsEnrollResponse>(response.Body)); }
/// <summary> /// makes a get call using Unirest. Returns response as string. /// </summary> /// <param name="url"></param> /// <param name="token"></param> /// <returns>string of the JSON data</returns> public static string Get(string url, string token) { string body = ""; try { HttpResponse <string> jsonReponse = Unirest.get(url) .header("accept", "application/json") .header("Authorization", "Bearer " + token) .asJson <string>(); body = jsonReponse.Body.ToString(); return(body); } catch (Exception ex) { Console.WriteLine(ex); return(body); } }
/// <summary> /// isAddressValid is a method that allows to check the validity of an address against a certain DID’s type and country. This can be useful if you have originally created an address for a given DID and you wish to reuse that same address for another DID. /// </summary> /// <param name="didType">Required parameter: The did type for the destination did.</param> /// <param name="destinationCountryCodeA3">Required parameter: The three letter identifier for country the destination did.</param> /// <param name="regulationAddressId">Required parameter: The identifier of the regulation address.</param> /// <return>Returns the dynamic response from the API call</return> public async Task <dynamic> GetIsAddressValidAsync( string didType, string destinationCountryCodeA3, string regulationAddressId) { //the base uri for api requests string baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder queryBuilder = new StringBuilder(baseUri); queryBuilder.Append("/services/rest/regulation/address/{regulationAddressId}/validation"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(queryBuilder, new Dictionary <string, object>() { { "regulationAddressId", regulationAddressId } }); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary <string, object>() { { "didType", didType }, { "destinationCountryCodeA3", destinationCountryCodeA3 } }); //validate and preprocess url string queryUrl = APIHelper.CleanUrl(queryBuilder); //prepare and invoke the API call request to fetch the response HttpRequest request = Unirest.get(queryUrl) //append request with appropriate headers and parameters .header("User-Agent", "APIMATIC 2.0") .header("Accept", "application/json") .basicAuth(basicAuthUserName, basicAuthPassword); //invoke request and get response HttpResponse <String> response = await request.asStringAsync(); //Error handling using HTTP status codes if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK { throw new APIException(@"HTTP Response Not OK", response.Code); } return(APIHelper.JsonDeserialize <dynamic>(response.Body)); }
private void load() { var responsedhy = Unirest.get("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/uk2/v1.0/%2F" + ms + "?pageIndex=0&pageSize=10") .header("X-RapidAPI-Key", "107dc24922mshbd9bd597451997fp19a55fjsnc869fe1003a4") .asJson <string>(); res = JsonConvert.DeserializeObject <Info>(responsedhy.Body); Console.WriteLine(res.Itineraries[0].PricingOptions[0].Price); int ag = res.Itineraries[0].PricingOptions[0].Agents[0]; foreach (var item in res.Itineraries) { Useful newo = new Useful(); Itineraries.Add(item); newo.Price = $"{item.PricingOptions[0].Price}$"; newo.OutboundLegId = item.OutboundLegId; var value = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).OriginStation; var value2 = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).DestinationStation; newo.Duration = $"{ res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Duration / 60}h { res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Duration%60} "; newo.Deals = $"{item.PricingOptions.Count} deals"; var photo = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Carriers[0]; newo.Photo = res.Carriers.First(itemm => itemm.Id == photo).ImageUrl; if (res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).SegmentIds.Count == 2) { newo.Mode = "Direct"; } else { newo.Mode = $"{(res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).SegmentIds.Count - 2).ToString()} stop"; } newo.Departuretime = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Departure.Split('T').Last();; newo.Departuredate = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Departure.Split('T').First();; newo.Arrival = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Arrival.Split('T').Last(); newo.ArrivalDate = res.Legs.First(itemm => itemm.Id == newo.OutboundLegId).Arrival.Split('T').First(); newo.OriginPlace = res.Places.First(itemm => itemm.Id == value).Code; newo.DestPlace = res.Places.First(itemm => itemm.Id == value2).Code; newo.Destcity = res.Places.First(itemm => itemm.Id == value2).Name; Application.Current.Dispatcher.Invoke(new Action(() => { Infos.Add(newo); })); //Infos.Add(newo); } }
/// <summary> /// listCapacityGroup is a method that allows you to get the list of your capacity groups. /// </summary> /// <param name="pageNumber">Required parameter: The page number, starting at 0.</param> /// <param name="pageSize">Required parameter: The page size (max number of entities that are displayed in the response).</param> /// <param name="capacityGroupId">Optional parameter: The identifier of the capacity group to search for.</param> /// <param name="description">Optional parameter: The description of the capacity group.</param> /// <param name="e164">Optional parameter: The e164 bound to the capacity group.</param> /// <return>Returns the dynamic response from the API call</return> public async Task <dynamic> ListCapacityGroupAsync( string pageNumber, string pageSize, string capacityGroupId = null, string description = null, string e164 = null) { //the base uri for api requests string baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder queryBuilder = new StringBuilder(baseUri); queryBuilder.Append("/services/rest/configuration/capacitygroup"); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary <string, object>() { { "pageNumber", pageNumber }, { "pageSize", pageSize }, { "capacityGroupId", capacityGroupId }, { "description", description }, { "e164", e164 } }); //validate and preprocess url string queryUrl = APIHelper.CleanUrl(queryBuilder); //prepare and invoke the API call request to fetch the response HttpRequest request = Unirest.get(queryUrl) //append request with appropriate headers and parameters .header("User-Agent", "APIMATIC 2.0") .header("Accept", "application/json") .basicAuth(basicAuthUserName, basicAuthPassword); //invoke request and get response HttpResponse <String> response = await request.asStringAsync(); //Error handling using HTTP status codes if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK { throw new APIException(@"HTTP Response Not OK", response.Code); } return(APIHelper.JsonDeserialize <dynamic>(response.Body)); }
/// <summary> /// Gets the item ID for a name that may not be exact /// </summary> /// <param name="name">The name of the item</param> /// <returns>The id of that belongs to the item name or null</returns> public static async Task <NameId> FuzzyMatchName(string name) { using (var db = new Database()) { // Checking if name is in DB var correct = await db.Database.SqlQuery <NameId>( "SELECT Id, Name " + "FROM items " + "WHERE LOWER(Name) = @p0 " + "OR SOUNDEX(Name) = SOUNDEX(@p0) " + "LIMIT 1", name) .FirstOrDefaultAsync(); // Found name if (correct != null) { return(correct); } // Getting item name from site var data = await Unirest.get($"http://rscript.org/lookup.php?type=ge&search={name.UrlEncode()}&exact=1") .asStringAsync(); // Getting item name from weird return data var matchId = Regex.Match(data.Body, @"\nIID:\s(\d+)(?:$|\n)").Groups[1]; var matchName = Regex.Match(data.Body, @"\nITEM:\s\d+\s(.+?)\s").Groups[1]; // Found name if (matchId.Success && matchName.Success) { return new NameId { Name = matchName.Value.Replace("_", " "), Id = matchId.Value.ToInt() } } ; // Fuzzy matching the DB very slowly correct = await db.Database.SqlQuery <NameId>( "SELECT Id, Name " + "FROM items " + "ORDER BY sys.jaro_winkler(Name, @p0) DESC " + "LIMIT 1", name) .FirstOrDefaultAsync(); return(correct); } }
public IList <CountryDescription> SlowHttpCall() { try { System.Threading.Thread.Sleep(1000); var jsonResponse = Unirest // .get(CountryInformationServiceUrl) .header("accept", "application/json") .asString(); var body = jsonResponse.Body; return(JsonConvert.DeserializeObject <CountryDescription[]>(body)); } catch (Exception e) { throw new RestCountriesAPIException("Could not read country information from " + CountryInformationServiceUrl, e); } }
//this code doesn't really touch the Ui(in terms of updating) so a dispatcher isn't necessary. DIspatcher is used to //when the code is within an async method, but it updates the Ui, meaning that the Ui thread is used. It would crash w/o it. //All it does is update the database of weatherData, making no changes to UI. Ui changes are all made in viewModel at this time. //Use Thread.Sleep(); too see if the async method is properly working. Result is that the UI should not freeze up. public async Task <string> GetWeatherDataAsync() { return(await Task.Run(() => { if (CityLocation != null && CountryLocation != null) { Task <HttpResponse <string> > jsonResponse = Unirest.get("https://community-open-weather-map.p.rapidapi.com/weather?callback=test&id=2172797&units=%22metric%22+or+%22imperial%22&mode=xml%2C+html&q=" + CityLocation + "%2C+" + CountryLocation + "&units=%22metric%22") .header("X-RapidAPI-Host", "community-open-weather-map.p.rapidapi.com") .header("X-RapidAPI-Key", "baa31766f0mshf8829a0c8da5dd9p1a932ajsn480bfe440f3b") .asJsonAsync <string>(); m_weatherData = jsonResponse.Result.Body.ToString(); } return m_weatherData; })); }
// GET: API public static Rootobject GetLocation() { string apiUrl = "https://simple-weather.p.mashape.com/weatherdata?"; string ips = GetLocalIPAddress(); Task <HttpResponse <string> > response = Unirest.get(apiUrl) .header("X-Mashape-Key", "MjvESZoQ1zmsh4mAPB13PdSiaFhkp1l6vHpjsnZm5dLZn4qD9b") .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .field("ip", ips) .field("reverse-lookup", false) .asJsonAsync <string>(); string r = response.Result.Body; var rootresult = JsonConvert.DeserializeObject <Rootobject>(r); return(rootresult); }
public async Task Corona(CommandContext commandInfo, [Description("Country name")] string name) { var response = await Unirest.get(@"https://api.covid19api.com/live/country/" + name.ToLower()) .header("Accept", "application/json") .asJsonAsync <String>(); var countries = JsonConvert.DeserializeObject <List <CoronaCountry> >(response.Body); var sumDead = countries.Sum(c => c.Deaths); var sumRecovered = countries.Sum(c => c.Recovered); var sumActive = countries.Sum(c => c.Active); var sumConfirmed = countries.Sum(c => c.Confirmed); var country = countries[0]; await commandInfo.RespondAsync($"{country.Country} :flag_{country.CountryCode.ToLower()}:\n{Emoji.SneezingFace}Active:{sumActive} \n{Emoji.Skull}Died: {sumDead} \n{Emoji.Mask}Recovered:{sumRecovered}\n{country.Date}"); }
private string GetNutritionWidget(int spoonacularProductId) { HttpResponse <string> response = Unirest.get($"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/food/products/{spoonacularProductId}/nutritionWidget") .header("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "aJW3b5eOp7mshOTu72ChE00lPeVPp1s0JOcjsntkWNySHxWWSj") .header("Accept", "text/html") .asJson <string>(); if (response.Code == 404 || response.Code == 400) { return(null); } else { return(response.Body); } }
async void GetUserInfo() { var response = await Unirest.get("http://localhost/users/" + ID).asJsonAsync <String>(); var seller = JsonConvert.DeserializeObject <List <Seller> >(response.Body); lblName.Text = seller[0].Name; lblAmount.Text = seller[0].AmountOfProducts.ToString(); lblFollowers.Text = seller[0].Followers.ToString(); lblRating.Text = seller[0].Rating.ToString(); try { pic.Load(seller[0].picURL); } catch (Exception) {} }
/// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="regNo">Required parameter: TODO: type parameter description here</param> /// <param name="color">Optional parameter: TODO: type parameter description here</param> /// <param name="cartType">Optional parameter: TODO: type parameter description here</param> /// <param name="queryParameters">Additional optional query parameters are supported by this endpoint</param> /// <return>Returns the CarInfoModel response from the API call</return> public async Task <CarInfoModel> GetCarInfoAsync( string regNo, string color = null, CarTypesEnum?cartType = null, Dictionary <string, object> queryParameters = null) { //the base uri for api requests string baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder queryBuilder = new StringBuilder(baseUri); queryBuilder.Append("/carinfo"); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary <string, object>() { { "RegNo", regNo }, { "Color", color }, { "CartType", (null != cartType) ? (int?)cartType : null } }); //append optional parameters to the query APIHelper.AppendUrlWithQueryParameters(queryBuilder, queryParameters); //validate and preprocess url string queryUrl = APIHelper.CleanUrl(queryBuilder); //prepare and invoke the API call request to fetch the response HttpRequest request = Unirest.get(queryUrl) //append request with appropriate headers and parameters .header("User-Agent", "APIMATIC 2.0") .header("Accept", "application/json"); //invoke request and get response HttpResponse <String> response = await request.asStringAsync(); //Error handling using HTTP status codes if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK { throw new APIException(@"HTTP Response Not OK", response.Code); } return(APIHelper.JsonDeserialize <CarInfoModel>(response.Body)); }
//Hämtar one-liner skämt från mashape.com public string GetJokeFromApi(string joke) { try { string errorMessage = string.Empty; //Mäter hur lång tid det tar att anropa API:t var handle = Insights.TrackTime("Time to get api call"); handle.Start(); HttpResponse <string> jsonResponse = Unirest.get("https://webknox-jokes.p.mashape.com/jokes/oneLiner") .header("X-Mashape-Key", "UMJJhgaBWumshuvL0Yrr8EhR6CfNp1bpx1Xjsnt2Gzhihdd7FF") .asJson <string>(); handle.Stop(); //Om hämtningen av skämtet lyckas if (jsonResponse.Code == 200) { string jokeRaw = jsonResponse.Body; jokeRaw = jokeRaw.Replace("text", "Joke"); jokeRaw = jokeRaw.Replace("{", ""); jokeRaw = jokeRaw.Replace("}", ""); //jokeRaw = jokeRaw.Replace("\u2019", "'"); return(jokeRaw); } //!= 200 errorMessage = "Nått gick fel, inget skämt =("; return(errorMessage); } catch (Exception ex) { ////Logga exception till insight om hämtning av skämtet inte lyckas Insights.Report(ex, new Dictionary <string, string> { { "Methodname", "GetJokeFromApi()" }, { "Where", "WebAPI.cs" } }); string errorMessage = "Something went wrong, are you sure you have a connection?"; return(errorMessage); } }
//for market history public static List <MarketHistory> SaveMarketHistory(string symbol) { const string API_KEY = "7I217NA0556LS5X8"; List <MarketHistory> marketHistory = new List <MarketHistory>(); try { HttpResponse <string> response = Unirest.get(String.Format("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={0}&apikey={1}", symbol, API_KEY)).asJson <string>(); if (response.Code != 200) { return(null); } JObject jMarketHistory = (JObject)JsonConvert.DeserializeObject(response.Body.ToString()); DateTime dailyDate; dailyDate = DateTime.Now; //initialize today's date for (int i = 0; i < jMarketHistory["Time Series (Daily)"].Count();) { //Console.WriteLine(dailyDate.ToString("yyyy-MM-dd")); if (jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")] == null) { dailyDate = dailyDate.AddDays(-1); continue; } MarketHistory dailyData = new MarketHistory(); dailyData.Open = double.Parse(jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")]["1. open"].ToString()); dailyData.High = double.Parse(jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")]["2. high"].ToString()); dailyData.Low = double.Parse(jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")]["3. low"].ToString()); dailyData.Close = double.Parse(jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")]["4. close"].ToString()); dailyData.Volume = int.Parse(jMarketHistory["Time Series (Daily)"][dailyDate.ToString("yyyy-MM-dd")]["5. volume"].ToString()); dailyData.Date = dailyDate; dailyData.Symbol = symbol; marketHistory.Add(dailyData); dailyDate = dailyDate.AddDays(-1); //step back by one day after processing every record i++; } marketHistory = marketHistory.OrderBy(t => t.Date).ToList <MarketHistory>(); Globals.Db.AddToMarketHistory(symbol, marketHistory); } catch (Exception ex) { //MessageBox.Show(ex.Message); } return(marketHistory); }
public static string RandomQuotes() { Task <HttpResponse <MyClass> > response = Unirest.get("https://sumitgohil-random-quotes-v1.p.rapidapi.com/fetch/randomQuote") .header("X-RapidAPI-Key", "bbb8e2dff4msh79f70d5bbf04ec4p172c97jsn6f5bee234637") .asJson(); string quote = ""; foreach (JToken token in a) { if (token.Path.Contains("quote") && !token.Path.Contains("quotes")) { quote = token.First.ToString(); } } return(""); }
/// <summary> /// Gets a comment by numeric ID. /// </summary> /// <param name="_Config">The _ configuration.</param> /// <param name="_MergeRequest">The _ merge request.</param> /// <param name="_ID">The _ identifier.</param> /// <returns></returns> public static Note GetComment(Config _Config, MergeRequest _MergeRequest, int _ID) { string URI = _Config.APIUrl + "projects/" + _MergeRequest.project_id.ToString() + "/merge_requests/" + _MergeRequest.id.ToString() + "/notes/" + _ID.ToString(); HttpResponse <string> R = Unirest.get(URI) .header("accept", "application/json") .header("PRIVATE-TOKEN", _Config.APIKey) .asString(); if (R.Code < 200 || R.Code >= 300) { throw new GitLabServerErrorException(R.Body, R.Code); } else { return(JsonConvert.DeserializeObject <Note>(R.Body)); } }
public async Task <string> GetBeersWithId() { var fav = new Favourites(); String data = fav.Read(); var result = data.Split(new string[] { "\\n" }, StringSplitOptions.None); string results = ""; foreach (string a in result) { string uri = $"https://api.punkapi.com/v2/beers/{a}"; HttpResponse <string> beerResults = await Unirest.get(uri).asJsonAsync <string>(); results = results + JsonConvert.DeserializeObject <object>(beerResults.Body).ToString(); } System.Diagnostics.Debug.WriteLine("dapster : " + JsonConvert.DeserializeObject <object>(results).ToString()); return(JsonConvert.DeserializeObject <object>(results).ToString()); }
public JsonRecipe GetRecipe(string ingredients) { // create url by passing in parameters string url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?"; string param_fillIngredients = "false"; string param_ingredients = ingredients; string param_limitLicense = "false"; string param_number = "1"; string param_ranking = "1"; // Request query string. var queryString = HttpUtility.ParseQueryString(string.Empty); queryString["fillIngredients"] = param_fillIngredients; queryString["ingredients"] = ingredients; queryString["limitLicense"] = param_limitLicense; queryString["number"] = param_number; queryString["ranking"] = param_ranking; var uri = url + queryString; // "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=false&ingredients=apples%2Cflour%2Csugar&limitLicense=false&number=5&ranking=1" // These code snippets use an open-source library. HttpResponse <MemoryStream> responseAPI = Unirest.get(uri) .header("X-Mashape-Key", APIKeys.Mashape_Key_Kevin) .header("Accept", "application/json") .asJson <MemoryStream>(); // System.IO.MemoryStream encoding to string StreamReader reader = new StreamReader(responseAPI.Body); string json = reader.ReadToEnd(); // Remove extra brackets on JSON string // Unsure if API is returning extra brackets or if StreamReader is adding json = json.TrimStart('['); json = json.TrimEnd(']'); // Deserialize json string into an object instance JsonRecipe recipeResult = new JsonRecipe(); JsonConvert.PopulateObject(json, recipeResult); return(recipeResult); }
public async Task Execute(object a, Message m) { var url = "http://www.runescape.com/player_count.js?varname=iPlayerCount&callback=jQuery000000000000000_0000000000&_=0"; HttpResponse <string> r = await Unirest.get(url) .asStringAsync(); // Checking if the request was successful if (r.Code < 200 || r.Code > 299) { await m.Channel.SendMessage($"Error code **{r.Code}** was returned from the server."); return; } // Getting number var jsonReadable = Regex.Match(r.Body, @"jQuery000000000000000_0000000000\((\d+?)\)").Groups[1].Value.ToInt(); await m.Channel.SendMessage($"**{jsonReadable.ToString("#,##0")}** players online"); }