Example #1
0
        /// <summary>
        /// Make a GET request
        /// </summary>
        /// <returns><c>Task&lt;Response&gt;</c></returns>
        public async Task <CXResponse> Get()
        {
            string tempUrl = url;

            if (mHttpContent != null)
            {
                tempUrl += "?" + await mHttpContent.ReadAsStringAsync().AsTask(cts.Token).ConfigureAwait(false);
            }
            else if (rawData != "")
            {
                tempUrl += "?" + rawData;
            }
            else if (data.Count > 0)
            {
                HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(data);
                string p = await content.ReadAsStringAsync().AsTask(cts.Token).ConfigureAwait(false);

                tempUrl += "?" + p;
            }
            Uri uri = new Uri(tempUrl);

            PrepareRequest(uri);
            HttpResponseMessage res = await mHttpClient.GetAsync(uri).AsTask(cts.Token).ConfigureAwait(false);

            return(new CXResponse(res, mFilter.CookieManager.GetCookies(uri)));
        }
Example #2
0
        /// <summary>
        /// Gets a access token from reddit
        /// </summary>
        /// <returns></returns>
        private async Task <AccessTokenResult> GetAccessToken(string code, bool isRefresh)
        {
            // Create the nav string
            string accessTokenRequest = "https://www.reddit.com/api/v1/access_token";

            try
            {
                // Create the post data
                List <KeyValuePair <string, string> > postData = new List <KeyValuePair <string, string> >();
                postData.Add(new KeyValuePair <string, string>("grant_type", isRefresh ? "refresh_token" : "authorization_code"));
                postData.Add(new KeyValuePair <string, string>(isRefresh ? "refresh_token" : "code", code));
                postData.Add(new KeyValuePair <string, string>("redirect_uri", BACONIT_REDIRECT_URL));

                // Create the auth header
                var          byteArray    = Encoding.UTF8.GetBytes(BACONIT_APP_ID + ":");
                var          base64String = "Basic " + Convert.ToBase64String(byteArray);
                IHttpContent response     = await m_baconMan.NetworkMan.MakePostRequest(accessTokenRequest, postData, base64String);

                string responseString = await response.ReadAsStringAsync();

                // Parse the response.
                return(JsonConvert.DeserializeObject <AccessTokenResult>(responseString));
            }
            catch (Exception e)
            {
                m_baconMan.MessageMan.DebugDia("Failed to get access token", e);
                return(null);
            }
        }
Example #3
0
        private static async void WriteRequestContent(IHttpContent content, int maxLength = 0)
        {
            Write("Content:");
            var raw = await content.ReadAsStringAsync();

            if ((raw.Length > maxLength) & (maxLength != 0))
            {
                raw = raw.Substring(0, maxLength);
            }
            Write(WebUtility.UrlDecode(raw));
        }
Example #4
0
 public static async Task<UploadResponse> ParseUploadResponseAsync(IHttpContent response)
 {
     string json = await response.ReadAsStringAsync();
     var jsonObject = JsonObject.Parse(json);
     string token = jsonObject["data"].GetObject()["token"].GetString();
     string secureId = jsonObject["data"].GetObject()["secure_id"].GetString();
     int errorCode = (int)jsonObject["err"].GetNumber();
     string expiration = jsonObject["expiration"].GetString();
     return new UploadResponse
     {
         Token = token,
         ErrorCode = errorCode,
         Expiration = new FileExpiration(expiration),
         SecureId = secureId
     };
 }
Example #5
0
        private static async void WriteContent(IHttpContent content, Formatting formatting, int maxLength = 0)
        {
            Write("Content:");
            var raw = await content.ReadAsStringAsync();

            if (formatting == Formatting.Indented)
            {
                raw = FormatJson(raw);
            }
            raw = raw.Contains("<!DOCTYPE html>") ? "got html content!" : raw;
            if ((raw.Length > maxLength) & (maxLength != 0))
            {
                raw = raw.Substring(0, maxLength);
            }
            Write(raw);
        }
Example #6
0
 public static async Task<EditResponse> ParseEditResponseAsync(IHttpContent response)
 {
     string json = await response.ReadAsStringAsync();
     var jsonObject = JsonObject.Parse(json);
     int errorCode = (int)jsonObject["status"].GetNumber();
     string newToken = jsonObject["new_token"].GetString();
     string url = jsonObject["url"].GetString();
     string expiration = jsonObject["expiration"].GetString();
     return new EditResponse
     {
         ErrorCode = errorCode,
         Token = newToken,
         Url = url,
         Expiration = new FileExpiration(expiration)
     };
 }
