}// 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
예제 #2
0
        /// <summary>
        /// Retrieve the data from the weather web service.
        /// </summary>
        public void GetCityData()
        {
            string previousSearchesPath   = $@"{AppDomain.CurrentDomain.BaseDirectory}res\storage\previous_searches\";
            string previousCitySearchFile = null;

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

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

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

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

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

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

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

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

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

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

                    StringBuilder fileData = new StringBuilder();

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

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

                break;

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

            default:
                break;
            }// end of switch block

            ProcessCityData();
        }// end of method GetCityData
예제 #3
0
        }// 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
예제 #4
0
 private void Clear()
 {
     UtilityMethod.ClearChildObject(Obstacle.transform);
     UtilityMethod.ClearChildObject(Terrains.transform);
     UtilityMethod.ClearChildObject(AnimatedObject.transform);
 }
예제 #5
0
 protected void Application_Start()
 {
     GlobalConfiguration.Configure(WebApiConfig.Register);
     //注册应用
     UtilityMethod.RegiestedService("test2", "http://localhost:2271/api/Service", "http://localhost", 16729);
 }
예제 #6
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtKeyName == null || txtKeyName.Text.Length == 0 ||
                txtKeyName.Text.Equals(""))
            {
                UtilityMethod.ShowMessage("Please enter a valid key name as given by the provider!", this,
                                          WeatherLionMain.PROGRAM_NAME + " - No Key Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtKeyName.Focus();
            }// end of if block
            else if (pwdKeyValue == null || pwdKeyValue.Text.Length == 0 ||
                     pwdKeyValue.Text.Equals(""))
            {
                UtilityMethod.ShowMessage("Please enter a valid key value as given by the provider!", this,
                                          WeatherLionMain.PROGRAM_NAME + " - No Key Value", MessageBoxButtons.OK, MessageBoxIcon.Error);
                pwdKeyValue.Focus();
            }// end of else if block
            else
            {
                string[] encryptedKey     = LionSecurityManager.Encrypt(pwdKeyValue.Text, true).Split(':');
                string   selectedProvider = cboAccessProvider.SelectedItem.ToString();

                switch (selectedProvider)
                {
                case "Here Maps Weather":
                    if (!LionSecurityManager.hereMapsRequiredKeys.Contains(txtKeyName.Text.ToLower()))
                    {
                        UtilityMethod.ShowMessage($"The {selectedProvider} does not require a key \"{ txtKeyName.Text}\"!",
                                                  this, $"{WeatherLionMain.PROGRAM_NAME} - Invalid Key Type", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtKeyName.Focus();

                        return;
                    }    // end of if block

                    break;

                case "Yahoo! Weather":
                    if (!LionSecurityManager.yahooRequiredKeys.Contains(txtKeyName.Text.ToLower()))
                    {
                        UtilityMethod.ShowMessage($"The {selectedProvider} does not require a key \"{ txtKeyName.Text}\"!",
                                                  this, $"{WeatherLionMain.PROGRAM_NAME} - Invalid Key Type", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtKeyName.Focus();

                        return;
                    }    // end of if block

                    break;

                default:
                    break;
                }// end of switch block

                if (UtilityMethod.AddSiteKeyToDatabase(cboAccessProvider.SelectedItem.ToString(),
                                                       txtKeyName.Text, encryptedKey[0], encryptedKey[1]) == 1)
                {
                    if (txtKeyName.Enabled)
                    {
                        txtKeyName.Text = ("");
                    }
                    pwdKeyValue.Text = "";

                    UtilityMethod.ShowMessage("The key was successfully added to the database.", this,
                                              WeatherLionMain.PROGRAM_NAME + " - Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtKeyName.Focus();
                }// end of if block
                else
                {
                    UtilityMethod.ShowMessage("The key could not be added to the database!"
                                              + "\nPlease recheck the key and try again.", this,
                                              WeatherLionMain.PROGRAM_NAME + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtKeyName.Focus();
                } // end of else block
            }     // end of else block
        }         // end of method btnAdd_Click
예제 #7
0
        public void FindDoorIntersection(List <BSPMapComponent> corridors, int corridorSize)
        {
            foreach (BSPCorridor corridor in corridors)
            {
                if (corridor.spaceRect.xMin > this.spaceRect.xMin && corridor.spaceRect.xMax < this.spaceRect.xMax &&
                    corridor.spaceRect.yMin > this.spaceRect.yMin && corridor.spaceRect.yMax < this.spaceRect.yMax
                    )
                {
                    continue;
                }

                if (!UtilityMethod.DoBoxesIntersect(this.spaceRect, corridor.spaceRect))
                {
                    continue;
                }


                //Horizontal
                if (corridor.spaceRect.width != corridorSize)
                {
                    int y = (int)corridor.spaceRect.y;

                    if (corridor.spaceRect.xMin < this.spaceRect.xMin)
                    {
                        doorPosition.Add(new Vector2Int((int)this.spaceRect.xMax, y));
                        doorPosition.Add(new Vector2Int((int)this.spaceRect.xMin - 1, y));

                        continue;
                    }

                    //Door at xMax side (right)
                    if (corridor.spaceRect.xMin < this.spaceRect.xMax && corridor.spaceRect.xMin > this.spaceRect.xMin)
                    {
                        doorPosition.Add(new Vector2Int((int)this.spaceRect.xMax, y));
                    }
                    else
                    {
                        //Door at xMin side (left)
                        doorPosition.Add(new Vector2Int((int)this.spaceRect.xMin - 1, y));
                    }
                }
                else
                {
                    //Door at yMax side (up)
                    int x = (int)corridor.spaceRect.x;

                    if (corridor.spaceRect.yMin < this.spaceRect.yMin)
                    {
                        doorPosition.Add(new Vector2Int(x, (int)this.spaceRect.yMax));
                        doorPosition.Add(new Vector2Int(x, (int)this.spaceRect.yMin - 1));

                        continue;
                    }

                    if (corridor.spaceRect.yMin < this.spaceRect.yMax && corridor.spaceRect.yMin > this.spaceRect.yMin)
                    {
                        doorPosition.Add(new Vector2Int(x, (int)this.spaceRect.yMax));
                    }
                    else
                    {
                        //Door at yMin side (bottom)
                        doorPosition.Add(new Vector2Int(x, (int)this.spaceRect.yMin - 1));
                    }
                }
            }
        }
        }                     // 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
예제 #9
0
        /// <summary>
        /// Accepts a CityData object and exports it to an XML file.
        /// </summary>
        /// <param name="cityData">The CityData object to be written to an XML file.</param>
        /// <returns>A <see cref="bool"/> value representing success or failure</returns>
        public static bool ExportToXML(CityData cityData)
        {
            if (cityData != null)
            {
                try
                {
                    bool              append;
                    XmlWriter         writer;
                    XmlDocument       xmlDoc   = new XmlDocument();
                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent             = true,
                        IndentChars        = ("\t"),
                        CloseOutput        = true,
                        OmitXmlDeclaration = false
                    };

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

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

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

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

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

                    return(true);
                }// end of try block
                catch (Exception e)
                {
                    UtilityMethod.LogMessage(UtilityMethod.LogLevel.SEVERE, e.Message,
                                             $"{TAG}::ExportToXML [line: {UtilityMethod.GetExceptionLineNumber(e)}]");
                    return(false);
                } // end of catch block
            }     // end of if block
            else
            {
                return(false);
            } // end of else block
        }     // end of method ExportToXML
        }     // 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
        }     // 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
        /// <summary>
        /// Load a required assets and prepare for program execution
        /// </summary>
        public static void Launch()
        {
            #region WeatherLion launch sequence

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

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

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

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

            wxOnly.Sort();  // sort the list

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

            authorizedProviders = wxOnly.ToArray();

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

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

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

            connectedToInternet = UtilityMethod.HasInternetConnection();

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

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

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

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

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

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

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

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

            Init();

            #endregion
        }// end of method Launch
