Пример #1
0
        }// end of method GetCityData

        private void SaveGeoNamesSearchResults(string previousCitySearchFile, string cityName)
        {
            string searchURL;

            if (UtilityMethod.HasInternetConnection())
            {
                // now that we have the name of the city, we need some search results from GeoNames
                try
                {
                    int maxRows = 100;

                    // All spaces must be replaced with the + symbols for the HERE Maps web service
                    if (cityName.Contains(" "))
                    {
                        cityName = cityName.Replace(" ", "+");
                    }// end of if block

                    searchURL = string.Format(
                        "http://api.geonames.org/searchJSON?{0}={1}&maxRows={2}&username={3}",
                        QUERY_COMMAND,
                        cityName.ToLower(),
                        maxRows,
                        WidgetUpdateService.geoNameAccount);

                    response = HttpHelper.DownloadUrl(searchURL); // get the search results from the GeoNames web service
                }// end of try block
                catch (Exception e)
                {
                    UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                             TAG + "::handleWeatherData [line: " +
                                             UtilityMethod.GetExceptionLineNumber(e) + "]");

                    response = null;
                }// end of catch block

                // attempt to store the search results locally if this search was not performed before
                if (!File.Exists(previousCitySearchFile))
                {
                    if (response != null)
                    {
                        try
                        {
                            if (JSONHelper.SaveToJSONFile(response, previousCitySearchFile))
                            {
                                UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO,
                                                         "JSON search data stored locally for " + cityName + ".",
                                                         TAG + "::SaveGeoNamesSearchResults");
                            } // end of if block
                        }     // end of try block
                        catch (Exception e)
                        {
                            UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                                     TAG + "::handleWeatherData [line: " +
                                                     UtilityMethod.GetExceptionLineNumber(e) + "]");
                        } // end of catch block
                    }     // end of if block
                }         // end of if block
            }             // end of if block
        }                 // end of method saveGeoNamesSearchResults
        }// end of default constructor

        public void Run()
        {
            try
            {
                // keep track of Internet connectivity
                if (UtilityMethod.TimeForConnectivityCheck())
                {
                    WeatherLionMain.connectedToInternet = UtilityMethod.HasInternetConnection();
                }// end of if block

                // If the program is not connected to the Internet, wait for a connection
                if (WeatherLionMain.connectedToInternet)
                {
                    // if there was no previous Internet connection, check for a return in connectivity
                    // and refresh the widget
                    if (currentWidget.usingPreviousData && UtilityMethod.UpdateRequired())
                    {
                        // run the weather service
                        WidgetUpdateService ws = new WidgetUpdateService(false, currentWidget);
                        ws.Run();
                    } // end of if block
                }     // end of if block

                if (WeatherLionMain.connectedToInternet)
                {
                    currentWidget.picOffline.Visible = false;
                }// end of if block
                else
                {
                    currentWidget.picOffline.Visible = true;
                }// end of else block

                currentWidget.CheckAstronomy();
            }// end of try block
            catch (Exception e)
            {
                UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::Run");
            } // end of catch block
        }     // end of method Run