Example #7
0
        /// <summary>
        /// 获取经纬度地址
        /// </summary>
        /// <param name="latitude">纬度</param>
        /// <param name="longitude">经度</param>
        private async System.Threading.Tasks.Task <GeocoderResult> getHttp(double latitude, double longitude)
        {
            Uri      requestUri = new Uri("http://api.map.baidu.com/geocoder/v2/?ak=LUmQKZ3QBGRy8qG6H7Yg5d8G5PaN46Oe&output=json&pois=0&coordtype=wgs84ll&location=" + latitude + "," + longitude);
            HttpUtil http       = new HttpUtil();

            try {
                IHttpContent content = await http.get(requestUri);

                string body = await content.ReadAsStringAsync();

                return(JsonUtil.gpsToAddress(body));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #8
0
        public static async Task <EditResponse> ParseEditResponseAsync(IHttpContent response)
        {
            string json = await response.ReadAsStringAsync();

            var    jsonObject = JsonObject.Parse(json);
            int    errorCode  = (int)jsonObject["status"].GetNumber();
            string newToken   = jsonObject["new_token"].GetString();
            string url        = jsonObject["url"].GetString();
            string expiration = jsonObject["expiration"].GetString();

            return(new EditResponse
            {
                ErrorCode = errorCode,
                Token = newToken,
                Url = url,
                Expiration = new FileExpiration(expiration)
            });
        }
Example #9
0
        public static async Task <UploadResponse> ParseUploadResponseAsync(IHttpContent response)
        {
            string json = await response.ReadAsStringAsync();

            var    jsonObject = JsonObject.Parse(json);
            string token      = jsonObject["data"].GetObject()["token"].GetString();
            string secureId   = jsonObject["data"].GetObject()["secure_id"].GetString();
            int    errorCode  = (int)jsonObject["err"].GetNumber();
            string expiration = jsonObject["expiration"].GetString();

            return(new UploadResponse
            {
                Token = token,
                ErrorCode = errorCode,
                Expiration = new FileExpiration(expiration),
                SecureId = secureId
            });
        }
        public async Task <MessageOfTheDay> GetNewMessage()
        {
            try
            {
                // Make the request
                IHttpContent response = await m_baconMan.NetworkMan.MakeGetRequest(c_motdUrl);

                string jsonResponse = await response.ReadAsStringAsync();

                // Try to parse it
                return(JsonConvert.DeserializeObject <MessageOfTheDay>(jsonResponse));
            }
            catch (Exception e)
            {
                m_baconMan.MessageMan.DebugDia("failed to get motd", e);
                m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToGetMotd", e);
            }

            return(null);
        }
Example #11
0
        private async Task HandleQueueMessage(HttpResponseHeaderCollection headers, IHttpContent content)
        {
            string brokerPropertiesSource;

            if (!headers.TryGetValue("BrokerProperties", out brokerPropertiesSource))
            {
                Log.Warning("Received Azure queue message without broker properties.");
                return;
            }

            string bodySource = await content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(bodySource))
            {
                Log.Warning("Received Azure queue message with empty body.");
                return;
            }

            JsonObject brokerProperties;

            if (!JsonObject.TryParse(brokerPropertiesSource, out brokerProperties))
            {
                Log.Warning("Received Azure queue message with invalid broker properties.");
                return;
            }

            JsonObject body;

            if (!JsonObject.TryParse(bodySource, out body))
            {
                Log.Warning("Received Azure queue message with not supported body (JSON expected).");
                return;
            }

            Log.Verbose("Received valid Azure queue message.");
            MessageReceived?.Invoke(this, new MessageReceivedEventArgs(brokerProperties, body));
        }
Example #12
0
        private async Task HandleQueueMessage(HttpResponseHeaderCollection headers, IHttpContent content)
        {
            string brokerPropertiesSource;

            if (!headers.TryGetValue("BrokerProperties", out brokerPropertiesSource))
            {
                _log.Warning("Received Azure queue message without broker properties.");
                return;
            }

            var bodySource = await content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(bodySource))
            {
                _log.Warning("Received Azure queue message with empty body.");
                return;
            }

            var brokerProperties = JObject.Parse(brokerPropertiesSource);
            var body             = JObject.Parse(bodySource);

            _log.Verbose("Received valid Azure queue message.");
            MessageReceived?.Invoke(this, new MessageReceivedEventArgs(brokerProperties, body));
        }
