Beispiel #1
0
        private static async Task <TResult> GetAsync <TResult>(
            Uri uri,
            Func <HttpResponseMessage, Task <TResult> > readResponseContent,
            CancellationToken ct,
            bool noCache)
        {
            ct.ThrowIfCancellationRequested();

            using (var request = new HttpRequestMessage(HttpMethod.Get, uri))
            {
                if (noCache)
                {
                    request.Headers.IfModifiedSince = DateTimeOffset.Now;
                }

                return(await RetryHelper.RunWithDelayAsync(
                           async() =>
                {
                    HttpResponseMessage response = await Client.SendAsync(request, ct).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();
                    return await readResponseContent(response).WithCancellation(ct).ConfigureAwait(false);
                },
                           ct,
                           ex => WebError.GetStatus(ex.HResult) == WebErrorStatus.CannotConnect && !NetworkInfo.IsNetworkAvailable).ConfigureAwait(false));
            }
        }
        public static async Task <string> GetStringAsync(string url)
        {
            try
            {
                using (HttpClient httpclient = new HttpClient())
                {
                    var httpResponse = await httpclient.GetAsync(new Uri(url));

                    if (!httpResponse.IsSuccessStatusCode)
                    {
                        throw new ServiceException("Faild to fetch the Photos From the server");
                    }

                    return(await httpResponse.Content.ReadAsStringAsync());
                }
            }
            catch (UnauthorizedAccessException)
            {
                throw new ServiceException("Unauthorized Access app doesn't has permession to access internet");
            }
            catch (OperationCanceledException)
            {
                throw new ServiceException("Call Time out");
            }
            catch (COMException ex)
            {
                var    error = WebError.GetStatus(ex.HResult);
                string msg   = "network error " + Enum.GetName(typeof(WebErrorStatus), error);
                throw new ServiceException(msg);
            }
            catch (Exception)
            {
                throw new ServiceException("Operation error please try again");
            }
        }
Beispiel #3
0
        private static async Task <TResult> PostAsync <TResult>(
            Uri uri,
            HttpContent content,
            Func <HttpResponseMessage, Task <TResult> > readResponseContent,
            CancellationToken ct,
            Action <HttpRequestMessage> requestAction = null)
        {
            ct.ThrowIfCancellationRequested();

            ValidationHelper.ArgumentNotNull(content, nameof(content));

            return(await RetryHelper.RunWithDelayAsync(
                       async() =>
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
                {
                    request.Content = content;
                    requestAction?.Invoke(request);

                    HttpResponseMessage response = await Client.SendAsync(request, ct).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();
                    return await readResponseContent(response).WithCancellation(ct).ConfigureAwait(false);
                }
            },
                       ct,
                       ex => WebError.GetStatus(ex.HResult) == WebErrorStatus.CannotConnect && !NetworkInfo.IsNetworkAvailable).ConfigureAwait(false));
        }
        /// <summary>
        /// Play preinstalled recording button click handler
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="args">Event arguments</param>
        private async void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            SenseRecording recording       = null;
            WebErrorStatus exceptionDetail = new WebErrorStatus();

            try
            {
                recording = await SenseRecording.LoadFromUriAsync(new Uri("https://github.com/Microsoft/steps/raw/master/Steps/Simulations/short%20walk.txt"));
            }
            catch (Exception ex)
            {
                exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
            }
            if (exceptionDetail == WebErrorStatus.HostNameNotResolved)
            {
                MessageDialog dialog = new MessageDialog("Check your network connection. Host name could not be resolved.", "Information");
                await dialog.ShowAsync();
            }
            if (recording != null)
            {
                _stepCounter = await StepCounterSimulator.GetDefaultAsync(recording);

                MessageDialog dialog = new MessageDialog(
                    "Recorded sensor type: " + recording.Type.ToString() +
                    "\r\nDescription: " + recording.Description +
                    "\r\nRecording date: " + recording.StartTime.ToString() +
                    "\r\nDuration: " + recording.Duration.ToString(),
                    "Recording info"
                    );
                await dialog.ShowAsync();
            }
        }
        static public bool HandleException(Exception exception, TextBox outputField, MainPage rootPage)
        {
            SyndicationErrorStatus status = SyndicationError.GetStatus(exception.HResult);

            if (status != SyndicationErrorStatus.Unknown)
            {
                outputField.Text += "The response content is not valid. " +
                                    "Please make sure to use a URI that points to an Atom feed.\r\n";
            }
            else
            {
                WebErrorStatus webError = WebError.GetStatus(exception.HResult);

                if (webError == WebErrorStatus.Unauthorized)
                {
                    outputField.Text += "Incorrect username or password.\r\n";
                }
                else if (webError == WebErrorStatus.Unknown)
                {
                    // Neither a syndication nor a web error.
                    return(false);
                }
            }

            rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);

            return(true);
        }
