1.在Web中添加天气服务引用地址
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
2.在Web中添加Wcf服务接口IWeatherService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace EasySL.Web.WCF
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IWeatherService”。
[ServiceContract]
public interface IWeatherService
{
[OperationContract]
string[] GetCityWeather(string CityName);
}
}
3.在Web中实现服务接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text; namespace EasySL.Web.WCF
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“WeatherService”。
// 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 WeatherService.svc 或 WeatherService.svc.cs,然后开始调试。
public class WeatherService : IWeatherService
{
public string[] GetCityWeather(string CityName)
{
ServiceRefWeather.WeatherWebServiceSoapClient client = new ServiceRefWeather.WeatherWebServiceSoapClient("WeatherWebServiceSoap");
string[] cityNameWeather = client.getWeatherbyCityName(CityName);
return cityNameWeather;
}
}
}
4.在client添加自己创建的Wcf服务地址、调用服务接口
/// <summary>
/// 通过wcf获取天气数据信息
/// </summary>
private void InitDataWeather()
{
try
{
ServiceReference1.WeatherServiceClient client = new ServiceReference1.WeatherServiceClient();
client.GetCityWeatherCompleted += (s, e) =>
{
try
{
if (e.Error == null)
{
string[] cityWeather = new string[e.Result.Count];
讲e.Result结果显示在页面中就ok了,然后我们将e.Result进行数据格式处理,运用独立存储讲结果保存起来 }
else
{
lbltitle1.Content = e.Error.Message;
}
}
catch (Exception ex)
{
lbltitle1.Content = ex.Message;
} };
client.GetCityWeatherAsync("北京");
}
catch (Exception ex)
{
//lbltitle1.Content = ex.Message;
} }
5.将数据结果存放到本地(运用独立存储技术)
private void WeatherWriterIsolatedStorageFile(string str)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
if (isf.FileExists("Weather.txt"))
{
isf.DeleteFile("Weather.txt");
}
using (Stream stream = isf.CreateFile("Weather.txt"))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(str);
}
}
}
6.读取存放的数据结果(独立存储)
private void ReaderWeatherIsolatedStorageFile()
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
if (isf.FileExists("AppConfig/Weather.txt"))
{
using (Stream stream = isf.OpenFile("Weather.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string[] line = reader.ReadToEnd().Split('|');
}
}
isf.DeleteFile("Weather.txt");
}
else
{
InitDataWeather();
}
}