Exemplo n.º 1
0
        /// <summary>
        /// Controller action developed using the the Bridge design pattern to get its data
        /// </summary>
        /// <remarks>
        /// This controller is programmed against the interface IWeatherClient, so it avoids the direct
        /// dependency on a third party interface.
        /// </remarks>
        /// <param name="zipCode">A String of the zip code to get the weather for</param>
        /// <returns></returns>
        public ActionResult BridgePattern(String zipCode = null)
        {
            if (String.IsNullOrWhiteSpace(zipCode))
            {
                zipCode = "53211";
            }

            IWeatherClient weatherClient = new WeatherUndergroundDriver();

            #region NOAA Weather Client
            //IWeatherClient weatherClient = new NoaaWeatherAdapter.NoaaWeatherDriver(this.zipCodeService);
            #endregion

            #region Fake Weather Service
            // IWeatherClient weatherClient = new FakeWeatherServiceDriver();
            #endregion

            #region Caching Decorator
            //IWeatherClient weatherClient = new WeatherClientCacheDecorator(new WeatherUndergroundDriver());
            #endregion

            CurrentConditions currentConditions = weatherClient.GetCurrentConditions(zipCode);

            BridgePatternModel model = new BridgePatternModel()
            {
                WeatherData = currentConditions
            };

            return(View(model));
        }
        // ----------------------------------------------------------------
        // ----------------------------------------------------------------
        public WeatherViewModel()
        {
            SearchCommand = new SearchCommand(this);
            Cities        = new ObservableCollection <City>();

            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                m_SelectedCity = new City
                {
                    LocalizedName = "Milwaukee"
                };


                m_CurrentConditions = new CurrentConditions
                {
                    WeatherText = "Partly cloudy",
                    Temperature = new Temperature
                    {
                        Imperial = new Units
                        {
                            Value = 51
                        }
                    }
                };
            }
        }
Exemplo n.º 3
0
        public WeatherVM()
        {
            //Display data during design time, just to show data is binding to the view.
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City
                {
                    LocalizedName = "New York"
                };

                CurrentConditions = new CurrentConditions
                {
                    WeatherText = "Partly cloudy",
                    Temperature = new Temperature
                    {
                        Imperial = new Units
                        {
                            Value = "65"
                        }
                    }
                };
            }

            //Want to initialize the search command, even outside of design time.
            SearchCommand = new SearchCommand(this);

            Cities = new ObservableCollection <City>();
        }
Exemplo n.º 4
0
        public WeatherViewModel()
        {
            // if it is in designer mode, and we are not running the application
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City()
                {
                    LocalizedName = "Ottawa"
                };
                CurrentConditions = new CurrentConditions()
                {
                    WeatherText = "Windy",
                    Temperature = new Temperature()
                    {
                        Metric = new Units
                        {
                            Value = "21"
                        }
                    }
                };
            }

            SearchCommand = new SearchCommand(this);
            Cities        = new ObservableCollection <City>();
        }
        public WeatherViewModel()
        {
            SearchCommand = new SearchCommand(this);
            Cities        = new ObservableCollection <City>();

            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _accuWeatherService = App.IocContainer.Resolve <IAccuWeatherService>();
                return;
            }

            City = new City {
                Name = "Evansville"
            };
            CurrentConditions = new CurrentConditions
            {
                WeatherText = "Bipolar",
                Temperature = new Temperature
                {
                    Metric = new TemperatureUnit {
                        Value = "21"
                    },
                    Imperial = new TemperatureUnit {
                        Value = "21"
                    }
                }
            };
        }
Exemplo n.º 6
0
        public WeatherVM()
        {
            //Init data on not running mode
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City
                {
                    LocalizedName = "Chicago"
                };

                CurrentConditions = new CurrentConditions
                {
                    WeatherText = "Partly Cloud",
                    Temperature = new Temperature
                    {
                        Metric = new Units
                        {
                            Value = 21
                        }
                    }
                };
            }

            SearchCommand = new SearchCommand(this);
        }