예제 #13
0
        public override void notifyTwoWayReplyReceived(IPAddress fromIP, byte[] buffer, int offset, int size, AsyncCallback originalRequestCallBack, Object originalAppState)
        {
            Console.WriteLine("ChordProxyNode::notifyTwoWayReplyReceived ENTER");
            String[] split = splitMsgBuffer(buffer, offset, size);
            if (String.Compare(split[0], "FIND_SUCCESSOR_REPLY") == 0)
            {
                Console.WriteLine("ChordProxyNode::notifyTwoWayReplyReceived FIND_SUCCESSOR_RECEIVED");
                String strSuccessorIP = split[1];
                Console.Write("ChordProxyNode::notifyTwoWayReplyReceived SuccessorIP = ");
                Console.WriteLine(strSuccessorIP);

                IPAddress successorIP = UtilityMethod.convertStrToIP(strSuccessorIP);

                ChordCommon.IChordNode_Object iNode_Object = new ChordCommon.IChordNode_Object();
                iNode_Object.node = (IChordNode)(proxyController.getProxyNode(successorIP));
                iNode_Object.obj  = originalAppState;

                Tashjik.Common.ObjectAsyncResult objectAsyncResult = new Tashjik.Common.ObjectAsyncResult(iNode_Object, false, false);
                if (originalRequestCallBack != null)
                {
                    originalRequestCallBack(objectAsyncResult);
                }
            }
            else if (String.Compare(split[0], "GET_PREDECESSOR_REPLY") == 0)
            {
                Console.WriteLine("ChordProxyNode::notifyTwoWayReplyReceived GET_PREDECESSOR_RECEIVED");
                String strPredecessorIP = split[1];
                ChordCommon.IChordNode_Object iNode_Object = new ChordCommon.IChordNode_Object();

                if (String.Compare(strPredecessorIP, "UNKNOWN_PREDECESSOR") == 0)
                {
                    Console.Write("ChordProxyNode::notifyTwoWayReplyReceived PREDECESSOR_UNKNOWN");
                    iNode_Object.node = null;
                }
                else
                {
                    Console.Write("ChordProxyNode::notifyTwoWayReplyReceived PredecessorIP = ");
                    Console.WriteLine(strPredecessorIP);

                    IPAddress predecessorIP = UtilityMethod.convertStrToIP(strPredecessorIP);

                    iNode_Object.node = (IChordNode)(proxyController.getProxyNode(predecessorIP));
                }
                iNode_Object.obj = originalAppState;

                Tashjik.Common.ObjectAsyncResult objectAsyncResult = new Tashjik.Common.ObjectAsyncResult(iNode_Object, false, false);
                if (originalRequestCallBack != null)
                {
                    originalRequestCallBack(objectAsyncResult);
                }
            }
            else if (String.Compare(split[0], "GET_FINGERTABLE_REPLY") == 0)
            {
                Console.WriteLine("ChordProxyNode::notifyTwoWayReplyReceived GET_FINGERTABLE_RECEIVED");

                String       strPredecessorIP = split[1];
                IChordNode[] fingerTable      = new IChordNode[split.Length - 1];
                for (int i = 1; i < 161; i++)
                {
                    if (split[i] == "NULL")
                    {
                        fingerTable[i - 1] = null;
                    }
                    else
                    {
                        fingerTable[i - 1] = (IChordNode)(proxyController.getProxyNode(UtilityMethod.convertStrToIP(split[i].ToString())));
                    }
                }
                ChordCommon.IChordNodeArray_Object iNodeArray_Object = new ChordCommon.IChordNodeArray_Object();
                iNodeArray_Object.nodeArray = fingerTable;
                iNodeArray_Object.obj       = originalAppState;

                Tashjik.Common.ObjectAsyncResult objectAsyncResult = new Tashjik.Common.ObjectAsyncResult(iNodeArray_Object, false, false);
                if (originalRequestCallBack != null)
                {
                    originalRequestCallBack(objectAsyncResult);
                }
            }
        }