Пример #3
0
        /// <summary>
        /// Retrieve the data from the weather web service.
        /// </summary>
        public void GetCityData()
        {
            string previousSearchesPath   = $@"{AppDomain.CurrentDomain.BaseDirectory}res\storage\previous_searches\";
            string previousCitySearchFile = null;

            if (dataURL != null)
            {
                if (dataURL.Contains("geonames"))
                {
                    SetService("geo");
                }// end of if block'
                else if (dataURL.Contains("api.here"))
                {
                    SetService("here");
                } // end of else block
            }     // end of if block

            switch (GetService())
            {
            case "geo":
                string cityName        = null;
                string currentLocation = null;

                if (UtilityMethod.HasInternetConnection())
                {
                    // the means that we only have GPS coordinates
                    if (dataURL.Contains("findNearbyPlaceNameJSON"))
                    {
                        response = HttpHelper.DownloadUrl(dataURL);

                        CityData       currentCityData = null;
                        List <dynamic> cityDataList    =
                            JsonConvert.DeserializeObject <List <dynamic> >(response);

                        if (cityDataList != null)
                        {
                            cityName = cityDataList[0]["name"].ToString();
                            string countryName   = cityDataList[0]["countryName"].ToString();
                            string countryCode   = cityDataList[0]["countryCode"].ToString();
                            string localCityName = cityDataList[0]["toponymName"].ToString();
                            string regionCode    = cityDataList[0]["adminCode1"].ToString();
                            string regionName    = cityDataList[0]["countryCode"].ToString().Equals("US") ?
                                                   UtilityMethod.usStatesByCode[regionCode].ToString() :
                                                   null;
                            float latitude  = float.Parse(cityDataList[0]["lat"].ToString());
                            float longitude = float.Parse(cityDataList[0]["lng"].ToString());

                            currentCityData = new CityData
                            {
                                cityName    = cityName,
                                countryName = countryName,
                                countryCode = countryCode,
                                regionCode  = regionCode,
                                regionName  = regionName,
                                latitude    = latitude,
                                longitude   = longitude
                            };

                            if (regionName != null)
                            {
                                currentLocation = cityName + ", " + regionName + ", "
                                                  + countryName;
                            }    // end of if block
                            else
                            {
                                currentLocation = cityName + ", " + countryName;
                            } // end of else block
                        }     // end of if block
                        else
                        {
                            // this means that the user entered a city manually
                            currentLocation = response;
                        }    // end of else block

                        cityName = currentLocation;
                    }    // end of if block
                    else // the URL contains the city name which can be extracted
                    {
                        int start = dataURL.IndexOf(QUERY_COMMAND) + QUERY_COMMAND.Length + 1;
                        int end   = dataURL.IndexOf("&");

                        try
                        {
                            cityName = Uri.UnescapeDataString(GetUrl().Substring(start, end).ToLower());
                            cityName = cityName.ReplaceAll("\\W", " ");
                        }    // end of try block
                        catch (UriFormatException e)
                        {
                            UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                                     TAG + "::handleWeatherData");
                        } // end of else block
                    }     // end of else block

                    // just the city name is required and nothing else
                    if (cityName != null && cityName.Contains(","))
                    {
                        cityName = cityName.Substring(0, cityName.IndexOf(",")).ToLower();
                    }    // end of if block // end of if block

                    StringBuilder fileData = new StringBuilder();

                    if (cityName != null)
                    {
                        previousCitySearchFile = $@"{previousSearchesPath}gn_sd_{cityName.ReplaceAll(" ", "_")}.json";
                    }    // end of if block

                    if (File.Exists(previousCitySearchFile))
                    {
                        // use the file from the local storage
                        strJSON =
                            File.ReadAllText($"{previousSearchesPath}gn_sd_{cityName.ReplaceAll(" ", "_")}.json");
                    }    // end of if block
                    else
                    {
                        SaveGeoNamesSearchResults(previousCitySearchFile, cityName);
                    } // end of else block
                }     // end of if block

                break;

            case "here":
                // I prefer to use the GeoNames search results as the Here results only returns a single city.
                // I might just add if in the future though.
                break;

            default:
                break;
            }// end of switch block

            ProcessCityData();
        }// end of method GetCityData
        /// <summary>
        /// Load a required assets and prepare for program execution
        /// </summary>
        public static void Launch()
        {
            #region WeatherLion launch sequence

            UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Initiating startup...", "WeatherLionMain::Launch");

            // build the required storage files
            if (BuildRequiredDatabases() == 1)
            {
                UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO,
                                         "All required databases constructed successfully.",
                                         "WeatherLionMain::Launch");
            }// end of if block
            else
            {
                UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE,
                                         "All required databases were not constructed successfully.",
                                         "WeatherLionMain::Launch");
            }// end of else block

            // check that the required access keys are available
            LionSecurityManager.Init();

            // Load only the providers who have access keys assigned to them
            List <string> wxOnly = LionSecurityManager.webAccessGranted;

            wxOnly.Sort();  // sort the list

            // GeoNames is not a weather provider so it cannot be select here
            wxOnly.Remove("GeoNames");

            authorizedProviders = wxOnly.ToArray();

            // ensure that program has all the default assets needed for functioning properly
            HealthCheck();

            // load user preferences
            storedPreferences = Preference.GetSavedPreferences();

            string previousWeatherData = $"{DATA_DIRECTORY_PATH}{WEATHER_DATA_XML}";

            connectedToInternet = UtilityMethod.HasInternetConnection();

            // check for an Internet connection or previous weather data stored local
            if (!connectedToInternet && !File.Exists(previousWeatherData))
            {
                UtilityMethod.ShowMessage("The program will not run without a working internet connection or "
                                          + "data that was previously stored locally" +
                                          "\nResolve your Internet connection and relaunch the program.", null);

                Application.Exit(); // terminate the program
            }// end of if block
            else if (connectedToInternet)
            {
                // obtain the current city of the connected Internet service
                currentCity = UtilityMethod.GetSystemLocation();

                if (currentCity != null)
                {
                    if (currentCity.regionCode != null)
                    {
                        systemLocation = $"{currentCity.cityName}, {currentCity.regionCode}";
                    }// end of if block
                    else
                    {
                        systemLocation = $"{currentCity.cityName}, {currentCity.countryName}";
                    } // end of else block
                }     // end of if block

                // if the user requires the current detected city location to be used as default
                if (storedPreferences.StoredPreferences.UseSystemLocation)
                {
                    if (systemLocation != null)
                    {
                        // use the detected city location as the default
                        storedPreferences.StoredPreferences.Location = systemLocation;

                        if (!storedPreferences.StoredPreferences.Location.Equals(systemLocation))
                        {
                            // update the preferences file
                            Preference.SaveProgramConfiguration("prefs", "Location", systemLocation);

                            // save the city to the local WorldCites database
                            UtilityMethod.AddCityToDatabase(
                                currentCity.cityName, currentCity.countryName,
                                currentCity.countryCode, currentCity.regionName,
                                currentCity.regionCode, currentCity.latitude,
                                currentCity.longitude);

                            JSONHelper.ExportToJSON(currentCity);
                            XMLHelper.ExportToXML(currentCity);
                        } // end of if block
                    }     // end of if block
                    else
                    {
                        UtilityMethod.ShowMessage("The program was unable to obtain your system's location."
                                                  + "\nYour location will have to be set manually using the preferences dialog.", null);

                        PreferencesForm pf = new PreferencesForm();
                        pf.Show();
                    } // end of else block
                }     // end of if block
            }         // end of else if block

            Init();

            #endregion
        }// end of method Launch