Exemplo n.º 7
0
        public WeatherVM()
        {
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City
                {
                    LocalizedName = "Bhubaneswar"
                };

                CurrentConditions = new CurrentConditions
                {
                    WeatherText = "Sunny",
                    Temperature = new Temperature
                    {
                        Metric = new Units
                        {
                            Value = "23"
                        }
                    }
                };
            }

            SearchCommand = new SearchCommand(this);
            Cities        = new ObservableCollection <City>();
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            // create the subject and observers
            WeatherData weatherData = new WeatherData();

            CurrentConditions conditions = new CurrentConditions(weatherData);
            Statistics statistics = new Statistics(weatherData);
            Forecast forecast = new Forecast(weatherData);

            // create the readings
            WeatherMeasurements readings = new WeatherMeasurements();
            readings.humidity = 40.5F;
            readings.pressure = 20F;
            readings.temperature = 72F;

            // update the readings - everyone should print
            weatherData.UpdateReadings(readings);

            // update
            readings.pressure = 10F;
            weatherData.UpdateReadings(readings);

            // update
            readings.humidity = 100;
            readings.temperature = 212.75F;
            readings.pressure = 950;
            weatherData.UpdateReadings(readings);

            Console.ReadLine();
        }
Exemplo n.º 9
0
        public WeatherVM()
        {
            // if the project is not running, eg in design mode, run this
            // excellent for testing fixed values
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City
                {
                    LocalizedName = "Plymouth"
                };

                CurrentConditions = new CurrentConditions
                {
                    WeatherText = "Cloudy",
                    Temperature = new Temperature
                    {
                        Metric = new Units
                        {
                            Value = "10"
                        }
                    }
                };
            }

            // passess an instance of the current class into the constructor
            // used for binding
            // this variable is bound to the search button. pressing it triggers an instance of this class (object)
            // to be passed into SearchCommand(this) which then has access to the entire objectt,
            // which then can be passed to the execute method, which runs MakeQuery() which is back in this class
            // xaml Button > VM Constuctor > Command Constructor > Command Execute Method > VM MakeQuey Method > AccuWeatherHelpers.GetCities using the Query property thats holding the city name
            SearchCommand = new SearchCommand(this);    //// initialize the Commands

            Cities = new ObservableCollection <City>(); // must initialise the observablCollection in the constructor
        }
Exemplo n.º 10
0
        public WeatherVM()
        {
            if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                SelectedCity = new City()
                {
                    LocalizedName = "New York"
                };

                CurrentConditions = new CurrentConditions()
                {
                    WeatherText = "Partly cloudly",
                    Temperature = new Temperature()
                    {
                        Metric = new Units()
                        {
                            Value = "21"
                        }
                    }
                };
            }

            SearchCommand = new SearchCommand(this);
            Cities        = new ObservableCollection <City>();
        }
Exemplo n.º 11
0
        public static async Task <CurrentConditions> GetCurrentConditions(string cityKey)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            string url = BASE_URL + string.Format(CURRENT_CONDITIONS_ENDPOINT, cityKey, API_KEY);

            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(url);

                string json = await response.Content.ReadAsStringAsync();

                if (json.Contains("ServiceUnavailable"))
                {
                    url      = url.Replace(API_KEY, API_KEY_2);
                    response = await client.GetAsync(url);

                    json = await response.Content.ReadAsStringAsync();

                    if (json.Contains("ServiceUnavailable"))
                    {
                        url      = url.Replace(API_KEY_2, API_KEY_3);
                        response = await client.GetAsync(url);

                        json = await response.Content.ReadAsStringAsync();
                    }
                }

                currentConditions = (JsonConvert.DeserializeObject <List <CurrentConditions> >(json).FirstOrDefault());
            }

            return(currentConditions);
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            WeatherData       weatherData    = new WeatherData();
            CurrentConditions currentDisplay = new CurrentConditions(weatherData);

            weatherData.SetMeasurementsChanged(80, 65, 30.4f);
            weatherData.SetMeasurementsChanged(82, 70, 29.2f);
            weatherData.SetMeasurementsChanged(78.5f, 90, 29.2f);
        }
        public static void Run()
        {
            var data = new WeatherData();

            var conditions = new CurrentConditions(data);
            var statistics = new Statistics(data);
            var forecast   = new Forecast(data);

            data.SetReading(26.6f, 54, 1012.1f);
            data.SetReading(16.6f, 64, 912.2f);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            WeatherData data = new WeatherData();

            CurrentConditions current = new CurrentConditions(data);
            Forecast forecast = new Forecast(data);
            Statitstics statistics = new Statitstics(data);

            data.setMeasurements(75, 54, 2);
            data.setMeasurements(80, 48, 3);
            data.setMeasurements(65, 40, 2);
        }
        public async Task <CurrentWeatherReadDto> GetCurrentWeather(string cityKey)
        {
            var currentWeather = _dbContext.CurrentWeathers.FirstOrDefault(x => x.Key == cityKey);

            if (currentWeather != null)
            {
                var favoriteLocation = _dbContext.FavoriteLocations.FirstOrDefault(x => x.Key == cityKey);
                return(new CurrentWeatherReadDto()
                {
                    Id = currentWeather.Id,
                    Key = currentWeather.Key,
                    Temprature = currentWeather.Temprature,
                    WeatherText = currentWeather.WeatherText,
                    IsFavorite = favoriteLocation != null,
                    FavoriteId = favoriteLocation?.Id ?? 0
                });
            }

            var requestUri = "http://dataservice.accuweather.com/currentconditions/v1/" + cityKey + "?apikey=" + _apiKey;
            var request    = new HttpRequestMessage(HttpMethod.Get, requestUri);
            var client     = _clientFactory.CreateClient();

            try
            {
                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    CurrentConditions conditions = (await response.Content.ReadAsAsync <List <CurrentConditions> >()).FirstOrDefault();
                    var weather = new CurrentWeather()
                    {
                        WeatherText = conditions.WeatherText,
                        Temprature  = conditions.Temperature.Metric.Value,
                        Key         = cityKey
                    };
                    _dbContext.CurrentWeathers.Add(weather);
                    _dbContext.SaveChanges();
                    return(new CurrentWeatherReadDto()
                    {
                        Id = weather.Id,
                        Key = weather.Key,
                        Temprature = weather.Temprature,
                        WeatherText = weather.WeatherText
                    });;
                }
            }
            catch (Exception e)
            {
            };
            return(null);
        }
    void DeleteConditionWindow(int id, int idOfType)
    {
        EntityDeleted(id);
        EditorInfo.ConditionsIndexes.RemoveAt(idOfType);
        EditorInfo.Conditions--;

        CurrentConditions.RemoveAt(idOfType);
        ClearAllConnectionsPending();

        DecrementIndexes(id);
        UpdateTargetAfterDeletion(id, idOfType, NodeType.Condition);

        WriteDebug("Deleting condition " + idOfType + " and it's associations.");
    }