Beispiel #6
0
        private async Task <bool> ValidateApplicationUsage()
        {
            // Hanu Epoch time.
            DateTime lastValidationTime = new DateTime(2011, 11, 4);
            DateTime now = DateTime.Now;

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            if (localSettings.Values["ValidationTime"] != null)
            {
                // This is not the first use.
                lastValidationTime = DateTime.Parse(localSettings.Values["ValidationTime"].ToString());
            }

            TimeSpan interval = now.Subtract(lastValidationTime);

            if (interval.Days > 7)
            {
                // Validate again

                try
                {
                    using (HttpClient hc = new HttpClient())
                    {
                        Uri address = new Uri("http://apps.ayansh.com/HanuGCM/Validate.php");

                        var values = new List <KeyValuePair <string, string> >
                        {
                            new KeyValuePair <string, string>("blogurl", _blogURL),
                        };

                        HttpFormUrlEncodedContent postContent = new HttpFormUrlEncodedContent(values);
                        HttpResponseMessage       response    = await hc.PostAsync(address, postContent).AsTask();

                        string response_text = await response.Content.ReadAsStringAsync();

                        if (response_text.Equals("Success"))
                        {
                            // Set Validation time as now
                            localSettings.Values["ValidationTime"] = now.ToString();
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
                catch (Exception e)
                {
                    WebErrorStatus error = WebError.GetStatus(e.GetBaseException().HResult);
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    System.Diagnostics.Debug.WriteLine(error.ToString());
                    return(false);
                }
            }

            return(true);
        }
        private async void GetFeed_Click(object sender, RoutedEventArgs e)
        {
            outputField.Text = "";

            // By default 'FeedUri' is disabled and URI validation is not required. When enabling the text box
            // validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(FeedUri.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Error: Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            SyndicationClient client = new SyndicationClient();

            client.BypassCacheOnRetrieve = true;

            // Although most HTTP servers do not require User-Agent header, others will reject the request or return
            // a different response if this header is missing. Use SetRequestHeader() to add custom headers.
            client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            rootPage.NotifyUser("Downloading feed...", NotifyType.StatusMessage);
            outputField.Text = "Downloading feed: " + uri.ToString() + "\r\n";

            try
            {
                currentFeed = await client.RetrieveFeedAsync(uri);

                rootPage.NotifyUser("Feed download complete.", NotifyType.StatusMessage);

                DisplayFeed();
            }
            catch (Exception ex)
            {
                SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult);
                if (status == SyndicationErrorStatus.InvalidXml)
                {
                    outputField.Text += "An invalid XML exception was thrown. " +
                                        "Please make sure to use a URI that points to a RSS or Atom feed.";
                }

                if (status == SyndicationErrorStatus.Unknown)
                {
                    WebErrorStatus webError = WebError.GetStatus(ex.HResult);

                    if (webError == WebErrorStatus.Unknown)
                    {
                        // Neither a syndication nor a web error. Rethrow.
                        throw;
                    }
                }

                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
        }
Beispiel #8
0
        private string GetErrorMessageFromWebException(Exception exception)
        {
            var webErrorStatus = WebError.GetStatus(exception.HResult);

            if (webErrorStatus == WebErrorStatus.CannotConnect)
            {
                return("Please check your internet connection.");
            }
            return(exception.Message);
        }
Beispiel #9
0
        public static string HttpClientExceptionHandler(int code, Exception ex)
        {
            WebErrorStatus error = WebError.GetStatus(code);

            if (error == WebErrorStatus.CannotConnect ||
                error == WebErrorStatus.CertificateCommonNameIsIncorrect ||
                error == WebErrorStatus.CertificateContainsErrors ||
                error == WebErrorStatus.CertificateExpired ||
                error == WebErrorStatus.CertificateIsInvalid ||
                error == WebErrorStatus.CertificateRevoked)
            {
                return("Error establishing a secure connection. This is usually caused by antivirus, firewall or VPN software, or problems with your ISP.");
            }
            else if (error == WebErrorStatus.Timeout)
            {
                return("The connection to AnkiWeb timed out. Please check your network connection and try again.");
            }
            else if (error == WebErrorStatus.InternalServerError)
            {
                return("AnkiWeb encountered an error. Please try again in a few minutes, and if the problem persists, please file a bug report.");
            }
            else if (error == WebErrorStatus.NotImplemented)
            {
                return("Please upgrade to the latest version of Anki.");
            }
            else if (error == WebErrorStatus.BadGateway)
            {
                return("AnkiWeb is under maintenance. Please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.ServiceUnavailable)
            {
                return("AnkiWeb is too busy at the moment. Please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.GatewayTimeout)
            {
                return("504 gateway timeout error received. Please try temporarily disabling your antivirus.");
            }
            else if (error == WebErrorStatus.Conflict)
            {
                return("Only one client can access AnkiWeb at a time. If a previous sync failed, please try again in a few minutes.");
            }
            else if (error == WebErrorStatus.ProxyAuthenticationRequired)
            {
                return("Proxy authentication required.");
            }
            else if (error == WebErrorStatus.RequestEntityTooLarge)
            {
                return("Your collection or a media file is too large to sync.");
            }
            else
            {
                return(String.Format("Error Code: {0:X}! {1}", ex.HResult, ex.Message));
            }
        }
Beispiel #10
0
        internal static void DisplayWebError(MainPage rootPage, Exception exception)
        {
            WebErrorStatus webErrorStatus = WebError.GetStatus(exception.HResult);

            if (webErrorStatus == WebErrorStatus.Unknown)
            {
                rootPage.NotifyUser("Unknown Error: " + exception.Message, NotifyType.ErrorMessage);
            }
            else
            {
                rootPage.NotifyUser("Web Error: " + webErrorStatus, NotifyType.ErrorMessage);
            }
        }
Beispiel #11
0
        private async Task <HttpResponseMessage> SendInternalAsync(HttpMethod httpMethod, Uri uri, IHttpContent content)
        {
            var request = new HttpRequestMessage(httpMethod, uri);

            if (content != null)
            {
                request.Content = content;
            }
            Logger.Info($"Sending {httpMethod} request to {uri} {(content != null ? "\n" + content : "")}");
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            HttpResponseMessage response;

            try
            {
                response = await HttpClient.SendRequestAsync(request).AsTask().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                stopwatch.Stop();
                var status = WebError.GetStatus(e.HResult);
                Logger.Error($"Caught exception in {stopwatch.ElapsedMilliseconds}ms while sending request to {uri}:\n${status}");
                if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
                {
                    throw new NoInternetException(status);
                }
                throw new NetworkException(status);
            }

            stopwatch.Stop();

            var success = response.IsSuccessStatusCode;

            if (!success)
            {
                var responeText = await response.Content.ReadAsStringAsync().AsTask().ConfigureAwait(false);

                Logger.Error($"Server responded with error code in {stopwatch.ElapsedMilliseconds}ms {uri} {response.StatusCode}:\n{responeText}");
                throw new ServerException((int)response.StatusCode, responeText);
            }
            Logger.Info($"Got response from {uri} in {stopwatch.ElapsedMilliseconds}ms with status code: {response.StatusCode}");
            return(response);
        }
Beispiel #12
0
        public async Task <FeedDto> RetrieveFeedAsync(Uri uri)
        {
            try
            {
                var feed = await client.RetrieveFeedAsync(uri).AsTask().ConfigureAwait(false);

                return(new FeedDto(feed.Title.Text,
                                   feed.Items.Select(x => new FeedItemDto(
                                                         x.ItemUri ?? x.Links.FirstOrDefault()?.Uri,
                                                         x.PublishedDate.UtcDateTime > new DateTime(1601, 1, 2) ? x.PublishedDate : x.LastUpdatedTime, // 1601 is used when PublishedDate is not set
                                                         RemoveHtmlTags(x.Title.Text),
                                                         RemoveHtmlTags(x.Summary?.Text)
                                                         )).ToArray()
                                   ));
            }
            catch (Exception ex) when(WebError.GetStatus(ex.HResult) == WebErrorStatus.NotModified)
            {
                throw new SyndicationServiceException(SyndicationServiceError.NotModified, ex);
            }
        }
        public override async Task <WeatherData.Weather> GetWeather(string location_query)
        {
            WeatherData.Weather weather = null;

            string currentAPI  = null;
            Uri    currentURL  = null;
            string forecastAPI = null;
            Uri    forecastURL = null;
            string query       = null;

#if WINDOWS_UWP
            var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();
            var culture  = new System.Globalization.CultureInfo(userlang);
#else
            var culture = System.Globalization.CultureInfo.CurrentCulture;
#endif
            string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);

            if (int.TryParse(location_query, out int id))
            {
                query = string.Format("id={0}", id);
            }
            else
            {
                query = location_query;
            }

            string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey();

            currentAPI  = "https://api.openweathermap.org/data/2.5/weather?{0}&appid={1}&lang=" + locale;
            currentURL  = new Uri(string.Format(currentAPI, query, key));
            forecastAPI = "https://api.openweathermap.org/data/2.5/forecast?{0}&appid={1}&lang=" + locale;
            forecastURL = new Uri(string.Format(forecastAPI, query, key));

            HttpClient       webClient = new HttpClient();
            WeatherException wEx       = null;

            try
            {
                // Get response
                HttpResponseMessage currentResponse = await webClient.GetAsync(currentURL);

                currentResponse.EnsureSuccessStatusCode();
                HttpResponseMessage forecastResponse = await webClient.GetAsync(forecastURL);

                forecastResponse.EnsureSuccessStatusCode();

                Stream currentStream  = null;
                Stream forecastStream = null;
#if WINDOWS_UWP
                currentStream  = WindowsRuntimeStreamExtensions.AsStreamForRead(await currentResponse.Content.ReadAsInputStreamAsync());
                forecastStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await forecastResponse.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                currentStream = await currentResponse.Content.ReadAsStreamAsync();

                forecastStream = await forecastResponse.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                CurrentRootobject  currRoot = null;
                ForecastRootobject foreRoot = null;
                await Task.Run(() =>
                {
                    currRoot = JSONParser.Deserializer <CurrentRootobject>(currentStream);
                });

                await Task.Run(() =>
                {
                    foreRoot = JSONParser.Deserializer <ForecastRootobject>(forecastStream);
                });

                // End Streams
                currentStream.Dispose();
                forecastStream.Dispose();

                weather = new WeatherData.Weather(currRoot, foreRoot);
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "OpenWeatherMapProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                if (SupportsWeatherLocale)
                {
                    weather.locale = locale;
                }

                weather.query = location_query;
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }
        private NAMResponse LoginWithCertificateAndSAMLRequest(Uri loginUri, string samlRequest)
        {
            var certificate = GetDeviceCertificate();

            Debug.WriteLine("Certificate found, verifying access to private key...");
            var verifyResult = VerifyCertificateKeyAccess(certificate);

            if (verifyResult)
            {
                Debug.WriteLine("Access granted, creating HttpClient...");
                HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter();
                httpFilter.ClientCertificate = certificate;

                // try login
                HttpClient httpClient = new HttpClient(httpFilter);

                try
                {
                    Debug.WriteLine("Sending SAML request to NAM...");
                    var uriBuilder = new UriBuilder(loginUri);
                    if (samlRequest != null)
                    {
                        uriBuilder.Query = "SAMLRequest=" + WebUtility.UrlEncode(samlRequest);
                    }

                    var ssoResponseTask = httpClient.GetAsync(uriBuilder.Uri).AsTask();
                    ssoResponseTask.Wait();
                    var ssoResponse = ssoResponseTask.Result;
                    ssoResponse.EnsureSuccessStatusCode();

                    // follow the Javascript redirect
                    Debug.WriteLine("Received response, trying to extract redirect URI from javascript");
                    var redirectUri = ExtractJavaScriptRedirectUri(ssoResponse, loginUri);
                    Debug.WriteLine("Requesting SAML response from: " + redirectUri.ToString());
                    var redirectResponseTask = httpClient.GetAsync(redirectUri).AsTask();
                    redirectResponseTask.Wait();
                    var redirectResponse = redirectResponseTask.Result;
                    redirectResponse.EnsureSuccessStatusCode();

                    // read the SAMLResponse
                    Debug.WriteLine("Received response from NAM, extracting SAMLResponse...");
                    NAMResponse namResponse = new NAMResponse(redirectResponse);

                    Debug.WriteLine("Returning SAML Response: " + namResponse.SAMLResponse);

                    string cookieHeader;
                    ssoResponse.Headers.TryGetValue("Set-Cookie", out cookieHeader);
                    namResponse.Cookies = cookieHeader;

                    Debug.WriteLine("And Cookies: " + namResponse.Cookies);

                    // update the session timestamp
                    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    localSettings.Values[SESSION_TIMESTAMP_KEY] = DateTime.Now.ToString();

                    return(namResponse);
                }
                catch (FormatException formatException)
                {
                    Debug.WriteLine("Uri extraction error: " + formatException.Message);

                    return(null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Connection error...");
                    Debug.WriteLine("Exception during NAM communication: " + ex.Message);

                    var exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
                    Debug.WriteLine("Exception Detail: " + exceptionDetail);

                    return(null);
                }
            }

            return(null);
        }
        private NAMResponse LoginDirectlyWithCertificateOnly()
        {
            var certificate = GetDeviceCertificate();

            Debug.WriteLine("Certificate found, verifying access to private key...");
            var verifyResult = VerifyCertificateKeyAccess(certificate);

            if (verifyResult)
            {
                Debug.WriteLine("Access granted, creating HttpClient...");
                HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter();
                httpFilter.ClientCertificate = certificate;

                // try login
                HttpClient httpClient = new HttpClient(httpFilter);

                try
                {
                    Debug.WriteLine("Authenticating directly with NAM...");
                    var loginUri = new Uri("https://login.schaeffler.com/nidp/app/login?id=Smartcard");

                    var ssoResponseTask = httpClient.GetAsync(loginUri).AsTask();
                    ssoResponseTask.Wait();
                    var ssoResponse = ssoResponseTask.Result;
                    ssoResponse.EnsureSuccessStatusCode();

                    // follow the Javascript redirect
                    Debug.WriteLine("Received response, trying to extract redirect URI from javascript");
                    var redirectUri = ExtractJavaScriptRedirectUri(ssoResponse, loginUri);
                    Debug.WriteLine("Requesting SAML response from: " + redirectUri.ToString());
                    var redirectResponseTask = httpClient.GetAsync(redirectUri).AsTask();
                    redirectResponseTask.Wait();
                    var redirectResponse = redirectResponseTask.Result;
                    redirectResponse.EnsureSuccessStatusCode();

                    // create an empty Response object, since the NAM won't send a SAMLResponse when authenticating directly
                    NAMResponse namResponse = new NAMResponse();
                    namResponse.SAMLResponse = "";
                    string cookieHeader;
                    ssoResponse.Headers.TryGetValue("Set-Cookie", out cookieHeader);
                    namResponse.Cookies = cookieHeader;

                    Debug.WriteLine("Cookies: " + namResponse.Cookies);

                    // update the session timestamp
                    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    localSettings.Values[SESSION_TIMESTAMP_KEY] = DateTime.Now.ToString();

                    return(namResponse);
                }
                catch (FormatException formatException)
                {
                    Debug.WriteLine("Uri extraction error: " + formatException.Message);

                    return(null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Connection error...");
                    Debug.WriteLine("Exception during NAM communication: " + ex.Message);

                    var exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult);
                    Debug.WriteLine("Exception Detail: " + exceptionDetail);

                    return(null);
                }
            }

            return(null);
        }
Beispiel #16
0
        public override async Task <Weather> GetWeather(string location_query)
        {
            Weather weather = null;

            string forecastAPI   = null;
            Uri    forecastURL   = null;
            string sunrisesetAPI = null;
            Uri    sunrisesetURL = null;

            forecastAPI   = "https://api.met.no/weatherapi/locationforecastlts/1.3/?{0}";
            forecastURL   = new Uri(string.Format(forecastAPI, location_query));
            sunrisesetAPI = "https://api.met.no/weatherapi/sunrise/1.1/?{0}&date={1}";
            string date = DateTime.Now.ToString("yyyy-MM-dd");

            sunrisesetURL = new Uri(string.Format(sunrisesetAPI, location_query, date));

#if WINDOWS_UWP
            var handler = new HttpBaseProtocolFilter()
            {
                AllowAutoRedirect      = true,
                AutomaticDecompression = true
            };
#else
            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect      = true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
#endif

            HttpClient webClient = new HttpClient(handler);

            // Use GZIP compression
#if WINDOWS_UWP
            var version = string.Format("v{0}.{1}.{2}",
                                        Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build);

            webClient.DefaultRequestHeaders.AcceptEncoding.Add(new HttpContentCodingWithQualityHeaderValue("gzip"));
            webClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("SimpleWeather ([email protected])", version));
#elif __ANDROID__
            var packageInfo = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, 0);
            var version     = string.Format("v{0}", packageInfo.VersionName);

            webClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            webClient.DefaultRequestHeaders.TryAddWithoutValidation("user-agent", String.Format("SimpleWeather ([email protected]) {0}", version));
#endif

            WeatherException wEx = null;

            try
            {
                // Get response
                HttpResponseMessage forecastResponse = await webClient.GetAsync(forecastURL);

                forecastResponse.EnsureSuccessStatusCode();
                HttpResponseMessage sunrisesetResponse = await webClient.GetAsync(sunrisesetURL);

                sunrisesetResponse.EnsureSuccessStatusCode();

                Stream forecastStream   = null;
                Stream sunrisesetStream = null;
#if WINDOWS_UWP
                forecastStream   = WindowsRuntimeStreamExtensions.AsStreamForRead(await forecastResponse.Content.ReadAsInputStreamAsync());
                sunrisesetStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await sunrisesetResponse.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                forecastStream = await forecastResponse.Content.ReadAsStreamAsync();

                sunrisesetStream = await sunrisesetResponse.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                weatherdata foreRoot  = null;
                astrodata   astroRoot = null;

                XmlSerializer foreDeserializer = new XmlSerializer(typeof(weatherdata));
                foreRoot = (weatherdata)foreDeserializer.Deserialize(forecastStream);
                XmlSerializer astroDeserializer = new XmlSerializer(typeof(astrodata));
                astroRoot = (astrodata)astroDeserializer.Deserialize(sunrisesetStream);

                weather = new Weather(foreRoot, astroRoot);
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                weather.query = location_query;

                foreach (Forecast forecast in weather.forecast)
                {
                    forecast.condition = GetWeatherCondition(forecast.icon);
                    forecast.icon      = GetWeatherIcon(forecast.icon);
                }
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }
Beispiel #17
0
        public override async Task <Weather> GetWeather(string location_query)
        {
            Weather weather = null;

            string queryAPI   = null;
            Uri    weatherURL = null;

#if WINDOWS_UWP
            var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();
            var culture  = new System.Globalization.CultureInfo(userlang);
#else
            var culture = System.Globalization.CultureInfo.CurrentCulture;
#endif
            string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);

            if (int.TryParse(location_query, out int woeid))
            {
                queryAPI = "https://query.yahooapis.com/v1/public/yql?q=";
                string query = "select * from weather.forecast where woeid=\""
                               + woeid + "\" and u='F'&format=json";
                weatherURL = new Uri(queryAPI + query);
            }
            else
            {
                queryAPI = "https://query.yahooapis.com/v1/public/yql?q=";
                string query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\""
                               + location_query + "\") and u='F'&format=json";
                weatherURL = new Uri(queryAPI + query);
            }

            HttpClient       webClient = new HttpClient();
            WeatherException wEx       = null;

            try
            {
                // Get response
                HttpResponseMessage response = await webClient.GetAsync(weatherURL);

                response.EnsureSuccessStatusCode();
                Stream contentStream = null;
#if WINDOWS_UWP
                contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                contentStream = await response.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                Rootobject root = null;
                await Task.Run(() =>
                {
                    root = JSONParser.Deserializer <Rootobject>(contentStream);
                });

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }

                weather = new Weather(root);
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "YahooWeatherProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                if (SupportsWeatherLocale)
                {
                    weather.locale = locale;
                }

                weather.query = location_query;
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }
        public override async Task <bool> IsKeyValid(string key)
        {
            string queryAPI = "https://weather.cit.api.here.com/weather/1.0/report.json";

            string app_id   = "";
            string app_code = "";

            if (!String.IsNullOrWhiteSpace(key))
            {
                string[] keyArr = key.Split(';');
                if (keyArr.Length > 0)
                {
                    app_id   = keyArr[0];
                    app_code = keyArr[keyArr.Length > 1 ? keyArr.Length - 1 : 0];
                }
            }

            Uri              queryURL = new Uri(String.Format("{0}?app_id={1}&app_code={2}", queryAPI, app_id, app_code));
            bool             isValid  = false;
            WeatherException wEx      = null;

            try
            {
                if (String.IsNullOrWhiteSpace(app_id) || String.IsNullOrWhiteSpace(app_code))
                {
                    throw (wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey));
                }

                // Connect to webstream
                HttpClient          webClient = new HttpClient();
                HttpResponseMessage response  = await webClient.GetAsync(queryURL);

                // Check for errors
                switch (response.StatusCode)
                {
                // 400 (OK since this isn't a valid request)
                case HttpStatusCode.BadRequest:
                    isValid = true;
                    break;

                // 401 (Unauthorized - Key is invalid)
                case HttpStatusCode.Unauthorized:
                    wEx     = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey);
                    isValid = false;
                    break;
                }

                // End Stream
                response.Dispose();
                webClient.Dispose();
            }
            catch (Exception ex)
            {
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                isValid = false;
            }

            if (wEx != null)
            {
#if WINDOWS_UWP
                await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
#elif __ANDROID__
                new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() =>
                {
                    Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show();
                });
#endif
            }

            return(isValid);
        }
        protected async void postRequest()
        {
            string jsonInput = JsonConvert.SerializeObject(input);

            LogManager.WriteLine("jsonInput: " + jsonInput);
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            CancellationTokenSource postTimeout = new CancellationTokenSource(); // 50 seconds

            postTimeout.CancelAfter(RestConfig.SOCKET_TIMEOUT_MS);

            CancellationTokenSource readTimeout = new CancellationTokenSource(); // 2 seconds

            readTimeout.CancelAfter(RestConfig.CONNECTION_TIMEOUT_MS);

            // POST REQUEST
            string GamificationLoginEndpoint = AppSettingsManager.GetAppSettings().engineServerEndPoint + GamificationLogin;

            LogManager.WriteLine("Gamification Login EndPoint: " + GamificationLoginEndpoint);
            Uri        gamificationServerUri = new Uri(GamificationLoginEndpoint);
            HttpClient client = GetConfiguredHttpClient();

            Encoding latinISO = Encoding.GetEncoding(RestConfig.OUTPUT_STREAM_CHARSET);

            byte[] messageArray = latinISO.GetBytes(jsonInput);

            MemoryStream ms = new MemoryStream(messageArray);

            IInputStream inStream = ms.AsInputStream();

            var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, gamificationServerUri);

            request.Content = new HttpStreamContent(inStream);
            ((HttpStreamContent)request.Content).Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");

            LogManager.WriteLine("Request: " + request);

            try
            {
                responseMessage = await client.PostAsync(request.RequestUri, request.Content).AsTask(postTimeout.Token);

                // READ RESPONSE
                try
                {
                    IInputStream responseStream = await responseMessage.Content.ReadAsInputStreamAsync().AsTask(readTimeout.Token);

                    string responseContent;
                    using (Stream receiveStream = responseStream.AsStreamForRead())
                    {
                        Encoding utf8 = Encoding.GetEncoding(RestConfig.INPUT_STREAM_CHARSET);
                        using (StreamReader readStream = new StreamReader(receiveStream, utf8))
                        {
                            responseContent = readStream.ReadToEnd();
                        }
                    }

                    string response = responseContent;

                    LogManager.WriteLine("response: " + response);

                    handleResponse(response);
                }

                catch (Exception e)
                {
                    WebErrorStatus status = WebError.GetStatus(e.HResult);

                    LogManager.WriteLine("Exception on Read Request: " + e);
                    handleResponse(e.Message);
                }
            }

            catch (Exception e)
            {
                WebErrorStatus status = WebError.GetStatus(e.HResult);

                LogManager.WriteLine("Error: " + status);

                LogManager.WriteLine("Exception on Post Request: " + e);
                handleResponse(e.Message);
            }

            // Once your app is done using the HttpClient object, we call 'Dispose' to
            // free up system resources (the underlying socket and memory used for the object)
            client.Dispose();
        }
        internal async Task <bool> downloadPosts()
        {
            if (_postArtifacts.Count > 0)
            {
                String url = HanuDowsApplication.getInstance().BlogURL + "/wp-content/plugins/hanu-droid/FetchPosts.php";

                int batchSize = 5;
                int size      = _postArtifacts.Count;
                int loops     = size / batchSize;
                int x         = 0;

                var  localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                bool allGood       = true;

                // Now time
                DateTime now = DateTime.UtcNow;

                while (x <= loops)
                {
                    IEnumerable <PostArtifact> pfList = _postArtifacts.Skip(x * batchSize).Take(batchSize);

                    if (pfList.Count() <= 0)
                    {
                        x++;
                        continue;
                    }

                    // Get Post IDs
                    string post_ids      = "";
                    string response_text = "";

                    foreach (PostArtifact pf in pfList)
                    {
                        post_ids += pf.PostID + ",";
                    }
                    post_ids = post_ids.TrimEnd(',');

                    try
                    {
                        // Download
                        using (HttpClient hc = new HttpClient())
                        {
                            Uri address = new Uri(url);

                            var values = new List <KeyValuePair <string, string> >
                            {
                                new KeyValuePair <string, string>("post_id", post_ids)
                            };

                            HttpFormUrlEncodedContent postContent = new HttpFormUrlEncodedContent(values);
                            HttpResponseMessage       response    = await hc.PostAsync(address, postContent).AsTask();

                            var buffer = await response.Content.ReadAsBufferAsync();

                            var byteArray = buffer.ToArray();
                            response_text = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

                            XDocument xdoc = XDocument.Parse(response_text);
                            DownloadedPostList = HanuDowsApplication.getInstance().parseXMLToPostList(xdoc);
                        }

                        bool success = await savePostsToDB();

                        if (!success)
                        {
                            allGood = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        WebErrorStatus error = WebError.GetStatus(ex.GetBaseException().HResult);
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                        System.Diagnostics.Debug.WriteLine(error.ToString());
                    }

                    x++;
                }

                if (allGood)
                {
                    // Set Last sync time
                    localSettings.Values["LastSyncTime"] = now.ToString();
                }
                else
                {
                    // Set last sync time to Hanu Epoch
                    localSettings.Values["LastSyncTime"] = (new DateTime(2011, 11, 4)).ToString();
                }
            }

            return(true);
        }
        public override async Task <bool> IsKeyValid(string key)
        {
            string           queryAPI = "https://api.openweathermap.org/data/2.5/";
            string           query    = "forecast?appid=";
            Uri              queryURL = new Uri(queryAPI + query + key);
            bool             isValid  = false;
            WeatherException wEx      = null;

            try
            {
                if (String.IsNullOrWhiteSpace(key))
                {
                    throw (wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey));
                }

                // Connect to webstream
                HttpClient          webClient = new HttpClient();
                HttpResponseMessage response  = await webClient.GetAsync(queryURL);

                // Check for errors
                switch (response.StatusCode)
                {
                // 400 (OK since this isn't a valid request)
                case HttpStatusCode.BadRequest:
                    isValid = true;
                    break;

                // 401 (Unauthorized - Key is invalid)
                case HttpStatusCode.Unauthorized:
                    wEx     = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey);
                    isValid = false;
                    break;
                }

                // End Stream
                response.Dispose();
                webClient.Dispose();
            }
            catch (Exception ex)
            {
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                isValid = false;
            }

            if (wEx != null)
            {
#if WINDOWS_UWP
                await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
#elif __ANDROID__
                new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() =>
                {
                    Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show();
                });
#endif
            }

            return(isValid);
        }
