public static string DownloadUrl(string address) { string serviceData = null; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; try { using (WebClient client = new WebClient()) { serviceData = client.DownloadString(address); } // end of outer using } // end of try block catch (WebException we) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, we.Message, $"{TAG}::DownloadUrl [line: {UtilityMethod.GetExceptionLineNumber(we)}]"); }// end of catch block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::DownloadUrl [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block return(serviceData); } // end of method DownloadUrl
}// 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 method CreateDefaultUserPreferences /// <summary> /// Create a default configuration file for the program /// </summary> private static void CreateDefaultAppConfiguration() { // if the directory does not exist then no previous configuration exists if (!Directory.Exists(SETTING_DIRECTORY)) { Directory.CreateDirectory(SETTING_DIRECTORY); try { using (var stream = File.Create(CONFIG_FILE)) { }; }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block else if (!File.Exists(CONFIG_FILE)) { try { using (var stream = File.Create(CONFIG_FILE)) { }; }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block try { using (StreamWriter swWriter = File.CreateText(CONFIG_FILE)) { int screenHeight = Screen.PrimaryScreen.WorkingArea.Height / 2; int screenWidth = Screen.PrimaryScreen.WorkingArea.Width / 2; m_widget_config = new ConfigurationData(new Point(screenWidth, screenHeight)); Type tType = m_widget_config.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); xsSerializer.Serialize(swWriter, m_widget_config); } // end of using block } // end of try block catch (FileNotFoundException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of method CreateDefaultAppConfiguration
} // end of method GetPreferencesData /// <summary> /// Creates the default user preferences file for the program /// </summary> private static void CreateDefaultUserPreferences() { // if the directory does not exist then no previous configuration exists if (!Directory.Exists(SETTING_DIRECTORY)) { Directory.CreateDirectory(SETTING_DIRECTORY); try { using (var stream = File.Create(PREFERENCE_FILE)) { }; }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block else if (!File.Exists(PREFERENCE_FILE)) { try { using (var stream = File.Create(PREFERENCE_FILE)) { }; }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block try { using (StreamWriter swWriter = File.CreateText(PREFERENCE_FILE)) { m_widget_preferences = new PreferencesData(WeatherLionMain.authorizedProviders[0], 1800000, "not set", false, false, "default", "miui"); Type tType = m_widget_preferences.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); xsSerializer.Serialize(swWriter, m_widget_preferences); } // end of using block } // end of try block catch (FileNotFoundException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CreatedefaultPreferencesPropertiesFile [line: " + $"{UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of method CreateDefaultUserPreferences
}// end of method GetConnection // method that closes the database connection public void Close() { try { conn.Close(); conn = null; }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::Close [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of method close()
/// <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
}// end of method GetInstance // method that opens a database connection private bool OpenConnection() { try { conn = new SQLiteConnection($"Data Source={@SQLITE_CONN_STRING};FailIfMissing=True;"); return(true); }// end of try black catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::OpenConnection [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); return(false); } // end of catch block } // end of method openConnection
}// end of method SaveCurrentWeatherXML public static void UpdateUnits(string currentTemperature, string currentFeelsLikeTemperture, string currentHigh, string currentLow, string currentWindSpeed, List <FiveDayForecast> fiveDayForecast) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(previousWeatherDataXML); XmlNode node = null; XmlNode root = xmlDoc.DocumentElement; node = xmlDoc.SelectSingleNode("//Temperature"); node.InnerText = currentTemperature; node = xmlDoc.SelectSingleNode("//FeelsLike"); node.InnerText = currentFeelsLikeTemperture; node = xmlDoc.SelectSingleNode("//HighTemperature"); node.InnerText = currentHigh; node = xmlDoc.SelectSingleNode("//LowTemperature"); node.InnerText = currentLow; node = xmlDoc.SelectSingleNode("//WindSpeed"); node.InnerText = currentWindSpeed; // Five Day Forecast XmlNodeList forecastList = xmlDoc.SelectNodes("//ForecastList/ForecastData"); for (int i = 0; i < forecastList.Count; i++) { XmlNode lowTemp = ((XmlElement)forecastList[i]).SelectSingleNode(".//LowTemperature"); lowTemp.InnerText = fiveDayForecast[i].forecastLowTemp; XmlNode highTemp = ((XmlElement)forecastList[i]).SelectSingleNode(".//HighTemperature"); highTemp.InnerText = fiveDayForecast[i].forecastHighTemp; }// end of for loop // save the updated units xmlDoc.Save(previousWeatherDataXML); }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::UpdateUnits [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of method UpdateUnits
}// end of method BuildRequiredDatabases private static void Init() { if (!LocationCheck()) { UtilityMethod.ShowMessage("The program will not run without a location set.\n" + "Enjoy the weather!", null, title: $"{PROGRAM_NAME} - Setup"); Application.Exit(); // terminate the program }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Necessary requirements met...", $"{TAG}::Init"); UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Launching Weather Widget...", $"{TAG}::Init"); } // end of else block } // end of method Init
/// <summary> /// Determines is the computer has an open Internet connection /// </summary> /// <returns>True/False dependent on the outcome of the check.</returns> public static bool HasNetworkAccess() { try { using (var client = new WebClient()) { using (client.OpenRead("http://clients3.google.com/generate_204")) { return(true); } // end of inner using } // end of outer using } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::HasNetworkAccess [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); return(false); } // end of catch block } // end of method HasNetworkAccess
} // end of method GetConfigurationData /// <summary> /// /// </summary> private void GetPreferencesData() { if (File.Exists(PREFERENCE_FILE)) { try { StreamReader srReader = File.OpenText(PREFERENCE_FILE); Type tType = m_widget_preferences.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); object oData = xsSerializer.Deserialize(srReader); m_widget_preferences = (PreferencesData)oData; srReader.Close(); }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::GetPreferencesData [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block } // end of method GetPreferencesData
} // end of method ExportToXML /// <summary> /// Converts XML data and converts them into a list of CityData objects. /// </summary> /// <returns>A <see cref="List{T}"/> containing CityData objects that were converted from XML</returns> public static List <CityData> ImportFromXML() { List <CityData> cd = new List <CityData>(); try { XmlDocument serviceData = new XmlDocument(); serviceData.Load(PREVIOUSLY_FOUND_CITIES_XML); if (serviceData != null) { XmlNodeList xnlCity = serviceData.SelectNodes("//City"); for (int i = 0; i < xnlCity.Count; i++) { string cityName = xnlCity[i].ChildNodes[0].InnerText; string countryName = xnlCity[i].ChildNodes[1].InnerText; string countryCode = xnlCity[i].ChildNodes[2].InnerText; string regionName = xnlCity[i].ChildNodes[3].InnerText; string regionCode = xnlCity[i].ChildNodes[4].InnerText; string latitude = xnlCity[i].ChildNodes[5].InnerText; string Longitude = xnlCity[i].ChildNodes[6].InnerText; cd.Add( new CityData( xnlCity[i].ChildNodes[0].InnerText, xnlCity[i].ChildNodes[1].InnerText, xnlCity[i].ChildNodes[2].InnerText, xnlCity[i].ChildNodes[3].InnerText, xnlCity[i].ChildNodes[4].InnerText, float.Parse(xnlCity[i].ChildNodes[5].InnerText), float.Parse(xnlCity[i].ChildNodes[6].InnerText) )); } // end of for loop } // end of if block } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::ImportFromXML [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block return(cd); } // end of method ImportFromXML
}// end of method ImportFromJSON /// <summary> /// Saves JSON data to a local file for quicker access later. /// </summary> /// <param name="jsonData">JSON data formatted as a <see cref="string"/>.</param> /// <param name="path">The path where the data will reside locally.</param> /// <returns>True/False depending on the success of the operation.</returns> public static bool SaveToJSONFile(string jsonData, string path) { bool fileSaved = false; try { if (jsonData != null) { string parentPath = Directory.GetParent(path).ToString(); // the storage directory must be present before file creation if (!Directory.Exists(parentPath)) { Directory.CreateDirectory(parentPath); }// end of if block if (!File.Exists(path)) { using (var jsonWriter = new StreamWriter(path, false)) { jsonWriter.WriteLine(JsonPrettify(jsonData)); } // end of using block } // end of if block else { // file already exists fileSaved = false; }// end of else block return(true); } // end of if block } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::SaveToJSONFile [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block return(fileSaved); }// end of method SaveToJSONFile
}// end of method Encrypt /// <summary> /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string /// </summary> /// <param name="cipherString">encrypted string</param> /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param> /// <returns></returns> public static string Decrypt(string cipherString, string hexKey, bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherString); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hexKey)); hashmd5.Clear(); }// end of if block else { keyArray = UTF8Encoding.UTF8.GetBytes(hexKey); }// end of else block TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = null; try { resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::Decrypt [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block tdes.Clear(); return(UTF8Encoding.UTF8.GetString(resultArray)); }// end of method Decrypt
}// end of default constructor public static void Init() { // create all necessary files if they are not present if (!Directory.Exists(databasePath)) { try { Directory.CreateDirectory(databasePath); File.Create(databaseFile); }// end of try black catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::init [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block if (!File.Exists(databaseFile)) { try { File.Create(databaseFile); UtilityMethod.CreateWSADatabase(); addKeys.Show(); }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::init [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block else if (!UtilityMethod.CheckIfTableExists("wak", "access_keys")) { UtilityMethod.CreateWSADatabase(); UtilityMethod.ShowMessage(announcement, addKeys, WeatherLionMain.PROGRAM_NAME + " - IMPORTANT", MessageBoxButtons.OK, MessageBoxIcon.Information); }// end of else if block LoadAccessProviders(); }// end of method init
}// 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
}// end of method Launch private static int AttachDatabase(string dbName, string alias) { string attachSQL = $"ATTACH DATABASE '{dbName}' as {alias}"; try { //conn.Open(); using (SQLiteCommand comm = conn.CreateCommand()) { comm.CommandText = attachSQL; IDataReader dr = comm.ExecuteReader(); return(1); } // end of using block } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"WeatherLionMain::AttachDatabase [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); return(0); } // end of catch block } // end of method AttachDatabase
} // end of method ExportToJSON /// <summary> /// Converts JSON data and converts them into a list of CityData objects. /// </summary> /// <returns>A <see cref="List{T}"/> containing CityData objects that were converted from JSON</returns> public static List <CityData> ImportFromJSON() { string strJSON = null; List <CityData> cityDataList = null; try { // if there is a file present then it will contain a list with at least one object if (File.Exists(PREVIOUSLY_FOUND_CITIES_JSON)) { strJSON = File.ReadAllText(PREVIOUSLY_FOUND_CITIES_JSON); // convert the file JSON into a list of objects cityDataList = JsonConvert.DeserializeObject <List <CityData> >(strJSON); } // end of if block } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::ImportFromJSON [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block return(cityDataList); }// end of method ImportFromJSON
} // end of method GetSiteKeyFromDatabase /** * Load all access providers stored in the database */ public static void LoadAccessProviders() { ArrayList appKeys = new ArrayList(); webAccessGranted = new List <string>(); try { foreach (string provider in WeatherLionMain.providerNames) { appKeys = GetSiteKeyFromDatabase(provider); if (appKeys != null) { switch (provider) { case "Dark Sky Weather": foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)darkSkyRequiredKeys).Contains(kv[0].ToLower())) { WidgetUpdateService.darkSkyApiKey = Decrypt(kv[1], kv[2], true); } // end of if block } // end of for each loop if (WidgetUpdateService.darkSkyApiKey != null) { webAccessGranted.Add("Dark Sky Weather"); } // end of if block break; case "GeoNames": foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)geoNamesRequiredKeys).Contains(kv[0].ToLower())) { WidgetUpdateService.geoNameAccount = Decrypt(kv[1], kv[2], true); } // end of if block } // end of for each loop if (WidgetUpdateService.geoNameAccount != null) { webAccessGranted.Add("GeoNames"); geoNamesAccountLoaded = true; } // end of if block break; case "Open Weather Map": foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)openWeatherMapRequiredKeys).Contains(kv[0].ToLower())) { WidgetUpdateService.openWeatherMapApiKey = Decrypt(kv[1], kv[2], true); } // end of if block } // end of for each loop if (WidgetUpdateService.openWeatherMapApiKey != null) { webAccessGranted.Add("Open Weather Map"); } // end of if block break; case "Weather Bit": foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)weatherBitRequiredKeys).Contains(kv[0].ToLower())) { WidgetUpdateService.weatherBitApiKey = Decrypt(kv[1], kv[2], true); } // end of if block } // end of for each loop if (WidgetUpdateService.weatherBitApiKey != null) { webAccessGranted.Add("Weather Bit"); } // end of if block break; case "Here Maps Weather": foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)hereMapsRequiredKeys).Contains(kv[0].ToLower())) { switch (kv[0].ToLower()) { case "app_id": WidgetUpdateService.hereAppId = Decrypt(kv[1], kv[2], true); break; case "app_code": WidgetUpdateService.hereAppCode = Decrypt(kv[1], kv[2], true); break; default: break; } // end of switch block } // end of if block } // end of for each loop if (WidgetUpdateService.hereAppId != null && WidgetUpdateService.hereAppCode != null) { webAccessGranted.Add("Here Maps Weather"); } // end of if block else if (WidgetUpdateService.hereAppId != null && WidgetUpdateService.hereAppCode == null) { UtilityMethod.ShowMessage("Here Maps Weather requires an app_code which is" + " not stored in the database.", title: WeatherLionMain.PROGRAM_NAME + " - Missing Key", mbIcon: MessageBoxIcon.Error); } // end of if block else if (WidgetUpdateService.hereAppId == null && WidgetUpdateService.hereAppCode != null) { UtilityMethod.ShowMessage("Here Maps Weather requires an app_id which is" + " not stored in the database.", title: WeatherLionMain.PROGRAM_NAME + " - Missing Key", mbIcon: MessageBoxIcon.Error); } // end of if block break; case "Yahoo! Weather": List <string> keysFound = new List <string>(); foreach (string key in appKeys) { string[] kv = key.Split(':'); if (((IList <string>)yahooRequiredKeys).Contains(kv[0].ToLower())) { switch (kv[0].ToLower()) { case "app_id": WidgetUpdateService.yahooAppId = Decrypt(kv[1], kv[2], true); keysFound.Add("app_id"); break; case "consumer_key": WidgetUpdateService.yahooConsumerKey = Decrypt(kv[1], kv[2], true); keysFound.Add("consumer_key"); break; case "consumer_secret": WidgetUpdateService.yahooConsumerSecret = Decrypt(kv[1], kv[2], true); keysFound.Add("consumer_secret"); break; default: break; } // end of switch block } // end of if block } // end of for each loop // remove all the keys that were found from the list keysMissing = new List <string>(((IList <string>)yahooRequiredKeys).Except(keysFound).ToList()); if (keysMissing.Count == 0) { webAccessGranted.Add("Yahoo! Weather"); } // end of if block else { // do not check for missing keys if the form is already displayed if (!addKeys.Visible) { if (CheckForMissingKeys() == DialogResult.Yes) { AccessKeysForm.frmKeys.cboAccessProvider.SelectedItem = "Yahoo! Weather"; AccessKeysForm.frmKeys.Visible = true; AccessKeysForm.frmKeys.Focus(); } // end of if block else { string msg = "Yahoo!Weather cannot be used as a weather source without " + "first adding the missing " + (keysMissing.Count > 1 ? "keys" : "key") + "."; UtilityMethod.ShowMessage(msg, AccessKeysForm.frmKeys, title: $"{WeatherLionMain.PROGRAM_NAME} - Missing Key", buttons: MessageBoxButtons.OK, mbIcon: MessageBoxIcon.Information); } // end of else block } // end of if block else { AccessKeysForm.frmKeys.txtKeyName.Focus(); } // end of else block } // end of else block break; default: break; } // end of switch block } // end of if block } // end of outer for each loop } // end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::LoadAccessProviders [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block // add the only weather provider that does not require a key webAccessGranted.Add(WeatherLionMain.YR_WEATHER); if (webAccessGranted.Count > 0) { string s = string.Join(", ", webAccessGranted); string fs = null; if (UtilityMethod.NumberOfCharacterOccurences(',', s) > 1) { fs = UtilityMethod.ReplaceLast(",", ", and", s); }// end of if block else if (UtilityMethod.NumberOfCharacterOccurences(',', s) == 1) { fs = s.Replace(",", " and"); }// end of else block else { fs = s; }// end of else block UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, $"The following access providers were loaded:\n{fs}.", $"{TAG}::LoadAccessProviders"); }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, "No valid access privelages were stored in the database!", $"{TAG}::LoadAccessProviders"); }// end of else block if (webAccessGranted.Count == 0) { if (NoAccessPrivialgesStored() == DialogResult.Yes) { if (!AccessKeysForm.frmKeys.Visible) { AccessKeysForm.frmKeys.ShowDialog(); AccessKeysForm.frmKeys.Focus(); }// end of if block else { AccessKeysForm.frmKeys.txtKeyName.Focus(); }// end of else block } else { UtilityMethod.MissingRequirementsPrompt("Insufficient Access Privilages"); } // end of if block } // end of if block if (webAccessGranted.Count >= 1 && !geoNamesAccountLoaded) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, "GeoNames user name not found!", $"{TAG}::LoadAccessProviders"); // confirm that user has a GeoNames account and want's to store it string prompt = "This program requires a geonames username\n" + "which was not stored in the database. IT IS FREE!" + "\nDo you wish to add it now?"; DialogResult result = MessageBox.Show(prompt, $"{WeatherLionMain.PROGRAM_NAME} - Add Access Privialges", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) { //AccessKeysForm kf = AccessKeysForm.frmKeys; if (!AccessKeysForm.frmKeys.Visible) { AccessKeysForm.frmKeys.m_key_provider = "GeoNames"; AccessKeysForm.frmKeys.ShowDialog(); }// end of if block else { AccessKeysForm.frmKeys.cboAccessProvider.SelectedItem = "GeoNames"; AccessKeysForm.frmKeys.pwdKeyValue.Focus(); } // end of else block } // end of if block else { UtilityMethod.MissingRequirementsPrompt("Insufficient Access Privilages"); } // end of else block } // end of else if block // if valid access was not loaded for the provider previously used, take it into account if (WeatherLionMain.storedPreferences != null) { if (!webAccessGranted.Contains(WeatherLionMain.storedPreferences.StoredPreferences.Provider)) { WeatherLionMain.noAccessToStoredProvider = true; }// end of if block else { WeatherLionMain.noAccessToStoredProvider = false; } // end of else block } // end of if block } // end of method LoadAccessProcviders
} // end of method Init private static void HealthCheck() { // the program CANNOT RUN with the assets directory if (!Directory.Exists(ASSETS_PATH)) { UtilityMethod.MissingRequirementsPrompt("Missing Assets Directory"); }// end of if block else { UtilityMethod.subDirectoriesFound.Clear(); // clear any previous list List <string> iconPacks = UtilityMethod.GetSubdirectories(WEATHER_ICONS_PATH); if (iconPacks == null || iconPacks.Count == 0) { UtilityMethod.MissingRequirementsPrompt("Empty Assets Directory"); }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Found " + iconPacks.Count + " icon " + (iconPacks.Count > 1 ? "packs..." : "pack..."), $"{TAG}::HealthCheck"); if (!iconPacks.Contains(DEFAULT_ICON_SET)) { UtilityMethod.MissingRequirementsPrompt("Missing Default Icons"); }// end of if block else if (!iconPacks.Contains(Preference.GetSavedPreferences().StoredPreferences.IconSet)) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.WARNING, $"The {storedPreferences.StoredPreferences.IconSet.ToUpper()}" + $" icon pack could not be found so the default {DEFAULT_ICON_SET.ToUpper()}" + " will be used!", $"{TAG}::HealthCheck"); Preference.SaveProgramConfiguration("prefs", "IconSet", "default"); }// end of else if block else { string iconsInUse = $"{WEATHER_ICONS_PATH}{storedPreferences.StoredPreferences.IconSet}/"; int imageCount = UtilityMethod.GetFileCount(iconsInUse); if (imageCount < 23) { UtilityMethod.MissingRequirementsPrompt("Insufficient Icon Count"); }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, $"Found {imageCount}" + (imageCount > 1 ? " images" : " image") + " in the " + UtilityMethod.ToProperCase(storedPreferences.StoredPreferences.IconSet) + " icon pack...", $"{TAG}::HealthCheck"); }// end of else block // check for the background and icon images if (!Directory.Exists(WIDGET_BACKGROUNDS_PATH)) { UtilityMethod.MissingRequirementsPrompt("Missing Background Image Directory"); }// end of if block else { imageCount = UtilityMethod.GetFileCount(WIDGET_BACKGROUNDS_PATH); if (imageCount < 3) { UtilityMethod.MissingRequirementsPrompt(imageCount > 1 ? "Missing Background Images" : "Missing Background Image"); }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Found " + imageCount + (imageCount > 1 ? " images" : " image") + " in the backgrounds directory...", $"{TAG}::HealthCheck"); } // end of else block } // end of else block if (!Directory.Exists(WIDGET_ICONS_PATH)) { UtilityMethod.MissingRequirementsPrompt("Missing Background Image Directory"); }// end of if block else { imageCount = UtilityMethod.GetFileCount(WIDGET_ICONS_PATH); if (imageCount < 11) { UtilityMethod.MissingRequirementsPrompt(imageCount > 1 ? "Missing Icon Images" : "Missing Icon Image"); }// end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "Found " + imageCount + (imageCount > 1 ? " images" : " image") + " in the icons directory...", $"{TAG}::HealthCheck"); } // end of else block } // end of else block } // end of else block } // end of else block } // end of else block } // end of method HealthCheck
}// end of method DoInBackground protected void Done() { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, log, "CityStorageService::Done"); }// end of method Done
} // end of method IconSetChanged // Load all available icon packs private void LoadInstalledIconPacks() { if (WeatherLionMain.iconPackList.Count > 0) { WeatherLionMain.iconPackList.Clear(); WeatherLionMain.iconSetControls.Clear(); WeatherLionMain.iconPacksLoaded = false; }// end of if block WeatherLionMain.iconPackList = UtilityMethod.GetSubdirectories("res/assets/img/weather_images"); WeatherLionMain.iconSetControls = new Hashtable(); // Add icon packs dynamically foreach (string packName in WeatherLionMain.iconPackList) { FlowLayoutPanel iconSelectionContainer = new FlowLayoutPanel { Size = new Size(140, 148) }; //iconSelectionContainer.BorderStyle = BorderStyle.FixedSingle; var margin = iconSelectionContainer.Margin; margin.Bottom = 10; iconSelectionContainer.Margin = margin; Label packTitle = new Label { AutoSize = false, Text = UtilityMethod.ToProperCase(packName), TextAlign = ContentAlignment.MiddleCenter, Size = new Size(iconSelectionContainer.Width, 20), Font = new Font("Arial", 11, FontStyle.Bold) }; string wiPath = $@"{AppDomain.CurrentDomain.BaseDirectory}res\assets\img\weather_images\"; bool previewImageExists = File.Exists($@"{wiPath}{packName}\preview_image.png"); string displayIcon = previewImageExists ? "preview_image.png" : "weather_10.png"; string wxIcon = $@"{wiPath}{packName}\{displayIcon}"; PictureBox packDefaultImage = new PictureBox { ImageLocation = wxIcon, Name = $"pic{UtilityMethod.ToProperCase(packName)}", SizeMode = PictureBoxSizeMode.Zoom, Size = new Size(iconSelectionContainer.Width, 100), Tag = packName.ToLower() }; RadioButton iconSelector = new RadioButton { AutoSize = false, BackColor = Color.Transparent, CheckAlign = ContentAlignment.MiddleCenter, Name = $"rad{UtilityMethod.ToProperCase(packName)}", Size = new Size(iconSelectionContainer.Width, 14), Tag = packName.ToLower() }; iconSelector.CheckedChanged += new EventHandler(IconSetChanged); iconSelectionContainer.Controls.Add(packTitle); iconSelectionContainer.Controls.Add(packDefaultImage); iconSelectionContainer.Controls.Add(iconSelector); // Add icon selections to FlowLayoutPanel flpIconSet.Controls.Add(iconSelectionContainer); List <Control> components = new List <Control> { packTitle, // Add the component that displays the icon pack title packDefaultImage, // Add the component that displays the icon pack default image iconSelector // Add the component that displays the radio button to select the pack }; WeatherLionMain.iconSetControls.Add(packName, components); }// end of foreach loop //string set = "hero"; //(un-comment during testing) string set = WeatherLionMain.storedPreferences.StoredPreferences.IconSet; ((RadioButton) ((List <Control>) WeatherLionMain.iconSetControls[set])[2]).Checked = true; WeatherLionMain.iconPacksLoaded = true; StringBuilder packs = new StringBuilder(string.Join(", ", WeatherLionMain.iconPackList.ToArray())); packs.Insert(packs.ToString().LastIndexOf(",") + 1, " and"); UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, $"Icon Packs Installed: {packs.ToString()}", $"{TAG}::LoadInstalledIconPacks"); }// end of method LoadInstalledIconPacks
} // end of method HealthCheck public static bool LocationCheck() { bool locationSet = false; if (storedPreferences.StoredPreferences.Location.Equals("not set")) { DialogResult setCurrentCity; if (systemLocation != null) { string prompt = "You must specify a current location in order to run the program. " + $"Your current location is detected as {systemLocation}.\n" + "Would you like to use it as your current location?"; DialogResult useSystemLocation = UtilityMethod.ResponseBox(prompt, PROGRAM_NAME + " - Setup"); if (useSystemLocation == DialogResult.Yes) { storedPreferences.StoredPreferences.UseSystemLocation = true; storedPreferences.StoredPreferences.Location = systemLocation; Preference.SaveProgramConfiguration("prefs", "UseSystemLocation", "true"); 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); locationSet = true; Application.Run(new WidgetForm()); }// end of if block else { prompt = "You must specify a current location in order to run the program.\n" + "Would you like to specify it now?"; setCurrentCity = UtilityMethod.ResponseBox(prompt, PROGRAM_NAME + " - Setup"); if (setCurrentCity == DialogResult.Yes) { preferences.ShowDialog(); // loop until a city is selected while (PreferencesForm.locationSelected) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.WARNING, "Waiting for location to be set!", $"{TAG}::LocationCheck"); }// end of while loop locationSet = PreferencesForm.locationSelected; } // end of if block } // end of else block } // end of if block else { setCurrentCity = UtilityMethod.ResponseBox("You must specify a current location in order to run the program.\n" + "Would you like to specify it now?", WeatherLionMain.PROGRAM_NAME + " Setup"); if (setCurrentCity == DialogResult.Yes) { preferences.Show(); // loop until a city is selected while (!PreferencesForm.locationSelected) { Console.WriteLine("Waiting for location to be set!"); }// end of while loop locationSet = PreferencesForm.locationSelected; }// end of if block else { UtilityMethod.ShowMessage("The program will not run without a location set.\nGoodbye.", null, title: $"{WeatherLionMain.PROGRAM_NAME}", buttons: MessageBoxButtons.OK, mbIcon: MessageBoxIcon.Information); Application.Exit(); //Exit the application. }// end of else block }// end of else block }// end of if block else { // the location was already set locationSet = true; }// end of else block return(locationSet); } // end of method LocationCheck
} // end of method SaveProgramConfiguration public static Preference GetSavedPreferences() { try { if (File.Exists(PREFERENCE_FILE)) { using (StreamReader srReader = File.OpenText(PREFERENCE_FILE)) { Type tType = m_widget_preferences.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); object oData = xsSerializer.Deserialize(srReader); m_widget_preferences = (PreferencesData)oData; } // end of using block } // end of if block else { // file does not exist so create the default one CreateDefaultAppPreferences(); } // end of else block } // end of try block catch (FileNotFoundException) { // file does not exist so create the default one CreateDefaultAppPreferences(); try { using (StreamReader srReader = File.OpenText(PREFERENCE_FILE)) { Type tType = m_widget_preferences.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); object oData = xsSerializer.Deserialize(srReader); m_widget_preferences = (PreferencesData)oData; } // end of using block } // end of try block catch (FileNotFoundException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of try block } // end of try block catch (IOException ex) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, ex.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(ex)}]"); }// end of try block try { if (File.Exists(CONFIG_FILE)) { using (StreamReader srReader = File.OpenText(CONFIG_FILE)) { Type tType = m_widget_config.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); object oData = xsSerializer.Deserialize(srReader); m_widget_config = (ConfigurationData)oData; } // end of using block } // end of if block else { // file does not exist so create the default one CreateDefaultAppConfiguration(); } // end of else block } // end of try block catch (FileNotFoundException) { // file does not exist so create the default one CreateDefaultAppConfiguration(); try { using (StreamReader srReader = File.OpenText(CONFIG_FILE)) { Type tType = m_widget_config.GetType(); XmlSerializer xsSerializer = new XmlSerializer(tType); object oData = xsSerializer.Deserialize(srReader); m_widget_config = (ConfigurationData)oData; } // end of using block } // end of try block catch (FileNotFoundException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of try block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of try block } // end of try block catch (IOException ex) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, ex.Message, $"Preference::GetSavedPreferences [line: {UtilityMethod.GetExceptionLineNumber(ex)}]"); }// end of try block return(new Preference()); } // end of method GetSavedPreferences
/// <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
}// end of method ProcessData public static bool SaveCurrentWeatherXML(string providerName, DateTime datePublished, string cityName, string countryName, string currentConditions, string currentTemperature, string currentFeelsLikeTemperture, string currentHigh, string currentLow, string currentWindSpeed, string currentWindDirection, string currentHumidity, string sunriseTime, string sunsetTime, List <FiveDayForecast> fiveDayForecast) { string weatherDataDirectory = WeatherLionMain.DATA_DIRECTORY_PATH; TimeZone localZone = TimeZone.CurrentTimeZone; string tzAbbr = UtilityMethod.ReplaceAll(localZone.DaylightName, "[a-z]", "").Replace(" ", ""); // create all necessary files if they are not present if (!Directory.Exists(weatherDataDirectory)) { Directory.CreateDirectory(weatherDataDirectory); }// end of if block try { XmlWriter writer; XmlDocument xmlDoc = new XmlDocument(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = ("\t"), CloseOutput = true, OmitXmlDeclaration = false }; // create a new file each time writer = XmlWriter.Create(previousWeatherDataXML, settings); // Root XmlElement writer.WriteStartElement("WeatherData"); // Provider Details writer.WriteStartElement("Provider"); writer.WriteElementString("Name", providerName); writer.WriteElementString("Date", string.Format("{0:ddd MMM dd HH:mm:ss} {1} {0:yyyy}", datePublished, tzAbbr)); writer.WriteEndElement(); // Location Readings writer.WriteStartElement("Location"); writer.WriteElementString("City", cityName); writer.WriteElementString("Country", countryName); writer.WriteEndElement(); // Atmospheric Readings writer.WriteStartElement("Atmosphere"); writer.WriteElementString("Humidity", currentHumidity); writer.WriteEndElement(); // Wind Readings writer.WriteStartElement("Wind"); writer.WriteElementString("WindSpeed", currentWindSpeed); writer.WriteElementString("WindDirection", currentWindDirection); writer.WriteEndElement(); // Astronomy readings writer.WriteStartElement("Astronomy"); writer.WriteElementString("Sunrise", sunriseTime); writer.WriteElementString("Sunset", sunsetTime); writer.WriteEndElement(); // Current Weather writer.WriteStartElement("Current"); writer.WriteElementString("Condition", UtilityMethod.ToProperCase(currentConditions)); writer.WriteElementString("Temperature", currentTemperature); writer.WriteElementString("FeelsLike", currentFeelsLikeTemperture); writer.WriteElementString("HighTemperature", currentHigh); writer.WriteElementString("LowTemperature", currentLow); writer.WriteEndElement(); // list of forecast data writer.WriteStartElement("DailyForecast"); // Five Day Forecast foreach (FiveDayForecast forecast in fiveDayForecast) { writer.WriteStartElement("DayForecast"); writer.WriteElementString("Date", string.Format("{0:ddd MMM dd hh:mm:ss} {1} {0:yyyy}", forecast.forecastDate, tzAbbr)); writer.WriteElementString("Condition", UtilityMethod.ToProperCase(forecast.forecastCondition)); writer.WriteElementString("LowTemperature", forecast.forecastLowTemp); writer.WriteElementString("HighTemperature", forecast.forecastHighTemp); writer.WriteEndElement(); }// end of for each loop writer.WriteEndElement(); // close the root element writer.WriteEndElement(); writer.Flush(); writer.Close(); UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, providerName + "'s weather data was stored locally!", "WeatherDataXMLService::SaveCurrentWeatherXML"); }// end of try block catch (FileNotFoundException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::SaveCurrentWeatherXML [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::SaveCurrentWeatherXML [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block return(true); }// end of method SaveCurrentWeatherXML
/// <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
}// end of method AccessFormControlsOnOtherThread /// <summary> /// Retrieves data from the Geo Names Web Service /// </summary> private void GetGeoNamesSuggestions() { List <string> matches = new List <string>(); string localCityName = null; string response = null; cityName = null; countryName = null; countryCode = null; regionCode = null; regionName = null; if (strJSON != null) { if (UtilityMethod.IsValidJson(strJSON)) { GeoNamesGeoLocation.cityGeographicalData = JsonConvert.DeserializeObject <GeoNamesGeoLocation>(strJSON); int matchCount = GeoNamesGeoLocation.cityGeographicalData.totalResultsCount; if (matchCount == 1) { GeoNamesGeoLocation.GeoNames place = GeoNamesGeoLocation.cityGeographicalData.geonames[0]; cityName = place.name; countryCode = place.countryCode; countryName = place.countryName; localCityName = place.toponymName; regionCode = place.adminCode1; regionName = place.countryCode.Equals("US") ? UtilityMethod.usStatesByCode[regionCode].ToString() : null; Latitude = place.lat; Longitude = place.lng; if (regionName != null) { response = $"{cityName}, {regionName}, {countryName}"; }// end of if block else { response = $"{cityName}, {countryName}"; } // end of else block } // end of if block else { foreach (GeoNamesGeoLocation.GeoNames place in GeoNamesGeoLocation.cityGeographicalData.geonames) { StringBuilder match = new StringBuilder(); // We only need the cities with the same name if (!place.name.Equals(PreferencesForm.searchCity.ToString(), StringComparison.OrdinalIgnoreCase)) { continue; } match.Append(place.name); // Geo Names may not return adminCodes1 for some results if (place.adminCodes1 != null) { if (place.adminCodes1.iso != null && !UtilityMethod.IsNumeric(place.adminCodes1.iso)) { string region = place.adminCodes1.iso ?? null; match.Append(", " + region); } // end of outer if block } // end of if block match.Append(", " + place.countryName); // Always verify that the adminName1 and countryName does not indicate a city already added if (!matches.ToString().Contains($"{place.adminName1}, {place.countryName}")) { // Redundancy check if (!matches.Contains(match.ToString())) { matches.Add(match.ToString()); } // end of if block } // end of if block } // end of for each loop } // end of else block } // end of if block } // end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, "The web service returned invalid JSON data", "CityDataService::GetGeoNamesSuggestions"); }// end of else block // ensure that a service did not request this data if (frmPreferences != null) { if (matches.Count > 0) { matchList = matches.ToArray(); PreferencesForm.cityNames = matchList; }// end of if block else { matches.Clear(); matchList = new string[] { "No match found..." }; PreferencesForm.cityNames = matchList; }// end of else block // since it is known that invoke will be required, the if statement is not // necessary but, it is good for practice. if (frmPreferences.InvokeRequired) { AccessWidget wid = new AccessWidget(AccessFormControlProperty); frmPreferences.Invoke(wid, new object[] { frmPreferences }); } // end of if block } // end of if block } // end of method GetGeoNamesSuggestions
}// end of method LoadFont #endregion #region Action Methods /// <summary> /// Determines the time of day to ensure correct icons are displayed. /// </summary> public void CheckAstronomy() { btnSunrise.Text = WidgetUpdateService.sunriseTime.ToString(); btnSunset.Text = WidgetUpdateService.sunsetTime.ToString(); Image wxImage = null; // update icons based on the time of day in relation to sunrise and sunset times if (WidgetUpdateService.sunriseTime != null && WidgetUpdateService.sunsetTime != null) { DateTime rightNow = DateTime.Now; DateTime rn = DateTime.Now; // date time right now (rn) DateTime?nf = null; // date time night fall (nf) DateTime?su = null; // date time sun up (su) try { string sunsetTwenty4HourTime = $"{rightNow.ToString("yyyy-MM-dd")} " + $"{UtilityMethod.Get24HourTime(WidgetUpdateService.sunsetTime.ToString())}"; string sunriseTwenty4HourTime = $"{rightNow.ToString("yyyy-MM-dd")} " + $"{UtilityMethod.Get24HourTime(WidgetUpdateService.sunriseTime.ToString())}"; nf = Convert.ToDateTime(sunsetTwenty4HourTime); su = Convert.ToDateTime(sunriseTwenty4HourTime); } // end of try block catch (FormatException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::CheckAstronomy [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); }// end of catch block StringBuilder currentConditionIcon = new StringBuilder(); string currentCondition = UtilityMethod.ValidateCondition( WidgetUpdateService.currentCondition.ToString()); if (rn == nf || rn > nf || rn < su) { if (currentCondition.ToLower().Contains("(night)")) { currentConditionIcon.Clear(); currentConditionIcon.Append( (string)UtilityMethod.weatherImages[currentCondition.ToLower()] ); }// end of if block else { // Yahoo has a habit of having sunny nights if (WidgetUpdateService.currentCondition.ToString().ToLower().Equals("sunny")) { WidgetUpdateService.currentCondition.Clear(); WidgetUpdateService.currentCondition.Append("Clear"); lblWeatherCondition.Text = UtilityMethod.ToProperCase( WidgetUpdateService.currentCondition.ToString()); }// end of if block if (UtilityMethod.weatherImages.ContainsKey($"{currentCondition.ToLower()} (night)")) { currentConditionIcon.Clear(); currentConditionIcon.Append((string)UtilityMethod.weatherImages[$"{currentCondition.ToLower()} (night)"]); }// end of if block else { currentConditionIcon.Clear(); currentConditionIcon.Append((string)UtilityMethod.weatherImages[currentCondition.ToLower()]); } // end of else block } // end of else block if (!sunsetUpdatedPerformed && !sunsetIconsInUse) { // Set image tooltip to current condition string UtilityMethod.AddControlToolTip(picCurrentConditions, WidgetUpdateService.currentCondition.ToString().ToProperCase()); sunsetIconsInUse = true; sunriseIconsInUse = false; sunsetUpdatedPerformed = true; sunriseUpdatedPerformed = false; }// end of if block else if (iconSetSwtich) { // reset the flag after switch is made iconSetSwtich = false; } // end of else if block } // end of if block else if (iconSetSwtich) { currentConditionIcon.Clear(); currentConditionIcon.Append((string)UtilityMethod.weatherImages[currentCondition.ToLower()]); // reset the flag after switch is made iconSetSwtich = false; }// end of else if block else { currentConditionIcon.Clear(); currentConditionIcon.Append((string)UtilityMethod.weatherImages[currentCondition.ToLower()]); if (!sunriseUpdatedPerformed && !sunriseIconsInUse) { // Set image tooltip to current condition string UtilityMethod.AddControlToolTip(picCurrentConditions, WidgetUpdateService.currentCondition.ToString().ToProperCase()); sunriseUpdatedPerformed = true; sunsetUpdatedPerformed = false; }// end of if block else if (iconSetSwtich) { // Set image tooltip to current condition string UtilityMethod.AddControlToolTip(picCurrentConditions, WidgetUpdateService.currentCondition.ToString().ToProperCase()); // reset the flag after switch is made iconSetSwtich = false; }// end of else if block else { sunriseIconsInUse = true; sunsetIconsInUse = false; } // end of else block } // end of else block if (currentConditionIcon.Length == 0) { currentConditionIcon.Append("na.png"); }// end of if block string imagePath = $"{WEATHER_IMAGE_PATH_PREFIX}" + $"{WeatherLionMain.storedPreferences.StoredPreferences.IconSet}" + $"/weather_{currentConditionIcon}"; wxImage = Image.FromFile(imagePath); if (imagePath.Contains("google now") || imagePath.Contains("miui") || imagePath.Contains("weezle")) { picCurrentConditions.Image = UtilityMethod.ResizeImage(wxImage, 120, 120); }// end of if block else { picCurrentConditions.Image = UtilityMethod.ResizeImage(wxImage, 140, 140); } // end of else block } // end of if block } // end of method CheckAstronomy
} // end of method AttachDatabase /// <summary> /// Build all required databases that the program will use. /// </summary> /// <returns></returns> public static int BuildRequiredDatabases() { string mainStorageFile = $"{MAIN_STORAGE_DIR}{MAIN_DATABASE_NAME}"; string cityStorageFile = $"{MAIN_STORAGE_DIR}{CITIES_DATABASE_NAME}"; string wakStorageFile = $"{MAIN_STORAGE_DIR}{WAK_DATABASE_NAME}"; StringBuilder keySuccess = new StringBuilder(); StringBuilder citySuccess = new StringBuilder(); int success = 0; // create all necessary files if they are not present if (!Directory.Exists(MAIN_STORAGE_DIR)) { Directory.CreateDirectory(MAIN_STORAGE_DIR); }// end of if block if (!File.Exists(mainStorageFile)) { try { SQLiteConnection.CreateFile(mainStorageFile); }// end of try black catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::BuildRequiredDatabases [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block if (!File.Exists(cityStorageFile)) { try { SQLiteConnection.CreateFile(cityStorageFile); citySuccess.Append("World cities database successfully created"); }// end of try black catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"WeatherLionMain::BuildRequiredDatabases [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block if (!File.Exists(wakStorageFile)) { try { SQLiteConnection.CreateFile(wakStorageFile); keySuccess.Append("Weather access database successfully created"); }// end of try black catch (IOException e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::BuildRequiredDatabases [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block if (File.Exists(mainStorageFile) && File.Exists(cityStorageFile) && File.Exists(wakStorageFile)) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.INFO, "The required storage files are present.", $"{TAG}::BuildRequiredDatabases"); // Establish connection with the databases and open it if (conn == null) { conn = ConnectionManager.GetInstance().GetConnection(); } try { conn.Open(); }// end of try block catch (Exception e) { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message, $"{TAG}::BuildRequiredDatabases [line: {UtilityMethod.GetExceptionLineNumber(e)}]"); } // end of catch block } // end of if block else { UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, "All the required storage files are not present.", $"{TAG}::BuildRequiredDatabases"); return(0); }// end of else block // attach required databases to the main database file if (AttachDatabase(wakStorageFile, "wak") == 1) { if (!UtilityMethod.CheckIfTableExists("wak", "access_keys")) { UtilityMethod.CreateWSADatabase(); }// end of if block success = 1; if (keySuccess.Length > 0) { keySuccess.Append(" and attached to main connection"); }// end of if block else { keySuccess.Append("Weather access database attached to main connection"); } // end of else block } // end of if block else { success = 0; }// end of else block if (AttachDatabase(cityStorageFile, "WorldCities") == 1) { if (!UtilityMethod.CheckIfTableExists("WorldCities", "world_cities")) { UtilityMethod.CreateWorldCitiesDatabase(); }// end of if block success = 1; if (citySuccess.Length > 0) { citySuccess.Append(" and attached to main connection"); }// end of if block else { citySuccess.Append("WorldCities database attached to main connection"); } // end of else block } // end of if block else { success = 0; }// end of else block return(success); }// end of method BuildRequiredDatabases