Exemplo n.º 17
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            CurrentConditions conditions = await OpenWeather.GetWeatherAsync(activity.Text);

            // return our reply to the user
            await context.PostAsync(string.Format("Current conditions in {1}: {0}. The temperature is {2}\u00B0 F.",
                                                  conditions.Weather[0].Main,
                                                  conditions.CityName,
                                                  conditions.Main.Temperature));

            context.Wait(MessageReceivedAsync);
        }
Exemplo n.º 18
0
        public static async Task <CurrentConditions> GetCurrentConditions(string cityKey)
        {
            var currentConditions = new CurrentConditions();
            var url = $"{BASE_URL}{string.Format(CURRENT_CONDITIONS_ENDPOINT, cityKey, API_KEY)}";

            using var client = new HttpClient();
            var response = await client.GetAsync(url);

            var json = await response.Content.ReadAsStringAsync();

            currentConditions = (JsonConvert.DeserializeObject <List <CurrentConditions> >(json)).FirstOrDefault();

            return(currentConditions);
        }
        public static async Task<CurrentConditions> GetCurrentConditions(string cityKey)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            string restURL = BASE_URI + String.Format(CURRENT_CONDITIONS_ENDPOINT, cityKey, API_KEY);

            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(restURL);
                var json = await response.Content.ReadAsStringAsync();
                currentConditions = (JsonConvert.DeserializeObject<List<CurrentConditions>>(json)).FirstOrDefault();
            }

            return currentConditions;
        }