Beispiel #22
0
        public override async Task <LocationQueryViewModel> GetLocation(WeatherUtils.Coordinate coord)
        {
            LocationQueryViewModel location = null;

            string queryAPI = "https://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=";
            string options  = "";
            string query    = string.Format("{0},{1}", coord.Latitude, coord.Longitude);
            Uri    queryURL = new Uri(queryAPI + query + options);

            OpenWeather.location result;
            WeatherException     wEx = null;

            try
            {
                // Connect to webstream
                HttpClient          webClient = new HttpClient();
                HttpResponseMessage response  = await webClient.GetAsync(queryURL);

                response.EnsureSuccessStatusCode();
                Stream contentStream = null;
#if WINDOWS_UWP
                contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                contentStream = await response.Content.ReadAsStreamAsync();
#endif

                // End Stream
                webClient.Dispose();

                // Load data
                XmlSerializer deserializer = new XmlSerializer(typeof(OpenWeather.location));
                result = (OpenWeather.location)deserializer.Deserialize(contentStream);

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                result = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                    await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                }
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                    new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() =>
                    {
                        Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show();
                    });
                }
#endif
                Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting location");
            }

            if (result != null && !String.IsNullOrWhiteSpace(result.query))
            {
                location = new LocationQueryViewModel(result);
            }
            else
            {
                location = new LocationQueryViewModel();
            }

            return(location);
        }
        public override async Task <Weather> GetWeather(string location_query)
        {
            Weather weather = null;

            string queryAPI   = null;
            Uri    weatherURL = null;

#if WINDOWS_UWP
            var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();
            var culture  = new CultureInfo(userlang);
#else
            var culture = CultureInfo.CurrentCulture;
#endif
            string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);
            queryAPI = "https://weather.cit.api.here.com/weather/1.0/report.json?product=alerts&product=forecast_7days_simple" +
                       "&product=forecast_hourly&product=forecast_astronomy&product=observation&oneobservation=true&{0}" +
                       "&language={1}&metric=false&app_id={2}&app_code={3}";

            string key      = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey();
            string app_id   = "";
            string app_code = "";

            if (!String.IsNullOrWhiteSpace(key))
            {
                string[] keyArr = key.Split(';');
                if (keyArr.Length > 0)
                {
                    app_id   = keyArr[0];
                    app_code = keyArr[keyArr.Length > 1 ? keyArr.Length - 1 : 0];
                }
            }

            weatherURL = new Uri(String.Format(queryAPI, location_query, locale, app_id, app_code));

            HttpClient       webClient = new HttpClient();
            WeatherException wEx       = null;

            try
            {
                // Get response
                HttpResponseMessage response = await webClient.GetAsync(weatherURL);

                response.EnsureSuccessStatusCode();
                Stream contentStream = null;
#if WINDOWS_UWP
                contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                contentStream = await response.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                Rootobject root = null;
                await Task.Run(() =>
                {
                    root = JSONParser.Deserializer <Rootobject>(contentStream);
                });

                // Check for errors
                if (root.Type != null)
                {
                    switch (root.Type)
                    {
                    case "Invalid Request":
                        wEx = new WeatherException(WeatherUtils.ErrorStatus.QueryNotFound);
                        break;

                    case "Unauthorized":
                        wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey);
                        break;

                    default:
                        break;
                    }
                }

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }

                weather = new Weather(root);

                // Add weather alerts if available
                if (root.alerts?.alerts != null && root.alerts.alerts.Length > 0)
                {
                    if (weather.weather_alerts == null)
                    {
                        weather.weather_alerts = new List <WeatherAlert>();
                    }

                    foreach (Alert result in root.alerts.alerts)
                    {
                        weather.weather_alerts.Add(new WeatherAlert(result));
                    }
                }
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "HEREWeatherProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                if (SupportsWeatherLocale)
                {
                    weather.locale = locale;
                }

                weather.query = location_query;
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }
Beispiel #24
0
        public override async Task <LocationQueryViewModel> GetLocation(string query)
        {
            LocationQueryViewModel location = null;

            string queryAPI = "https://autocomplete.wunderground.com/aq?query=";
            string options  = "&h=0&cities=1";
            Uri    queryURL = new Uri(queryAPI + query + options);

            OpenWeather.AC_RESULT result;
            WeatherException      wEx = null;

            try
            {
                // Connect to webstream
                HttpClient          webClient = new HttpClient();
                HttpResponseMessage response  = await webClient.GetAsync(queryURL);

                response.EnsureSuccessStatusCode();
                Stream contentStream = null;
#if WINDOWS_UWP
                contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                contentStream = await response.Content.ReadAsStreamAsync();
#endif

                // End Stream
                webClient.Dispose();

                // Load data
                var root = JSONParser.Deserializer <OpenWeather.AC_Rootobject>(contentStream);
                result = root.RESULTS.FirstOrDefault();

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                result = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                    await Toast.ShowToastAsync(wEx.Message, ToastDuration.Short);
                }
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                    new Android.OS.Handler(Android.OS.Looper.MainLooper).Post(() =>
                    {
                        Toast.MakeText(Application.Context, wEx.Message, ToastLength.Short).Show();
                    });
                }
