Esempio n. 1
0
                /// <summary>
                /// Gets a specific comment from the Snippet by Note ID
                /// </summary>
                /// <param name="_Config">The _ configuration.</param>
                /// <param name="_Project">The _ projet.</param>
                /// <param name="_Snippet">The _ snippet.</param>
                /// <param name="_ID">The _ identifier.</param>
                /// <returns></returns>
                public static Note GetComment(Config _Config, Project _Project, Snippet _Snippet, int _ID)
                {
                    string URI = _Config.APIUrl + "projects/" + _Project.id.ToString() + "/snippets/" + _Snippet.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));
                    }
                }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
        // This code matches the HTTP Request that we included in our api controller
        public async Task <bool> checkLogin(string username, string password)
        {
            var httpClient = new HttpClient();
            // http://MainHost/api/UserCredentials/username=foo/password=foo. The api value and response value should match in order to return a true status code.
            var response = await httpClient.GetAsync(LoginWebServiceUrl + "studentID=" + username + "/" + "password="******"studentID=" + username + "/" + "password=" + password)
                                                          .asJsonAsync <string>();
                var obj = JsonConvert.DeserializeObject <Users>(response2.Result.Body);
                SessionUserCredentials.Name   = obj.Name;
                SessionUserCredentials.Points = Convert.ToInt32(obj.Points);
                SessionUserCredentials.Team   = obj.Team;
                SessionUserCredentials.Id     = obj.Id;
            }

            return(response.IsSuccessStatusCode); // return either true or false
        }
Esempio n. 4
0
        public async Task <bool> checkRegister(string username, string password, string name)
        {
            var httpClient = new HttpClient();

            var response = await httpClient.GetAsync(RegisterWebServiceUrl + "studentID=" + username + "/" + "password="******"/" + "name=" + name);

            if (response.IsSuccessStatusCode)
            {
                Task <HttpResponse <string> > response2 = Unirest.get(LoginWebServiceUrl + "studentID=" + username + "/" + "password=" + password)
                                                          .asJsonAsync <string>();
                var obj = JsonConvert.DeserializeObject <Users>(response2.Result.Body);
                SessionUserCredentials.Name   = obj.Name;
                SessionUserCredentials.Points = Convert.ToInt32(obj.Points);
                SessionUserCredentials.Team   = obj.Team;
                SessionUserCredentials.Id     = obj.Id;
            }

            return(response.IsSuccessStatusCode);
        }
Esempio n. 5
0
        /// <summary>
        /// The listCountry operation allows you to search for countries available in the Voxbone coverage.
        /// </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="countryCodeA3">Optional parameter: The three letter identifier of the country.</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task <dynamic> ListCountryAsync(
            string pageNumber,
            string pageSize,
            string countryCodeA3 = 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/inventory/country");


            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary <string, object>()
            {
                { "pageNumber", pageNumber },
                { "pageSize", pageSize },
                { "countryCodeA3", countryCodeA3 }
            });

            //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));
        }
Esempio n. 6
0
        private void playZingMp3(String zingUrl)
        {
            zingUrl = zingUrl.Replace(".html", "");
            String musicId = zingUrl.Substring(zingUrl.LastIndexOf("/") + 1);

            HttpResponse <String> response =
                Unirest.get("http://api.mp3.zing.vn/api/mobile/song/getsonginfo?requestdata={%22id%22:%22" + musicId +
                            "%22}")
                .asString();

            JObject jsonResponse = JObject.Parse(response.Body);
            String  fileName     = jsonResponse.GetValue("title").Value <String>();

            JToken token       = jsonResponse.GetValue("source");
            String downloadUrl = JObject.Parse(token.ToString()).GetValue("320").Value <String>();

            windowMedia.URL = downloadUrl;
            windowMedia.Ctlcontrols.play();
        }
Esempio n. 7
0
        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");
        }