Example #13
0
#pragma warning restore

        /// <summary>
        /// Gets a video url from gfycat
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <returns></returns>
        private async Task <string> GetGfyCatGifUrl(string apiUrl)
        {
            // Return if we have nothing.
            if (apiUrl.Equals(String.Empty))
            {
                return(String.Empty);
            }

            try
            {
                // Make the call
                IHttpContent response = await App.BaconMan.NetworkMan.MakeGetRequest(apiUrl);

                string jsonReponse = await response.ReadAsStringAsync();

                // Parse the data
                GfyCatDataContainer gfyData = JsonConvert.DeserializeObject <GfyCatDataContainer>(jsonReponse);

                // Validate the repsonse
                string mp4Url = gfyData.item.Mp4Url;
                if (String.IsNullOrWhiteSpace(mp4Url))
                {
                    throw new Exception("Gfycat response failed to parse");
                }

                // Return the url
                return(mp4Url);
            }
            catch (Exception e)
            {
                App.BaconMan.MessageMan.DebugDia("failed to get image from gfycat", e);
                App.BaconMan.TelemetryMan.ReportUnExpectedEvent(this, "FaileGfyCatApiCall", e);
            }

            return(String.Empty);
        }
Example #14
0
        protected async override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);

            if (args.Kind == ActivationKind.VoiceCommand)
            {
                VoiceCommandActivatedEventArgs command = args as VoiceCommandActivatedEventArgs;
                SpeechRecognitionResult        result  = command.Result;

                string cmdName      = result.RulePath[0];
                string arg          = "";
                string access_token = "";
                string device       = "";
                string function     = "";
                switch (cmdName)
                {
                case "LightsOn":
                    arg      = "on";
                    device   = "";
                    function = "all_lights";
                    break;

                case "LightsOff":
                    //turn off the lights
                    arg      = "off";
                    device   = "";
                    function = "all_lights";
                    break;

                case "LockDoor":
                    arg      = "lock";
                    device   = "";
                    function = "door";
                    break;

                case "UnlockDoor":
                    arg      = "unlock";
                    device   = "";
                    function = "door";
                    break;

                default:
                    Debug.Write("Command not found");
                    break;
                }

                //turn on the lights
                IEnumerable <KeyValuePair <string, string> > data = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("access_token", access_token),
                    new KeyValuePair <string, string>("args", arg)
                };
                System.Uri   uri     = new System.Uri("https://api.particle.io/v1/devices/" + device + "/" + function);
                IHttpContent content = new HttpFormUrlEncodedContent(data);
                using (HttpClient client = new HttpClient())
                {
                    using (HttpResponseMessage res = await client.PostAsync(uri, content))
                    {
                        using (IHttpContent hcontent = res.Content)
                        {
                            string mcontent = await hcontent.ReadAsStringAsync();

                            HttpContentHeaderCollection headers = hcontent.Headers;
                        }
                    }
                }
            }
        }
        private async Task HandleQueueMessage(HttpResponseHeaderCollection headers, IHttpContent content)
        {
            string brokerPropertiesSource;
            if (!headers.TryGetValue("BrokerProperties", out brokerPropertiesSource))
            {
                Log.Warning("Received Azure queue message without broker properties.");
                return;
            }
            
            var bodySource = await content.ReadAsStringAsync();
            if (string.IsNullOrEmpty(bodySource))
            {
                Log.Warning("Received Azure queue message with empty body.");
                return;
            }

            var brokerProperties = JObject.Parse(brokerPropertiesSource);
            var body = JObject.Parse(bodySource);

            Log.Verbose("Received valid Azure queue message.");
            MessageReceived?.Invoke(this, new MessageReceivedEventArgs(brokerProperties, body));
        }
 public static async Task <string> ReadAsStringUTF8Async(this IHttpContent content)
 {
     return(await content.ReadAsStringAsync(Encoding.UTF8));
 }