#endif
                Logger.WriteLine(LoggerLevel.Error, ex, "MetnoWeatherProvider: error getting location");
            }

            if (result != null && !String.IsNullOrWhiteSpace(result.l))
            {
                location = new LocationQueryViewModel(result);
            }
            else
            {
                location = new LocationQueryViewModel();
            }

            return(location);
        }
Beispiel #25
0
        public override async Task <Weather> GetWeather(string location_query)
        {
            Weather weather = null;

            string queryAPI   = null;
            Uri    weatherURL = null;

#if WINDOWS_UWP
            var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();
            var culture  = new System.Globalization.CultureInfo(userlang);
#else
            var culture = System.Globalization.CultureInfo.CurrentCulture;
#endif
            string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);

            string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey();

            queryAPI = "https://api.wunderground.com/api/" + key + "/astronomy/conditions/forecast10day/hourly/alerts/lang:" + locale;
            string options = ".json";
            weatherURL = new Uri(queryAPI + location_query + options);

            HttpClient       webClient = new HttpClient();
            WeatherException wEx       = null;

            try
            {
                // Get response
                HttpResponseMessage response = await webClient.GetAsync(weatherURL);

                response.EnsureSuccessStatusCode();
                Stream contentStream = null;
#if WINDOWS_UWP
                contentStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                contentStream = await response.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                Rootobject root = null;
                await Task.Run(() =>
                {
                    root = JSONParser.Deserializer <Rootobject>(contentStream);
                });

                // Check for errors
                if (root.response.error != null)
                {
                    switch (root.response.error.type)
                    {
                    case "querynotfound":
                        wEx = new WeatherException(WeatherUtils.ErrorStatus.QueryNotFound);
                        break;

                    case "keynotfound":
                        wEx = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey);
                        break;

                    default:
                        break;
                    }
                }

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }

                weather = new Weather(root);

                // Add weather alerts if available
                if (root.alerts != null && root.alerts.Length > 0)
                {
                    if (weather.weather_alerts == null)
                    {
                        weather.weather_alerts = new List <WeatherAlert>();
                    }

                    foreach (Alert result in root.alerts)
                    {
                        weather.weather_alerts.Add(new WeatherAlert(result));
                    }
                }
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherUndergroundProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                if (SupportsWeatherLocale)
                {
                    weather.locale = locale;
                }

                weather.query = location_query;
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }
        public async Task InitializePlaybackList()
        {
            // string uri = "https://channel9.msdn.com/Feeds/RSS"; //"http://www.xamarinpodcast.com/rss";
            string uri = "http://www.xamarinpodcast.com/rss";

            Uri _feedUri;

            if (!Uri.TryCreate(uri, UriKind.Absolute, out _feedUri))
            {
                return;
            }

            var client = new SyndicationClient {
                BypassCacheOnRetrieve = true
            };

            try
            {
                var _currentFeed = await client.RetrieveFeedAsync(_feedUri);

                var title = _currentFeed.Title;

                foreach (var item in _currentFeed.Items)
                {
                    // Display title.
                    var displayTitle = item.Title?.Text ?? "(no title)";
                    if (item.Links.Count > 1)
                    {
                        var linkUri      = item.Links[1].Uri;
                        var artUriString = item.ElementExtensions.FirstOrDefault(e => e.NodeName == "image")?.AttributeExtensions.FirstOrDefault(a => a.Name == "href")?.Value;
                        if (string.IsNullOrEmpty(artUriString))
                        {
                            artUriString = item.ElementExtensions.LastOrDefault(e => e.NodeName == "thumbnail")?.AttributeExtensions.FirstOrDefault(a => a.Name == "url")?.Value;
                        }

                        Uri artUri = null;
                        if (artUriString != null)
                        {
                            artUri = new Uri(artUriString);
                        }

                        var media = new MediaModel(linkUri)
                        {
                            Title = displayTitle, ArtUri = artUri
                        };

                        playlistView.Items.Add(media);
                        playbackList.Items.Add(media.MediaPlaybackItem);
                    }
                }
            }
            catch (Exception ex)
            {
                SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult);
                if (status == SyndicationErrorStatus.InvalidXml)
                {
                    Debug.WriteLine("An invalid XML exception was thrown. " +
                                    "Please make sure to use a URI that points to a RSS or Atom feed.");
                }

                if (status == SyndicationErrorStatus.Unknown)
                {
                    WebErrorStatus webError = WebError.GetStatus(ex.HResult);

                    if (webError == WebErrorStatus.Unknown)
                    {
                        // Neither a syndication nor a web error. Rethrow.
                        throw;
                    }
                }
                Debug.WriteLine(ex.Message);
            }

            // Subscribe for changes
            playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;

            // Loop
            playbackList.AutoRepeatEnabled = true;

            playlistView.SelectedIndex = -1;
        }