Mini Kabibi Habibi

Current Path : C:/Users/Public/Documents/DXperience 13.1 Demos/WinForms/CS/MapMainDemo/
Upload File :
Current File : C:/Users/Public/Documents/DXperience 13.1 Demos/WinForms/CS/MapMainDemo/DemoUtils.cs

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace DevExpress.XtraMap.Demos {
    /// <summary>
    /// Summary description for DemoUtils.
    /// </summary>
    public class DemoUtils {
        static string key = "AmSNFwVzMvaqFlCYQx9RRUfcAwSQCzi_Vcesric6JFQuBO9wZFXEsqzili-INaUA";

        public static string DevexpressBingKey { get { return key; } }

        public static XDocument LoadXml(string name) {
            try {
                return XDocument.Load("file:\\\\" + GetRelativePath(name));
            } catch {
                return null;
            }
        }
        public static string GetRelativePath(string name) {
            name = "Data\\" + name;
            string path = System.Windows.Forms.Application.StartupPath;
            string s = "\\";
            for (int i = 0; i <= 10; i++) {
                if (System.IO.File.Exists(path + s + name))
                    return (path + s + name);
                else
                    s += "..\\";
            }
            return "";
        }
        public static string GetRelativeDirectoryPath(string name) {
            name = "Data\\" + name;
            string path = System.Windows.Forms.Application.StartupPath;
            string s = "\\";
            for (int i = 0; i <= 10; i++) {
                if (System.IO.Directory.Exists(path + s + name))
                    return (path + s + name);
                else
                    s += "..\\";
            }
            return "";
        }
    }

    public class CityWeather {
        OpenWeatherMapService.CityWeatherInfo cityWeatherInfo;
        List<CityWeather> forecast;
        Weather weather;
        List<WeatherDescription> weatherDescriptions;

        public CityWeather(OpenWeatherMapService.CityWeatherInfo cityWeatherInfo) {
            this.cityWeatherInfo = cityWeatherInfo;
            this.weather = new Weather(cityWeatherInfo.main);
            this.weatherDescriptions = new List<WeatherDescription>();
            foreach (OpenWeatherMapService.WeatherDescriptionInfo weatherDescription in cityWeatherInfo.weather)
                weatherDescriptions.Add(new WeatherDescription(weatherDescription));
        }

        public DateTime DateTime { get { return GetTime(cityWeatherInfo.dt); } }
        public int CityID { get { return cityWeatherInfo.id; } }
        public string City { get { return cityWeatherInfo.name; } }
        public double Longitude { get { return cityWeatherInfo.coord.lon; } }
        public double Latitude { get { return cityWeatherInfo.coord.lat; } }
        public Weather Weather { get { return weather; } }
        public List<WeatherDescription> WeatherDescriptions { get { return weatherDescriptions; } }
        public List<CityWeather> Forecast { get { return forecast; } }
        public string CelsiusDisplayText { get { return City + "\n" + weather.CelsiusTemperatureString; } }
        public string KelvinDisplayText { get { return City + "\n" + weather.KelvinTemperatureString; } }
        public string FahrenheitDisplayText { get { return City + "\n" + weather.FahrenheitTemperatureString; } }

        public DateTime ForecastTime { get; set; }
        public string WeatherIconPath { get; set; }

        public event EventHandler ForecastUpdated;

        DateTime GetTime(long seconds) {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return dtDateTime.AddSeconds(seconds).ToLocalTime();
        }
        internal void SetForecast(List<OpenWeatherMapService.CityWeatherInfo> forecast) {
            List<CityWeather> cityWeatherList = new List<CityWeather>();
            foreach (OpenWeatherMapService.CityWeatherInfo cityWeatherInfo in forecast) 
                cityWeatherList.Add(new CityWeather(cityWeatherInfo));
            this.forecast = cityWeatherList;
            
            if (ForecastUpdated != null) ForecastUpdated(this, EventArgs.Empty);
        }
        public string GetTemperatureDataMember(TemperatureMeasureUnits measureUnits) {
            switch (measureUnits) {
                case TemperatureMeasureUnits.Fahrenheit:
                    return "FahrenheitDisplayText";
                case TemperatureMeasureUnits.Kelvin:
                    return "KelvinDisplayText";
                default:
                    return "CelsiusDisplayText";
            }
        }
    }

    public enum TemperatureMeasureUnits {
        Celsius,
        Fahrenheit,
        Kelvin
    }

    public class Weather {
        OpenWeatherMapService.WeatherInfo weatherInfo;

        public int CelsiusTemperature { get { return (int)(weatherInfo.temp - 273.15); } }
        public int FahrenheitTemperature { get { return (int)(weatherInfo.temp - 273.15) * 9 / 5 + 32; } }
        public int KelvinTemperature { get { return (int)weatherInfo.temp; } }
        public string CelsiusTemperatureString { get { return CelsiusTemperature.ToString("+#;-#;0") + " �C"; } }
        public string FahrenheitTemperatureString { get { return FahrenheitTemperature.ToString("+#;-#;0") + " �F"; } }
        public string KelvinTemperatureString { get { return weatherInfo.temp.ToString("+#;-#;0") + " �K"; } }

        public Weather(OpenWeatherMapService.WeatherInfo weatherInfo) {
            this.weatherInfo = weatherInfo;
        }
        public string GetTemperatureString(TemperatureMeasureUnits measureUnits) {
            switch (measureUnits) {
                case TemperatureMeasureUnits.Fahrenheit:
                    return FahrenheitTemperatureString;
                case TemperatureMeasureUnits.Kelvin:
                    return KelvinTemperatureString;
                default:
                    return CelsiusTemperatureString;
            }
        }
    }
    public class WeatherDescription {
        OpenWeatherMapService.WeatherDescriptionInfo weatherDescriptionInfo;

        public string IconName { get { return weatherDescriptionInfo.icon; } }

        public WeatherDescription(OpenWeatherMapService.WeatherDescriptionInfo weatherDescriptionInfo) {
            this.weatherDescriptionInfo = weatherDescriptionInfo;
        }
    }
    public class OpenWeatherMapService {
        const string OpenWeatherUrl = "http://api.openweathermap.org/data/2.1/find/city?bbox=-180,-90,180,90";
        const string OpenWeatherIconPathPrefix = "http://openweathermap.org/img/w/";

        #region classes for JSON parsing

        [DataContract]
        public class ForecastInfo {
            [DataMember]
            public List<CityWeatherInfo> list;
        }
        [DataContract]
        public class WorldWeatherInfo {
            [DataMember]
            public IList<CityWeatherInfo> list;
        }
        [DataContract]
        public class CityWeatherInfo {
            [DataMember]
            internal int id = 0;
            [DataMember]
            internal string name = null;
            [DataMember]
            internal Coordinates coord = null;
            [DataMember]
            internal WeatherInfo main = null;
            [DataMember]
            internal List<WeatherDescriptionInfo> weather = null;
            [DataMember]
            internal WindInfo wind = null;
            [DataMember]
            internal long dt = 0;
        }
        [DataContract]
        public class WeatherDescriptionInfo {
            [DataMember]
            internal string main = null;
            [DataMember]
            internal string description = null;
            [DataMember]
            internal string icon = null;
        }
        [DataContract]
        public class WindInfo {
            [DataMember]
            internal double speed = 0.0;
            [DataMember]
            internal double deg = 0.0;
        }
        [DataContract]
        public class WeatherInfo {
            [DataMember]
            internal double temp = 0.0;
            [DataMember]
            internal double pressure = 0.0;
            [DataMember]
            internal double humidity = 0.0;
        }
        [DataContract]
        public class Coordinates {
            [DataMember]
            internal double lon = 0.0;
            [DataMember]
            internal double lat = 0.0;
        }

        #endregion

        List<CityWeather> weatherInCities;
        List<string> capitalNames;
        static readonly object forecastLocker = new object();

        public CityWeather LosAngelesWeather { get; set; }
        public List<CityWeather> WeatherInCities { get { return weatherInCities; } }
        public event EventHandler ReadCompleted;

        public OpenWeatherMapService(List<string> capitalNames) {
            this.capitalNames = capitalNames;
        }
        public void GetWeatherAsync() {
            WebClient weatherClient = new WebClient();
            weatherClient.OpenReadCompleted += weatherClient_OpenReadCompleted;
            weatherClient.OpenReadAsync(new Uri(OpenWeatherUrl));
        }
        void weatherClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
            WebClient weatherClient = sender as WebClient;
            weatherClient.OpenReadCompleted -= weatherClient_OpenReadCompleted;

            if (e.Cancelled || e.Error != null)
                return;

            Stream stream = e.Result;
            Task.Factory.StartNew(() => {
                DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(WorldWeatherInfo));
                WorldWeatherInfo worldWeatherInfo = (WorldWeatherInfo)dc.ReadObject(stream);
                List<CityWeather> citiesWeather = new List<CityWeather>();
                foreach (CityWeatherInfo weatherInfo in worldWeatherInfo.list) {
                    CityWeather cityWeather = new CityWeather(weatherInfo);
                    if (cityWeather.City == "Los Angeles")
                        LosAngelesWeather = cityWeather;
                    if (cityWeather.WeatherDescriptions != null && cityWeather.WeatherDescriptions.Count > 0)
                        cityWeather.WeatherIconPath = OpenWeatherIconPathPrefix + cityWeather.WeatherDescriptions[0].IconName + ".png";

                    if (capitalNames.Contains(cityWeather.City))
                        citiesWeather.Add(cityWeather);
                }
                weatherInCities = citiesWeather;
                RaiseReadComplete();
            });
        }
        public void GetForecastForCityAsync(CityWeather cityWeather) {
            string link = "http://api.openweathermap.org/data/2.1/forecast/city/" + cityWeather.CityID.ToString();
            WebClient forecastClient = new WebClient();
            forecastClient.OpenReadCompleted += forecastClient_OpenReadCompleted;
            forecastClient.OpenReadAsync(new Uri(link), cityWeather);
        }
        void forecastClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
            if (e.Error == null) {
                ((WebClient)sender).OpenReadCompleted -= forecastClient_OpenReadCompleted;
                Stream stream = e.Result;
                CityWeather cityWeatherInfo = (CityWeather)e.UserState;
                Task.Factory.StartNew(() => {
                    lock (forecastLocker) {
                        DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(ForecastInfo));
                        ForecastInfo forecast = (ForecastInfo)dc.ReadObject(stream);
                        cityWeatherInfo.SetForecast(forecast.list);
                    }
                });
            }
        }
        void RaiseReadComplete() {
            if (ReadCompleted != null) ReadCompleted(this, EventArgs.Empty);
        }
    }
    public class DemoWeatherItemFactory : DefaultMapItemFactory {
        protected override void InitializeItem(MapItem item, object obj) {
            CityWeather cityWeather = obj as CityWeather;
            MapCustomElement element = item as MapCustomElement;
            if (element == null || cityWeather == null) 
                return;
            element.Padding = new Padding(2, 6, 2, 0);
            element.ImageUri = new Uri(cityWeather.WeatherIconPath);
        }
    }
}