Exemplo n.º 20
0
        public static async Task <CurrentConditions> GetCurrentConditions(string locationKey)
        {
            CurrentConditions currentConditions = new CurrentConditions();
            string            url = BASE_URL + String.Format(CURRENT_CONDITIONS_ENDPOINT, locationKey, API_KEY);

            using (HttpClient client = new HttpClient())
            {
                var responce = await client.GetAsync(url);

                string json = await responce.Content.ReadAsStringAsync();

                currentConditions = JsonConvert.DeserializeObject <List <CurrentConditions> >(json)[0];
            }
            return(currentConditions);
        }
    public void CreateConditionNode()
    {
        ConditionNode newCondition = new ConditionNode();

        newCondition.ConditionID = EditorInfo.Conditions;
        CurrentConditions.Add(newCondition);

        EditorInfo.Windows.Add(new Rect(10 + scrollPosition.x, 10 + scrollPosition.y, 200, 5));
        EditorInfo.WindowTypes.Add(NodeType.Condition);
        EditorInfo.NodeTypesIDs.Add(EditorInfo.Conditions++);
        EditorInfo.ConditionsIndexes.Add(EditorInfo.Windows.Count - 1);

        newCondition.SetAttributeCheckCondition(CharacterAttribute.Agility, 10, InequalityTypes.Equal);

        SaveChanges("Create Condition Node");
    }
        // ----------------------------------------------------------------
        // ----------------------------------------------------------------
        public static async Task <CurrentConditions> GetCurrentConditions(string cityKey)
        {
            CurrentConditions currentConditions = new CurrentConditions();
            string            formattedURL      = m_BaseURL + string.Format(m_ConditionsEndpoint, cityKey, m_ApiKey);

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(formattedURL);

                string json = await response.Content.ReadAsStringAsync();

                currentConditions = (JsonConvert.DeserializeObject <List <CurrentConditions> >(json)).FirstOrDefault();
            }

            return(currentConditions);
        }
        public ActionResult Index(String zipCode = null)
        {
            if (String.IsNullOrWhiteSpace(zipCode))
            {
                zipCode = "53211";
            }

            CurrentConditions currentConditions = this.weatherClient.GetCurrentConditions(zipCode);

            DependencyInjectionIndexModel model = new DependencyInjectionIndexModel()
            {
                WeatherData = currentConditions
            };

            return(View(model));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Performs a call to the API in order to retrieve current weather conditions for selected city
        /// </summary>
        /// <param name="cityKey">Key used to identify selected city</param>
        /// <param name="language">Selected language</param>
        /// <returns>Current weather conditions for selected city</returns>
        public static async Task <CurrentConditions> GetCurrentConditions(string cityKey, string language)
        {
            var currentConditions = new CurrentConditions();

            string url = BaseUrl + string.Format(currentConditionsUrl, cityKey, ApiKey, language);

            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(url);

                string json = await response.Content.ReadAsStringAsync();

                currentConditions = JsonConvert.DeserializeObject <List <CurrentConditions> >(json).FirstOrDefault();
            }

            return(currentConditions);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the current conditions for the given zip code
        /// </summary>
        /// <remarks>
        /// This method first checks the cache to see if we already have a cached copy of the current
        /// conditions for the given zip code.  If not, we'll call the object that we are wrapping to
        /// get the current conditions, store the results in the cache and return them.  If we already
        /// have a cached copy, we just return those.
        /// <para>
        /// In this very simple implementation, results are cached for 5 minutes
        /// </para>
        /// </remarks>
        /// <param name="zipCode">A String of the zip code to get the current locations for</param>
        /// <returns>A CurrentConditions object giving the conditions at the specified location</returns>
        public CurrentConditions GetCurrentConditions(string zipCode)
        {
            Cache cache = HttpRuntime.Cache;

            CurrentConditions currentConditions = cache[zipCode] as CurrentConditions;

            if (currentConditions == null)
            {
                // We don't have the value in the cache, so we need to query it from
                // the service and store it in the cache
                currentConditions = this.wrappedWeatherClient.GetCurrentConditions(zipCode);

                cache.Add(zipCode, currentConditions, null, DateTime.Now.AddMinutes(5),
                          Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
            }
            return(currentConditions);
        }
Exemplo n.º 26
0
        public static async Task <CurrentConditions> GetCurrentConditionsAsync(string city)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            string url = BASE_URL + string.Format(CONDITIONS_URL, city, API_KEY);

            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(url);

                string json = await response.Content.ReadAsStringAsync();

                currentConditions = (JsonConvert.DeserializeObject <List <CurrentConditions> >(json)).FirstOrDefault();
            }

            return(currentConditions);
        }
Exemplo n.º 27
0
        public async static Task <CurrentConditions> GetCurrentConditions(string cityKey)
        {
            CurrentConditions conditions = new CurrentConditions();

            string url = Base_Url + String.Format(Current_Conditions_Endpoint, cityKey, Api_Key);


            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetAsync(url);

                string json = await response.Content.ReadAsStringAsync();

                conditions = JsonConvert.DeserializeObject <List <CurrentConditions> >(json).FirstOrDefault();
            }

            return(conditions);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Maps the NOAA response object to our standard response object
        /// </summary>
        /// <param name="response">A NoaaResponse object of the response received from the NOAA service</param>
        /// <returns></returns>
        internal CurrentConditions MapResponseObject(NoaaResponse response)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            currentConditions.Source       = "NOAA";
            currentConditions.LocationName = response.location.areaDescription;
            currentConditions.Latitide     = Convert.ToDouble(response.location.latitude);
            currentConditions.Longitude    = Convert.ToDouble(response.location.longitude);
            //currentConditions.ObservationTime = DateTime.ParseExact(response.currentobservation.Date, "dd MMM HH:mm", CultureInfo.InvariantCulture);

            currentConditions.ConditionsDescription = response.currentobservation.Weather;
            currentConditions.Temperature           = Convert.ToDouble(response.currentobservation.Temp);
            currentConditions.Humidity             = Convert.ToDouble(response.currentobservation.Relh);
            currentConditions.Dewpoint             = Convert.ToDouble(response.currentobservation.Dewp);
            currentConditions.Windchill            = ConvertWindchillString(response.currentobservation.WindChill);
            currentConditions.WindSpeed            = Convert.ToDouble(response.currentobservation.Winds);
            currentConditions.WindSpeedGusts       = Convert.ToDouble(response.currentobservation.Gust);
            currentConditions.WindDirectionDegrees = Convert.ToDouble(response.currentobservation.Windd);
            currentConditions.WindDirection        = this.MapWindDirection(response.currentobservation.Windd);

            return(currentConditions);
        }
