}// end on seven-argument constructor

        public static bool DeserializeCityJSON(string cityJSON, ref CityData cityData)
        {
            cityData = JsonConvert.DeserializeObject<CityData>(cityJSON);

            if (cityData == null)
            {
                return false;
            }// end of if block
            else
            {
                return true;
            }// end of else block            
        }// end of method DeserializeCityJSON       
Exemple #2
0
        /// <summary>
        /// Accepts a CityData object and exports it to a JSON file.
        /// </summary>
        /// <param name="cityData">The CityData object to be written to a JSON file.</param>
        /// <returns>A <see cref="bool"/> value representing success or failure</returns>
        public static bool ExportToJSON(CityData dataItem)
        {
            if (dataItem != null)
            {
                try
                {
                    string          strJSON       = null;
                    string          convertedJson = null;
                    List <CityData> cityDataList;

                    // check for the parent directory
                    if (!Directory.Exists(Directory.GetParent(PREVIOUSLY_FOUND_CITIES_JSON).FullName))
                    {
                        Directory.CreateDirectory(Directory.GetParent(PREVIOUSLY_FOUND_CITIES_JSON).FullName);
                    }// end of if block

                    if (File.Exists(PREVIOUSLY_FOUND_CITIES_JSON))
                    {
                        strJSON      = File.ReadAllText(PREVIOUSLY_FOUND_CITIES_JSON);
                        cityDataList = JsonConvert.DeserializeObject <List <CityData> >(strJSON);
                        cityDataList.Add(dataItem);
                        convertedJson = JsonConvert.SerializeObject(cityDataList, Formatting.Indented);
                    }// end of if block
                    else
                    {
                        cityDataList = new List <CityData> {
                            dataItem
                        };                                              // create an array so that more items can be added later
                        convertedJson = JsonConvert.SerializeObject(cityDataList, Formatting.Indented);
                    }// end of else block

                    using (var jsonWriter = new StreamWriter(PREVIOUSLY_FOUND_CITIES_JSON, false))
                    {
                        jsonWriter.WriteLine(JsonPrettify(convertedJson));
                    }// end of using block

                    return(true);
                }// end of try block
                catch (Exception e)
                {
                    UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                             $"{TAG}::ExportToJSON [line: {UtilityMethod.GetExceptionLineNumber(e)}]");
                    return(false);
                } // end of catch block
            }     // enn of if block
            else
            {
                return(false);
            } // end of else block
        }     // end of method ExportToJSON
Exemple #3
0
        }// end of method Run

        /// <summary>
        /// Add new location locally if it does not already exists
        /// </summary>
        private void StoreNewLocationLocally()
        {
            string[] searchCity = city.Split(',');

            foreach (GeoNamesGeoLocation.GeoNames foundCity in GeoNamesGeoLocation.cityGeographicalData
                     .geonames)
            {
                if (foundCity.name.Equals(searchCity[0].Trim().ToLower(), StringComparison.OrdinalIgnoreCase) &&
                    foundCity.adminCodes1.iso.Equals(searchCity[1].Trim(), StringComparison.OrdinalIgnoreCase) &&
                    !UtilityMethod.IsNumeric(foundCity.adminCodes1.iso) ||
                    foundCity.countryName.Equals(searchCity[1].Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    string cityName    = UtilityMethod.ToProperCase(foundCity.name);
                    string countryName = UtilityMethod.ToProperCase(foundCity.countryName);
                    string countryCode = foundCity.countryCode.ToUpper();
                    string regionName  = UtilityMethod
                                         .ToProperCase(foundCity.adminName1);

                    string regionCode = null;
                    regionCode = foundCity.adminCodes1.iso?.ToUpper();

                    float Latitude  = float.Parse(foundCity.lat);
                    float Longitude = float.Parse(foundCity.lng);

                    CityData cityData = new CityData(cityName, countryName, countryCode,
                                                     regionName, regionCode, Latitude, Longitude);

                    string currentCity = regionCode != null ? $"{cityName}, {regionCode}" : $"{cityName}, {countryName}";

                    if (!UtilityMethod.IsFoundInDatabase(currentCity))
                    {
                        UtilityMethod.AddCityToDatabase(cityName, countryName, countryCode,
                                                        regionName, regionCode, Latitude, Longitude);
                    }// end of if block

                    if (!UtilityMethod.IsFoundInJSONStorage(currentCity))
                    {
                        JSONHelper.ExportToJSON(cityData);
                    }// end of if block

                    if (!UtilityMethod.IsFoundInXMLStorage(currentCity))
                    {
                        XMLHelper.ExportToXML(cityData);
                    } // end of if block
                }     // end of if block
            }         // end of for each loop
        }             // end of method StoreNewLocationLocally
Exemple #4
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
Exemple #5
0
        /// <summary>
        /// Accepts a CityData object and exports it to an XML file.
        /// </summary>
        /// <param name="cityData">The CityData object to be written to an XML file.</param>
        /// <returns>A <see cref="bool"/> value representing success or failure</returns>
        public static bool ExportToXML(CityData cityData)
        {
            if (cityData != null)
            {
                try
                {
                    bool              append;
                    XmlWriter         writer;
                    XmlDocument       xmlDoc   = new XmlDocument();
                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent             = true,
                        IndentChars        = ("\t"),
                        CloseOutput        = true,
                        OmitXmlDeclaration = false
                    };

                    // check for the parent directory
                    if (!Directory.Exists(Directory.GetParent(PREVIOUSLY_FOUND_CITIES_XML).FullName))
                    {
                        Directory.CreateDirectory(Directory.GetParent(PREVIOUSLY_FOUND_CITIES_XML).FullName);
                    }// end of if block

                    if (File.Exists(PREVIOUSLY_FOUND_CITIES_XML))
                    {
                        xmlDoc.Load(PREVIOUSLY_FOUND_CITIES_XML);
                        XmlElement root = xmlDoc.DocumentElement;

                        writer = root.CreateNavigator().AppendChild();
                        append = true;
                    }// end of if block
                    else
                    {
                        writer = XmlWriter.Create(PREVIOUSLY_FOUND_CITIES_XML, settings);
                        append = false;
                    }// end of else block

                    // Root element
                    if (!append)
                    {
                        writer.WriteStartElement("WorldCities");
                    }
                    writer.WriteStartElement("City");
                    writer.WriteElementString("CityName", cityData.cityName);
                    writer.WriteElementString("CountryName", cityData.countryName);
                    writer.WriteElementString("CountryCode", cityData.countryCode);
                    writer.WriteElementString("RegionName", cityData.regionName);
                    writer.WriteElementString("RegionCode", cityData.regionCode);
                    writer.WriteElementString("Latitude", cityData.latitude.ToString());
                    writer.WriteElementString("Longitude", cityData.longitude.ToString());
                    writer.WriteEndElement();
                    if (!append)
                    {
                        writer.WriteEndElement();
                    }
                    writer.Flush();
                    writer.Close();

                    if (append)
                    {
                        xmlDoc.Save(PREVIOUSLY_FOUND_CITIES_XML);
                    }

                    return(true);
                }// end of try block
                catch (Exception e)
                {
                    UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                             $"{TAG}::ExportToXML [line: {UtilityMethod.GetExceptionLineNumber(e)}]");
                    return(false);
                } // end of catch block
            }     // end of if block
            else
            {
                return(false);
            } // end of else block
        }     // end of method ExportToXML
        /// <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