Example #17
0
        /// <summary>
        /// Returns the reddit post as a string.
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public async Task <string> MakeRedditGetRequestAsString(string apiUrl)
        {
            IHttpContent content = await MakeRedditGetRequest(apiUrl);

            return(await content.ReadAsStringAsync());
        }
        internal static async Task <T> ReadAsJsonAsync <T>(this IHttpContent content)
        {
            string json = await content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <T>(json));
        }
Example #19
0
        /// <summary>
        /// Returns the reddit post as a string.
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public async Task <string> MakeRedditPostRequestAsString(string apiUrl, List <KeyValuePair <string, string> > postData)
        {
            IHttpContent content = await MakeRedditPostRequest(apiUrl, postData);

            return(await content.ReadAsStringAsync());
        }
        /*
         * GetWeather initilizes a Result onject with all of the selected countries data.
         */
        public async Task GetWeather(string cCode)
        {
            // Load local storage
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            // TempSetting represents the forma to convert kelvin to celsius.
            double tempSetting = 273.15;

            // Must confirm with local storage users selected temperature format.
            try
            {
                switch ((string)localSettings.Values["tempSetting"])
                {
                case "Celsius":
                    tempSetting = 273.15;
                    break;

                case "Kelvin":
                    tempSetting = -0;
                    break;

                default:
                    tempSetting = 273.15;
                    break;
                }
            }
            catch
            {
                // If no local storage value is available do not show the prevSearch textbox.
                tempSetting = 1;
            }

            string cityCode = cCode;
            string apiKey   = "&APPID=833dac87e9be3b3f86533d84b6064a84";

            string url = "http://api.openweathermap.org/data/2.5/forecast?" + cityCode + apiKey;

            // Adapted from https://stackoverflow.com/questions/5566942/how-to-get-a-json-string-from-url
            var uri = new Uri(url);

            using (HttpResponseMessage response = await Client.GetAsync(uri))
            {
                using (IHttpContent content = response.Content)
                {
                    // Ensure that the httpRequest was a success.
                    if (response.IsSuccessStatusCode)
                    {
                        this.httpSuccess = true;
                        Debug.WriteLine("DEBUG : content =" + content);
                        var json = await content.ReadAsStringAsync();

                        // Adapted from https://stackoverflow.com/questions/36516146/parsing-json-in-uwp

                        Result = JsonConvert.DeserializeObject <RootObject>(json);

                        SortedDays = new List <List <WeatherController> >();

                        // Create a list of weatherController objects to hold each hourly interval.
                        List <WeatherController> sortedHours = new List <WeatherController>();

                        // A base time.
                        DateTime prevDate = Convert.ToDateTime("2000-01-01");
                        int      counter  = 0;

                        // iterate through Result list  .
                        for (int i = 0; i < Result.List.Count(); i++)
                        {
                            // if the date is greater than the previous date add the sortedHours to SortedDays.
                            if (Convert.ToDateTime(Result.List[counter].Dt_txt).Date > prevDate.Date && counter != 0)
                            {
                                SortedDays.Add(sortedHours);
                                sortedHours = new List <WeatherController>();
                            }
                            WeatherController wController = new WeatherController
                            {
                                Dtime     = Result.List[counter].Dt_txt,
                                DayOfWeek = (Convert.ToDateTime(Result.List[counter].Dt_txt).DayOfWeek).ToString(),
                                Temp      = (Math.Truncate(Result.List[counter].Main.Temp - tempSetting) * 100) / 100,
                                Humidity  = Result.List[counter].Main.Humidity,
                                Desc      = Result.List[counter].Weather[0].Description,
                                WindSpeed = Result.List[counter].Wind.Speed,
                                Icon      = "http://openweathermap.org/img/w/" + Result.List[counter].Weather[0].Icon + ".png",
                                City      = Result.City.Name,
                                CoLong    = Result.City.Coord.Lon,
                                CoLat     = Result.City.Coord.Lat
                            };

                            sortedHours.Add(wController);

                            prevDate = Convert.ToDateTime(Result.List[counter].Dt_txt);
                            counter++;
                        }

                        // Add any left over sortedHours to SortedDays.
                        if (sortedHours != null)
                        {
                            SortedDays.Add(sortedHours);
                        }
                    }
                    else
                    {
                        this.httpSuccess = false;
                        Debug.WriteLine("DEBUG: response error" + response.ReasonPhrase);
                    }
                }
            }//using (HttpResponseMessage response = await Client.GetAsync(uri))
        }