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()
}// 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
/// <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 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
/// <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 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 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 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 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
/// <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 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
}// 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
}// 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