Ejemplo n.º 1
0
        public override async Task <bool> IsKeyValid(string key)
        {
            string           queryAPI = "https://api.wunderground.com/api/";
            string           query    = "/q/NY/New_York.json";
            Uri              queryURL = new Uri(queryAPI + key + query);
            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);

                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;

                // End Stream
                webClient.Dispose();

                // Load data
                Rootobject root = await JSONParser.DeserializerAsync <Rootobject>(contentStream);

                // Check for errors
                if (root.response.error != null)
                {
                    switch (root.response.error.type)
                    {
                    case "keynotfound":
                        wEx     = new WeatherException(WeatherUtils.ErrorStatus.InvalidAPIKey);
                        isValid = false;
                        break;
                    }
                }
                else
                {
                    isValid = true;
                }

                // End Stream
                if (contentStream != null)
                {
                    contentStream.Dispose();
                }
            }
            catch (Exception)
            {
                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);
        }