Esempio n. 8
0
        public bool GetTokenAccess(string email, string password)
        {
            bool   resultado = true;
            string respuesta = string.Empty;
            HttpResponse <string> response = Unirest.get("https://login.microsoftonline.com/common/login").basicAuth(email, password).asJson <string>();


            if (response.Code == 200)
            {
                respuesta = response.Body;
            }
            else
            {
                resultado = false;
            }


            return(resultado);
        }
        public static void RebuildAlbum()
        {
            Cursor.Current = Cursors.WaitCursor;

            album          = ConfigurationSettings.AppSettings["Album"];
            albumKey       = ConfigurationSettings.AppSettings["AlbumKey"];
            mashapeAuthKey = ConfigurationSettings.AppSettings["MashapeAuthKey"];

            HttpResponse <string> response = Unirest.get("https://lambda-face-recognition.p.mashape.com/album_rebuild?album=" + album + "&albumkey=" + albumKey)
                                             .header("X-Mashape-Authorization", mashapeAuthKey)
                                             .asString();

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var output = jss.Deserialize <dynamic>(response.Body);

            Cursor.Current = Cursors.Default;

            MessageBox.Show(response.Body);
        }
        public static string Get(string url, string myToken)
        {
            string body = "";

            try {
                HttpResponse <string> jsonReponse = Unirest.get(url)
                                                    .header("accept", "application/json")
                                                    .header("Authorization", "Bearer " + myToken)
                                                    .asJson <string>();
                body = jsonReponse.Body.ToString();
                return(body);
            }
            catch (Exception ex) {
                //log.WriteLine(ex);
                //log.Flush();
                Console.WriteLine(ex);
                return(body);
            }
        }
Esempio n. 11
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Start ...");
            //the added Wait() causes the thread to hold until the task is finished.
            Task <HttpResponse <MyClass.RootObject> > response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/5162")
                                                                 .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
                                                                 .header("X-RapidAPI-Key", "myKey")
                                                                 .asJsonAsync <MyClass.RootObject>();


            //if need to perform other logic while you are waiting
            while (response.Status == TaskStatus.Running)
            {
                // perform other logic like gui here
            }
            var status = response.Status;

            Console.WriteLine("End ....");
        }
        public List <Media> GetMedias(string username, int count = 20, string maxId = null)
        {
            string endpoint = Endpoints.ACCOUNT_MEDIAS.Replace("{username}", username).Replace("{count}", count.ToString());

            List <Media> medias          = new List <Media>();
            bool         isMoreAvailable = true;

            while (isMoreAvailable)
            {
                // pass in maxId, if this is a loop from moreAvailable, the maxId will be the oldest post in the previous pass
                HttpResponse <string> response = Unirest.get(endpoint.Replace("{max_id}", maxId)).asString();

                // if http response is success, we will continue, if not, we cannot do much more so we will just say no more available
                // and return whatever we currently have
                if (response.Code == 200)
                {
                    MediaResponse mediaResponse = JsonConvert.DeserializeObject <MediaResponse>(response.Body);

                    // the instagram response also has a status, if ok continue
                    if (mediaResponse.status == "ok")
                    {
                        medias.AddRange(mediaResponse.items);

                        // Assumption: more_available will be false if there are ever less than specified COUNT items returned
                        // as long as that variable is correctly set, we exit the loop
                        // If there is at least one entry, we will capture the oldest one's id and set that as maxId in case
                        // we need to do another pass in the while loop
                        if (mediaResponse.items.Count() > 0)
                        {
                            maxId = mediaResponse.items.OrderBy(i => i.CreateDate).First().Id;
                        }
                    }

                    isMoreAvailable = mediaResponse.more_available;
                }
                else
                {
                    isMoreAvailable = false;
                }
            }

            return(medias);
        }