예제 #14
0
        private void LinkCorridorBetween(BSPRoom left, BSPRoom right)
        {
            tempCorridors.Clear();

            Rect lroom = left.spaceRect;
            Rect rroom = right.spaceRect;

            // Debug.Log("Creating corridor(s) between " + left.debugId + "(" + lroom + ") and " + right.debugId + " (" + rroom + ")");

            // attach the corridor to a random point in each room
            Vector2 lpoint = new Vector2(UtilityMethod.RandRangeToInt(lroom.x + 1, lroom.xMax - 1),
                                         UtilityMethod.RandRangeToInt(lroom.y + 1, lroom.yMax - 1));
            Vector2 rpoint = new Vector2(UtilityMethod.RandRangeToInt(rroom.x + 1, rroom.xMax - 1),
                                         UtilityMethod.RandRangeToInt(rroom.y + 1, rroom.yMax - 1));



            //Debug.Log("lPoint " + lpoint +", rPoint " + rpoint);
            // always be sure that left point is on the left to simplify the code
            if (lpoint.x > rpoint.x)
            {
                Vector2 temp = lpoint;
                lpoint = rpoint;
                rpoint = temp;
            }

            int w            = (int)(lpoint.x - rpoint.x);
            int h            = (int)(lpoint.y - rpoint.y);
            int corridorSize = 1;

            // if the points are not aligned horizontally
            if (w != 0)
            {
                // choose at random to go horizontal then vertical or the opposite
                if (Random.Range(0, 1) > 2)
                {
                    // add a corridor to the right
                    tempCorridors.Add(new BSPCorridor(new Rect(lpoint.x, lpoint.y, Mathf.Abs(w) + 1, corridorSize)));

                    // if left point is below right point go up
                    // otherwise go down
                    if (h < 0)
                    {
                        tempCorridors.Add(new BSPCorridor(new Rect(rpoint.x, lpoint.y, corridorSize, Mathf.Abs(h))));
                    }
                    else
                    {
                        tempCorridors.Add(new BSPCorridor(new Rect(rpoint.x, lpoint.y, corridorSize, -Mathf.Abs(h))));
                    }
                }
                else
                {
                    // go up or down
                    if (h < 0)
                    {
                        tempCorridors.Add(new BSPCorridor(new Rect(lpoint.x, lpoint.y, corridorSize, Mathf.Abs(h))));
                    }
                    else
                    {
                        tempCorridors.Add(new BSPCorridor(new Rect(lpoint.x, rpoint.y, corridorSize, Mathf.Abs(h))));
                    }

                    // then go right
                    tempCorridors.Add(new BSPCorridor(new Rect(lpoint.x, rpoint.y, Mathf.Abs(w) + 1, corridorSize)));
                }
            }
            else
            {
                //假設 房間的x軸對齊的話
                //根據y軸的差距 決定往下 或 往上走
                if (h < 0)
                {
                    tempCorridors.Add(new BSPCorridor(new Rect((int)lpoint.x, (int)lpoint.y, corridorSize, Mathf.Abs(h))));
                }
                else
                {
                    tempCorridors.Add(new BSPCorridor(new Rect((int)rpoint.x, (int)rpoint.y, corridorSize, Mathf.Abs(h))));
                }
            }

            corridors.AddRange(tempCorridors);

            //left.FindDoorIntersection(tempCorridors, corridorSize);
            //right.FindDoorIntersection(tempCorridors, corridorSize);

            foreach (BSPCorridor corridor in corridors)
            {
                //Debug.Log ("corridor: " + corridor.spaceRect);
            }
        }
        public void Calculate()
        {
            if (soundQueue.Count <= 0 && soundSegmentQueue.Count <= 0)
            {
                return;
            }
            if (segmentId > 10000)
            {
                segmentId = 0;
            }                                           //reset segment id

            //segmentId = 0;
            diffractedSegments.Clear();

            mapKeyPoints = new List <MapPointData>();

            soundSegmentQueue_nextFrame = new Queue <SoundSegment>();

            int numOfSoundForOneRound = soundQueue.Count;

            for (int q = 0; q < numOfSoundForOneRound; q++)
            {
                Sound sound = soundQueue.Dequeue();

                if (!sound.IsOver())
                {
                    soundQueue.Enqueue(sound);

                    float volume = sound.volume; // rayFrequency;

                    float steps          = sound.volume / (system.fadingSpeed + float.Epsilon);
                    float spreadDistance = steps * system.stepDistance;

                    //mapKeyPoints.Add(new MapPointData(sound.sid, sound.producedPos, sound.volume, fadingSpeed, stepDistance));

                    Transform target  = sound.producer.transform;
                    Vector3   origin  = target.position;
                    Vector3   forward = target.forward;

                    //rotate clockwise and counter-clockwise to find the bondary vectors
                    float   halfRange = sound.range / 2;
                    Vector3 bound_CCW = UtilityMethod.RotateAroundY(halfRange, forward);
                    Vector3 bound_CW  = UtilityMethod.RotateAroundY(-halfRange, forward);
                    //Debug.DrawRay(agent.transform.position, bound_CCW * 10, Color.cyan);
                    //Debug.DrawRay(agent.transform.position, bound_CW * 10, Color.green);

                    float   delta  = 360f / rayFrequency;
                    int     rayNum = (int)(sound.range / delta);
                    Vector3 dir    = bound_CW;
                    for (int i = 0; i <= rayNum; i++)   // <= because we enqueue the segement first then increment the angle, so we need extra 1 time for the last direction
                    {
                        //raycast
                        soundSegmentQueue.Enqueue(new SoundSegment(segmentId, origin, dir, sound.volume, sound.type, 0));
                        dir = UtilityMethod.RotateAroundY(delta, dir);
                    }
                }
            }
            while (soundSegmentQueue.Count > 0)
            {
                SoundSegment segment = soundSegmentQueue.Dequeue();

                RayCastFromPoint(segment);
            }
            soundSegmentQueue = soundSegmentQueue_nextFrame;
        }
