Yahoo!天気予報APIを利用して、自分のWCFサービスを作成します.


この文章はhttp://www.cnblogs.com/Ivan-Yan/archive/2010/01/16/1649479.htmlこの文章の基礎の上に
WCFのサービスモードは、一般的にサービスをサーバー側で作成し、クライアント側でこのサービスを呼び出します.本ファイルは、Silverlightクライアントの呼び出しで実現されます.まず、WCFサービスを作成し、DataSetを戻り値として定義します.一方、silverlightクライアントでは、ArayOfXElementタイプの戻り値を得ることができます.messageBoxで出力すると、このデータは1つのxml構造のデータであることが分かります.
WCFサービス端末:
using System.Xmlを追加します.using System.Collections;using System.Data名前空間3つ
namespace WeatherReport.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class weatherService
    {
        [OperationContract]
        public void DoWork()
        {
            //          
            return;
        }

        [OperationContract]
        public DataSet getWeather(string strCityName)
        {
            string strXml = "http://xml.weather.yahoo.com/forecastrss?p=CHXX" + CityNameToCityNum(strCityName);
            XmlDocument Weather = new XmlDocument();
            Weather.Load(strXml);

            XmlNamespaceManager namespacemanager = new XmlNamespaceManager(Weather.NameTable);
            namespacemanager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNodeList nodes = Weather.SelectNodes("/rss/channel/item/yweather:forecast", namespacemanager);

            DataSet ds = new DataSet();
            DataTable dt = new DataTable("weatherMessage");
            ds.Tables.Add(dt);

            ds.Tables["weatherMessage"].Columns.Add("Data", typeof(string));
            ds.Tables["weatherMessage"].Columns.Add("Week", typeof(string));
            ds.Tables["weatherMessage"].Columns.Add("Weather", typeof(string));
            ds.Tables["weatherMessage"].Columns.Add("Tlow", typeof(string));
            ds.Tables["weatherMessage"].Columns.Add("Thigh", typeof(string));

            if (nodes.Count > 0)
            {
                foreach (XmlNode node in nodes)
                {
                    DataRow dr = ds.Tables["weatherMessage"].NewRow();
                    dr["Data"] = EmonthToCmonth(node.SelectSingleNode("@date").Value.ToString());
                    dr["Week"] = EweekToCweek(node.SelectSingleNode("@day").Value.ToString()) + "(" + node.SelectSingleNode("@day").Value.ToString() + ")";
                    dr["Weather"] = node.SelectSingleNode("@text").Value;
                    dr["Tlow"] = FToC(int.Parse(node.SelectSingleNode("@low").Value)) + "℃";
                    dr["Thigh"] = FToC(int.Parse(node.SelectSingleNode("@high").Value)) + "℃";
                    ds.Tables["weatherMessage"].Rows.Add(dr);
                }
                return ds;
            }
            else
            {
                DataRow dr = ds.Tables["weatherMessage"].NewRow();
                dr["Data"] = "None";
                dr["Week"] = "None";
                dr["Weather"] = "None";
                dr["Tlow"] = "None";
                dr["Thigh"] = "None";

                ds.Tables["weatherMessage"].Rows.Add(dr);
                return ds;
            }

        }

        /// <summary>
        ///         
        /// </summary>
        /// <param name="f">   </param>
        /// <returns></returns>
        [OperationContract]
        private string FToC(int f)
        {
            return Math.Round((f - 32) / 1.8, 1).ToString();
        }

        /// <summary>
        ///           
        /// </summary>
        /// <param name="strEweek">       </param>
        /// <returns></returns>
        [OperationContract]
        private string EweekToCweek(string strEweek)
        {
            switch (strEweek)
            {
                case "Mon":
                    return "   ";
                // break;
                case "Tue":
                    return "   ";
                // break;
                case "Wed":
                    return "   ";
                // break;
                case "Thu":
                    return "   ";
                //break;
                case "Fri":
                    return "   ";
                //break;
                case "Sat":
                    return "   ";
                // break;
                case "Sun":
                    return "   ";
                // break;
                default:
                    return "    ";
                // break;
            }
        }

        /// <summary>
        ///          
        /// </summary>
        /// <param name="strReplace">        </param>
        /// <returns></returns>
        [OperationContract]
        private string EmonthToCmonth(string strReplace)
        {
            return Convert.ToDateTime(strReplace).ToString("yyyy MM dd ");
        }

        /// <summary>
        ///             
        /// </summary>
        /// <param name="strCityName">    </param>
        /// <returns></returns>
        [OperationContract]
        private string CityNameToCityNum(string strCityNameToNum)
        {
            //                 
            Hashtable htWeather = new Hashtable();
            htWeather.Add("  ", "0008");
            htWeather.Add("  ", "0133");
            htWeather.Add("  ", "0044");
            htWeather.Add("  ", "0448");
            htWeather.Add("  ", "0116");
            htWeather.Add("  ", "0031");
            htWeather.Add("  ", "0017");
            htWeather.Add("  ", "0097");
            htWeather.Add("  ", "0049");
            htWeather.Add("  ", "0064");
            htWeather.Add("  ", "0512");
            htWeather.Add("  ", "0165");
            htWeather.Add("    ", "0249");
            htWeather.Add("    ", "0135");
            htWeather.Add("  ", "0013");
            htWeather.Add("  ", "0259");
            htWeather.Add("  ", "0037");
            htWeather.Add("  ", "0080");
            htWeather.Add("  ", "0502");
            htWeather.Add("  ", "0100");
            htWeather.Add("  ", "0016");
            htWeather.Add("   ", "0122");
            htWeather.Add("  ", "0039");
            htWeather.Add("  ", "0129");
            htWeather.Add("  ", "0076");
            htWeather.Add("  ", "0119");
            htWeather.Add("  ", "0141");
            htWeather.Add("  ", "0010");
            htWeather.Add("  ", "0079");
            htWeather.Add("  ", "0236");
            htWeather.Add("  ", "0099");

            object cityNum = htWeather[strCityNameToNum];

            if (cityNum == null)
            {
                return "City not found";
            }
            else
            {
                return cityNum.ToString();
            }
        }
        //              [OperationContract]     
    }
}
silverlight   :

private WCFService.weatherServiceClient sc = new WCFService.weatherServiceClient();

        public void addEvent()
        {
            sc.getWeatherCompleted += new EventHandler<WCFService.getWeatherCompletedEventArgs>(sc_getWeatherCompleted);
        }

        void sc_getWeatherCompleted(object sender, WCFService.getWeatherCompletedEventArgs e)
        {
            var result = e.Result;
            var s = from item in result.Nodes[1].Descendants("weatherMessage")
                    select new
                    {
                        Data = item.Element("Data").Value,
                        Week = item.Element("Week").Value,
                        Weather = item.Element("Weather").Value,
                        Tlow = item.Element("Tlow").Value,
                        Thigh = item.Element("Thigh").Value
                    };
            foreach (var v in s)
            {
                MessageBox.Show(v.Data + "--" + v.Weather);
            }
        }

      

        private void Button_Click(object sender, RoutedEventArgs e)
        {

             addEvent();
            sc.getWeatherAsync("  ");
        }

  ,     WCF