Exemplo n.º 29
0
        private void SetupDesignerDisplay()
        {
            Query = "Test City";

            // Setting private variable directly to avoid triggering OnPropertyChanged event (and associated API
            // call). Otherwise this will exhaust API limit by making a call each time the designer is reloaded
            selectedCity = new City
            {
                LocalizedName = "Test City",
                Country       = new Region
                {
                    LocalizedName = "United States",
                    ID            = "US"
                },
                AdministrativeArea = new Region
                {
                    LocalizedName = "Minnesota",
                    ID            = "MN"
                }
            };

            CurrentConditions = new CurrentConditions
            {
                WeatherText = "Test Weather Text",
                Temperature = new Temperature
                {
                    Imperial = new UnitValue
                    {
                        Value = 32
                    }
                }
            };

            for (int i = 1; i <= 5; i++)
            {
                Cities.Add(SelectedCity);
            }
        }
Exemplo n.º 30
0
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            string zip = SearchBar.Text;


            using (WebClient webClient = new WebClient())


            {
                //Tells the Weather Underground API who's boss
                webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

                // Grabs json info from github and saves it to a string.
                string json = webClient.DownloadString("http://api.wunderground.com/api/a3bf043be8c7fc4a/geolookup/conditions/q/" + zip + ".json");

                //this converts the json info into usable information for us
                CurrentConditions currentConditions = new CurrentConditions();
                currentConditions = JsonConvert.DeserializeObject <CurrentConditions>(json);

                //This stores the information that was converted to strings
                string Weather       = currentConditions.weather;
                string Elevation     = currentConditions.elevation;
                string Longitude     = currentConditions.lon;
                string Latitude      = currentConditions.lat;
                string LocationState = currentConditions.state;
                string LocationCity  = currentConditions.city;
                string Temperature   = currentConditions.temperature_string;
                string FeelsLike     = currentConditions.feelslike_string;
                string Wind          = currentConditions.wind_string;
                string WindDirection = currentConditions.wind_dir;
                string Humidity      = currentConditions.relative_humidity;
                string UV            = currentConditions.UV;
                string Visibility    = currentConditions.visibility_mi;
                string Percipitation = currentConditions.precip_today_string;

                // writes the information out to the console
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// A simple mapper method that maps the response we get from WeatherUnderground to our standard response object
        /// for current conditions
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        internal CurrentConditions MapCurrentConditionsResponse(CurrentConditionsResponse response)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            // I took the name and location from the display location.  You could choose to map it from the measurement location
            currentConditions.Source          = "Weather Underground";
            currentConditions.LocationName    = response.current_observation.display_location.full;
            currentConditions.Latitide        = Convert.ToDouble(response.current_observation.display_location.latitude);
            currentConditions.Longitude       = Convert.ToDouble(response.current_observation.display_location.longitude);
            currentConditions.ObservationTime = DateTime.Parse(response.current_observation.local_time_rfc822);

            currentConditions.ConditionsDescription = response.current_observation.weather;
            currentConditions.Temperature           = response.current_observation.temp_f;
            currentConditions.Humidity  = Convert.ToDouble(response.current_observation.relative_humidity.Replace('%', ' '));
            currentConditions.Dewpoint  = response.current_observation.dewpoint_f;
            currentConditions.Windchill = this.ConvertWindchillString(response.current_observation.windchill_f);

            currentConditions.WindSpeed            = response.current_observation.wind_mph;
            currentConditions.WindDirectionDegrees = response.current_observation.wind_degrees;
            currentConditions.WindDirection        = response.current_observation.wind_dir;

            return(currentConditions);
        }