예제 #16
0
        public override void Update(List <PointViewerUtility.ActionBase> acts, PlayerBase[] plist, FieldBase f)
        {
            if (acts.Count == 1 && f is field)
            {
                Player target = (Player)UtilityMethod.Target(plist, acts[0].Player);
                Action act    = (Action)acts[0];

                switch (act.State)
                {
                case (Action.O1):
                    target.O1++;
                    if (target.Standup2)
                    {
                        target.Standup2   = false;
                        target.BonusAdded = true;
                    }
                    if (!target.BonusAdded && !target.Standup1)
                    {
                        target.Standup1 = true;
                    }

                    target.Point = target.O1 + target.O2;
                    if (target.BonusAdded)
                    {
                        target.Point++;
                    }

                    break;

                case (Action.O2):
                    target.O2++;
                    if (target.Standup1)
                    {
                        target.Standup1   = false;
                        target.BonusAdded = true;
                    }
                    if (!target.BonusAdded && !target.Standup2)
                    {
                        target.Standup2 = true;
                    }

                    target.Point = target.O1 + target.O2;
                    if (target.BonusAdded)
                    {
                        target.Point++;
                    }

                    break;

                case (Action.X1):
                    target.X1++;
                    break;

                case (Action.X2):
                    target.X2++;
                    break;

                default:
                    break;
                }
            }
            else if (acts.Count > 1)
            {
                foreach (Action act in acts)
                {
                    Player p = (Player)PointViewerUtility.UtilityMethod.Target(plist, act.Player);
                    switch (act.State)
                    {
                    case Action.SET4o2x:
                        p.WinPoint = winPoint - 1;
                        p.LoseX    = losePoint;
                        break;

                    case Action.SET4o3x:
                        p.WinPoint = winPoint - 1;
                        p.LoseX    = losePoint + 1;
                        break;

                    case Action.SET5o2x:
                        p.WinPoint = winPoint;
                        p.LoseX    = losePoint;
                        break;

                    case Action.SET5o3x:
                        p.WinPoint = winPoint;
                        p.LoseX    = losePoint + 1;
                        break;

                    default:
                        p.WinPoint = winPoint;
                        p.LoseX    = losePoint;
                        break;
                    }
                }
            }
        }