Esempio n. 13
0
        private List <string> GetVideos(int prodId)
        {
            string        endpoint = Startup.SettingFactory()["IGDB:endpoint"];
            string        userkey  = Startup.SettingFactory()["IGDB:user-key"];
            List <string> retVal   = new List <string>();

            string url = "https://api-" + endpoint + ".apicast.io/games/";
            Task <HttpResponse <string> > jsonResponse = Unirest.get(url + prodId + "?fields=videos")
                                                         .header("user-key", userkey)
                                                         .header("Accept", "application/json")
                                                         .asJsonAsync <string>();
            var x     = jsonResponse.Result.Body;
            var model = JsonConvert.DeserializeObject <List <Root> >(jsonResponse.Result.Body);

            if (model[0].videos != null && model[0].videos.Count() > 0)
            {
                retVal = model[0].videos.AsQueryable().Select(video => "https://www.youtube.com/embed/" + video.video_id).ToList();
            }
            return(retVal);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Start of Program...");

            HttpResponse <string> response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/9999")
                                             .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
                                             .header("X-RapidAPI-Key", "myKey")
                                             .asJson <string>();

            var result = response.Body;

            JObject parsedString = JObject.Parse(result);

            RootObject myGame = parsedString.ToObject <RootObject>();

            // Get game id
            Console.WriteLine(myGame.results[0].gameId);

            Console.WriteLine("End of Program....");
        }
        private SpoonProductInformation GetSpoonItem(int spoonacularProductId)
        {
            string url = $"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/food/products/{spoonacularProductId}";
            HttpResponse <string> response = Unirest.get(url)
                                             .header("X-RapidAPI-Key", "aJW3b5eOp7mshOTu72ChE00lPeVPp1s0JOcjsntkWNySHxWWSj")
                                             .asJson <string>();

            if (response.Code == 404 || response.Code == 400)
            {
                string error = "Error: type an items name in the search bar or some sort of tag, such as drinks, candy, chips, etc.";
                return(null);
            }
            else
            {
                var serializer = new JsonSerializer();
                var info       = JsonConvert.DeserializeObject <SpoonProductInformation>(response.Body);

                return(info);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Gets the price history for an item
        /// </summary>
        /// <param name="itemName">The name of the item</param>
        /// <returns>The price history of the item</returns>
        public static async Task <IDictionary <DateTime, int> > GetPriceHistory(string itemName, bool exactName = false)
        {
            if (!exactName)
            {
                itemName = (await FuzzyMatchName(itemName)).Name;
            }

            var data = await Unirest.get($"http://runescape.wikia.com/wiki/Module:Exchange/{itemName.UrlEncode()}/Data?action=raw")
                       .asStringAsync();

            // Checking if response was okay
            if (data.Code < 200 || data.Code > 299)
            {
                if (data.Code == 404)
                {
                    throw new ControlledException($"Price history for item with the name \"{itemName}\" could not be found.");
                }

                throw new HttpRequestException($"Request returned {data.Code}.");
            }

            // Converting to json
            var jsonReadable = data.Body
                               .Replace("'", "\"")
                               .Replace("return {", "[")
                               .Replace("}", "]");
            var json = JsonConvert.DeserializeObject <string[]>(jsonReadable);

            // Converting to price history
            var dic = new Dictionary <DateTime, int>();

            json.ForEach(h =>
            {
                var time  = TimeUtil.FromUnixTime(h.Split(':')[0].ToUlong());
                var price = h.Split(':')[1].ToInt();

                dic[time] = price;
            });

            return(dic);
        }
Esempio n. 17
0
        public WordDefinition getWordEntry(string word)
        {
            try
            {
                if (checkDailyLimit() == false)
                {
                    throw new Exception("Daily API calls limit reached.");
                }

                HttpResponse <string> response = Unirest.get(endpointURL + word)
                                                 .header("X-Mashape-Key", apiKey)
                                                 .header("Accept", "application/json")
                                                 .asJson <string>();

                if (response.Code == 404)
                {
                    return(null);
                }
                else if (response.Code != 200)
                {
                    throw new Exception($"WordAPI returned error {response.Code} - message:{response.Body}");
                }

                WordDefinition wdEntry = JsonConvert.DeserializeObject <WordDefinition>(response.Body, new JsonSerializerSettings
                {
                    Error = HandleDeserializationError
                });

                if (!String.IsNullOrEmpty(missingPronunciation) && wdEntry.pronunciation == null)//populate manually
                {
                    wdEntry.pronunciation     = new Pronunciation();
                    wdEntry.pronunciation.all = missingPronunciation;
                }

                return(wdEntry);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 18
0
 public List <IngredientsJson> getRecipes(String LUISIngredients)
 {
     try
     {
         string url = $"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?fillIngredients=true&ingredients={LUISIngredients}&limitLicense=true&number=5&ranking=2";
         HttpResponse <string> response = Unirest.get(url)
                                          .header("X-Mashape-Key", "waVWFXWmMEmshIIkFrNRfj8T1ii8p1AlRJrjsnkb9fZC0uN270")
                                          .header("Accept", "application/json")
                                          .asJson <string>();
         String strResponse = response.Body;
         List <IngredientsJson> lstRecipes = new List <IngredientsJson>();
         lstRecipes = JsonConvert.DeserializeObject <List <IngredientsJson> >(strResponse);
         return(lstRecipes);
     }
     catch (Exception e)
     {
         String strTextToWrite = DateTime.Now.ToString() + "Spoonacular.getRecipes Exception: " + e.Message;
         File.AppendAllText(ASRFile, strTextToWrite + Environment.NewLine);
         return(null);
     }
 }
        public static void DownloadImages(DateTime start, int imageCount, TimeSpan delta)
        {
            String lastDate = "";
            int    counter  = 1;

            while (counter <= imageCount)
            {
                Console.WriteLine("trying date " + start.ToString(DATE_FORMAT));
                var closestImageUrl = string.Format(HV_API, "getClosestImage", start.ToString(DATE_FORMAT));
                var response        = Unirest.get(closestImageUrl).asString();
                if (response.Code != 200)
                {
                    Console.WriteLine("error getting closest date: " + response.Code);
                    continue;
                }
                start += delta;
                var date = JsonConvert.DeserializeObject <ClosestImageResponse>(response.Body).date;
                Console.WriteLine("closest date: " + date);
                if (date == lastDate)
                {
                    Console.WriteLine("skipping, same as last");
                    continue;
                }
                lastDate = date;
                var getImageUrl = string.Format(HV_API, "getJP2Image", DateTime.Parse(date).ToString(DATE_FORMAT));
                HttpResponse <Stream> imgResponse = Unirest.get(getImageUrl).asBinary();
                if (imgResponse.Code != 200)
                {
                    Console.WriteLine("error getting image: " + imgResponse.Code);
                    continue;
                }
                using (var fileStream = File.Create(@"./" + counter + ".jp2"))
                {
                    imgResponse.Body.CopyTo(fileStream);
                }
                Console.WriteLine("image downloaded\n");
                counter++;
            }
        }
Esempio n. 20
0
        public String[] getInstructions(int recipeID, String strRecipeName)
        {
            try
            {
                string url = $"https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/{recipeID}/analyzedInstructions?stepBreakdown=true";
                HttpResponse <string> response = Unirest.get(url)
                                                 .header("X-Mashape-Key", "I4Gh7MsEkJmshjKplIePxRXXw3Ump1uEReajsnOwO3FLB2mMsS")
                                                 .header("Accept", "application/json")
                                                 .asJson <string>();
                String strResponse = response.Body;
                List <RecipeInstructJSON> lstInstructions = new List <RecipeInstructJSON>();
                //List<String> lstSteps = new List<String>();

                lstInstructions = JsonConvert.DeserializeObject <List <RecipeInstructJSON> >(strResponse);
                String[]      strSteps       = new String[lstInstructions[0].steps.Count + 1];
                List <String> lstIngredients = new List <string>();
                //String strInstructions = "";
                for (int i = 2; i <= lstInstructions[0].steps.Count; i++)
                {
                    for (int k = 0; k < lstInstructions[0].steps[i - 2].ingredients.Count; k++)
                    {
                        lstIngredients.Add(lstInstructions[0].steps[i - 2].ingredients[k].name);
                    }

                    strSteps[i] = lstInstructions[0].steps[i - 2].step;
                    //strInstructions += lstInstructions[i].step + " ";
                }
                strSteps[0]    = strRecipeName;
                lstIngredients = lstIngredients.Distinct(StringComparer.OrdinalIgnoreCase).ToList <String>();
                strSteps[1]    = "The ingredients are " + String.Join(", ", lstIngredients) + ".";
                return(strSteps);
            }
            catch (Exception e)
            {
                String strTextToWrite = DateTime.Now.ToString() + "Spoonacular.getInstructions Exception: " + e.Message;
                File.AppendAllText(ASRFile, strTextToWrite + Environment.NewLine);
                return(null);
            }
        }
Esempio n. 21
0
        static async Task <byte[]> GetGif(string tag)
        {
            // These code snippets use an open-source library. http://unirest.io/net
            var response = Unirest.get("https://giphy.p.mashape.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + tag)
                           .header("X-Mashape-Key", "uNOgVxAHRemshRiAMi6C7GQ68qR4p1dEz8jjsn5eMK4qYLUwW1")
                           .header("Accept", "application/json")
                           .asJson <string>();
            var json = (JObject)JsonConvert.DeserializeObject(response.Body);

            if (!json["data"].HasValues)
            {
                return(null);
            }
            var data = json["data"]["fixed_height_downsampled_url"].Value <string>();

            using (var client = new HttpClient())
            {
                var gif = await client.GetByteArrayAsync(data);

                return(gif);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Uses jagex's crappy API
        /// </summary>
        /// <param name="url">A endpoint of jagex's crappy API</param>
        /// <returns>Data returned from jagex's crappy API</returns>
        public static async Task <JObject> GetFromJCA(string url)
        {
            HttpResponse <string> data;

            do
            {
                data = await Unirest.get(url).asStringAsync();

                if (data.Code == 404)
                {
                    return(null);
                }

                if (data.Code == 429 || data.Body == null || data.Body.Trim().IsNullOrEmpty())
                {
                    Console.WriteLine($"Waiting... {url}");
                    await Task.Delay(4000);
                }
            } while (data.Body == null || data.Body.Trim().IsNullOrEmpty());

            return(JsonConvert.DeserializeObject <JObject>(data.Body));
        }
Esempio n. 23
0
        public string ReadOutLoudYoda(string yoda)
        {
            var handle = Insights.TrackTime("Time for API to connect");

            handle.Start();

            var response = Unirest.get("https://yoda.p.mashape.com/yoda?sentence=" + yoda)
                           .header("X-Mashape-Key", "jNdTUH1UxUmshWJ0duG9JGydgLqGp13bv6IjsnmZCuwlTEAK62")
                           .header("Accept", "text/plain")
                           .asString();

            if (response.Code == 200)
            {
                return(response.Body);
            }

            handle.Stop();

            string errorMessages = "Could not connect to API";

            return(errorMessages);
        }
Esempio n. 24
0
        public async Task <bool> getRandomQandA(int id)
        {
            var httpClient = new HttpClient();

            var response = await httpClient.GetAsync(GetRandomQuestionAndAnswerURL + "Id=" + id);

            if (response.IsSuccessStatusCode)
            {
                Task <HttpResponse <string> > response2 = Unirest.get(GetRandomQuestionAndAnswerURL)
                                                          .asJsonAsync <string>();
                var obj = JsonConvert.DeserializeObject <QandA>(response2.Result.Body);

                SessionQandA.Question = obj.Question;
                SessionQandA.ChoiceA  = obj.ChoiceA;
                SessionQandA.ChoiceB  = obj.ChoiceB;
                SessionQandA.ChoiceC  = obj.ChoiceC;
                SessionQandA.ChoiceD  = obj.ChoiceD;
                SessionQandA.Answer   = obj.Answer;
            }

            return(response.IsSuccessStatusCode);
        }
            /// <summary>
            /// Get SSHKey by numeric ID.
            /// </summary>
            /// <param name="_Config"></param>
            /// <param name="_User"></param>
            /// <param name="_id"></param>
            /// <returns></returns>
            public static SSHKey Get(Config _Config, User _User, int _id)
            {
                SSHKey RetVal;

                try
                {
                    string URI = _Config.APIUrl;

                    if (_User == null)
                    {
                        URI += "user/keys/";
                    }
                    else
                    {
                        URI += "users/" + _User.id.ToString() + "/keys/";
                    }

                    URI += _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
                    {
                        RetVal = JsonConvert.DeserializeObject <SSHKey>(R.Body.ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return(RetVal);
            }
Esempio n. 26
0
        /// <summary>
        /// Get zero or more objects from table Customers
        /// </summary>
        /// <param name="filter">Optional parameter: Arbitrary search criteria</param>
        /// <return>Returns the CustomersModel response from the API call</return>
        public async Task <CustomersModel> GetCustomersAsync(
            string filter = null)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);

            queryBuilder.Append("/Customers");


            //process optional query parameters
            APIHelper.AppendUrlWithQueryParameters(queryBuilder, new Dictionary <string, object>()
            {
                { "filter", filter }
            });

            //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 <CustomersModel>(response.Body));
        }
Esempio n. 27
0
        private void btnTranslate_Click(object sender, RoutedEventArgs e)
        {
            //using (var client = new HttpClient())
            //{
            //    client.BaseAddress = new Uri("https://yoda.p.mashape.com/");
            //    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-Mashape-Key", "zVcTJBa3H3mshvcot6As86uycEnep1ZKEkdjsnL8GBGUY6UWMF");
            //    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
            //   var response= client.GetAsync("yoda?sentence="+ txtWords.Text.Trim().ToString()).Result;

            //    string json = new JavaScriptSerializer().Serialize(jsonResult.Data);
            //}

            try
            {
                Task <HttpResponse <string> > response = Unirest.get("https://yoda.p.mashape.com/yoda?sentence=" + txtWords.Text.Trim().ToString())
                                                         .header("X-Mashape-Key", "zVcTJBa3H3mshvcot6As86uycEnep1ZKEkdjsnL8GBGUY6UWMF")
                                                         .header("Accept", "text/plain").asStringAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 28
0
        // Get gameInfo
        public async Task <object> gameInfo(int GameId)
        {
            // These code snippets use an open-source library. http://unirest.io/net
            Task <HttpResponse <object> > response = Unirest.get("http://store.steampowered.com/api/appdetails?appids=" + GameId + "&l=spanish")
                                                     .asJsonAsync <object>();

            await response;

            string json = response.Result.Body.ToString();

            Dictionary <string, object> sData = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);

            string result = sData[GameId.ToString()].ToString();

            RootObject rootObject = null;

            if (!string.IsNullOrEmpty(result))
            {
                rootObject = JsonConvert.DeserializeObject <RootObject>(result);
            }

            return(rootObject);
        }
Esempio n. 29
0
        public WordUsageExample getWordUsage(string word)
        {
            try
            {
                StringBuilder fullQuery = new StringBuilder(endpointURL);
                //q: word to search, l=languge english, size:max results
                fullQuery.AppendFormat("q={0}&key={1}&l=en&size=4&format=json", word, apiKey);
                HttpResponse <string> response = Unirest.get(fullQuery.ToString())
                                                 .header("Accept", "application/json")
                                                 .asJson <string>();

                if (response.Code != 200)
                {
                    throw new Exception($"WordAPI return error code{response.Code} - message:{response.Body}");
                }

                return(JsonConvert.DeserializeObject <WordUsageExample>(response.Body));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 30
0
        public string GetStringFromApi(string sentence)
        {
            string errorMsg = "";

            try
            {
                var response = Unirest.get("https://yoda.p.mashape.com/yoda?sentence=" + sentence)
                               .header("X-Mashape-Key", "GED6XhwlBhmshzR1JzaQqkQpqhBtp13gS5qjsnkCIIZHIXrNa7")
                               .header("Accept", "text/plain")
                               .asString();

                if (response.Code == 200)
                {
                    return(response.Body);
                }
                errorMsg = "Error";
                return(errorMsg);
            }
            catch (Exception ex)
            {
                return(errorMsg = "Error");
            }
        }