예제 #17
0
        }         // end of method btnDeleteKey_Click

        private void btnFinish_Click(object sender, EventArgs e)
        {
            LionSecurityManager.LoadAccessProviders();

            if (LionSecurityManager.keysMissing != null)
            {
                if (LionSecurityManager.keysMissing.Count > 0)
                {
                    DialogResult answer = LionSecurityManager.CheckForMissingKeys();
                    LionSecurityManager.accessGranted = false;

                    if (answer == DialogResult.Yes)
                    {
                        if (!Visible)
                        {
                            Visible = true;
                        }// end of if block
                        else
                        {
                            txtKeyName.Focus();
                        } // end of else block
                    }     // end of if block
                    else
                    {
                        string wp = null;
                        //string[] keys = null;

                        if (LionSecurityManager.keysMissing.Count > 1)
                        {
                            List <string> missingHereKeys  = new List <string>();
                            List <string> missingYahooKeys = new List <string>();

                            foreach (string keyName in LionSecurityManager.keysMissing)
                            {
                                if (LionSecurityManager.hereMapsRequiredKeys.Contains(keyName))
                                {
                                    missingHereKeys.Add(keyName);
                                }// end of if block
                                else if (LionSecurityManager.hereMapsRequiredKeys.Contains(keyName))
                                {
                                    missingYahooKeys.Add(keyName);
                                } // end of else if block
                            }     // end of for each loop

                            if (missingHereKeys.Count > 0)
                            {
                                string hKeys = string.Join(", ", missingHereKeys);
                                string fs    = null;

                                if (UtilityMethod.NumberOfCharacterOccurences(',', hKeys) > 1)
                                {
                                    fs = UtilityMethod.ReplaceLast(",", ", and", hKeys);
                                }// end of if block
                                else if (UtilityMethod.NumberOfCharacterOccurences(',', hKeys) == 1)
                                {
                                    fs = hKeys.Replace(",", " and");
                                }// end of else block
                                else
                                {
                                    fs = hKeys;
                                }// end of else block

                                wp = WeatherLionMain.HERE_MAPS;
                                string kc = missingHereKeys.Count > 1 ? "keys" : "key";

                                UtilityMethod.ShowMessage($"{wp} cannot be used as a weather source without\n"
                                                          + $"first adding the missing {kc} {fs}.", this, $"{WeatherLionMain.PROGRAM_NAME} - Missing Key", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }// end of if block

                            if (missingYahooKeys.Count > 0)
                            {
                                string hKeys = string.Join(", ", missingHereKeys);
                                string fs    = null;

                                if (UtilityMethod.NumberOfCharacterOccurences(',', hKeys) > 1)
                                {
                                    fs = UtilityMethod.ReplaceLast(",", ", and", hKeys);
                                }// end of if block
                                else if (UtilityMethod.NumberOfCharacterOccurences(',', hKeys) == 1)
                                {
                                    fs = hKeys.Replace(",", " and");
                                }// end of else block
                                else
                                {
                                    fs = hKeys;
                                }// end of else block

                                wp = WeatherLionMain.YAHOO_WEATHER;
                                string kc = missingHereKeys.Count > 1 ? "keys" : "key";

                                UtilityMethod.ShowMessage($"{wp} cannot be used as a weather source without\n"
                                                          + $"first adding the missing {kc} {fs}.", this,
                                                          title: $"{WeatherLionMain.PROGRAM_NAME} - Missing Key", buttons: MessageBoxButtons.OK,
                                                          mbIcon: MessageBoxIcon.Error);
                            } // end of if block
                        }     // end of if block
                    }         // end of else block
                }             // end of if block
            }                 // end of if block

            if (LionSecurityManager.webAccessGranted.Count >= 1 &&
                !LionSecurityManager.webAccessGranted.Contains("GeoNames"))
            {
                UtilityMethod.ShowMessage("This program requires a geonames username"
                                          + " which was not stored in the database.\nIT IS FREE!", this,
                                          title: $"{WeatherLionMain.PROGRAM_NAME} - Missing Key", buttons: MessageBoxButtons.OK,
                                          mbIcon: MessageBoxIcon.Error);
            }// end of else if block
            else if (LionSecurityManager.webAccessGranted.Count == 2 &&
                     LionSecurityManager.webAccessGranted.Contains("GeoNames") &&
                     LionSecurityManager.webAccessGranted.Contains("Yr.no (Norwegian Metrological Institute)"))
            {
                UtilityMethod.ShowMessage("The program will only display weather data from"
                                          + " Yr.no (Norwegian Metrological Institute).\nObtain access keys for"
                                          + " the others if you wish to use them.", this,
                                          title: $"{WeatherLionMain.PROGRAM_NAME} - Single Weather Providery", buttons: MessageBoxButtons.OK,
                                          mbIcon: MessageBoxIcon.Information);
                LionSecurityManager.accessGranted = true;
                Close();
            }// end of else if block
            else
            {
                LionSecurityManager.accessGranted = true;
                Close();
            } // end of else block
        }     // end of method btnFinish_Click
        }// 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
예제 #19
0
        }     // 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
예제 #20
0
    public void SaveToDatabase()
    {
        string rawData = JsonHelper.ToJson <CharacterStats>(_chararcterList.ToArray());

        UtilityMethod.PrefSave(ParameterFlag.SaveSlotKey.Character, rawData);
    }