在这些文章中,将实现一个WeatherDataSource,它将针对由weather(英文)提供的REST(英文)XMLAPI来工作,以便根据邮政编码来检索天气信息。通常会首先实现派生的数据源控件。
public class WeatherDataSource : DataSourceControl {
public static readonly string
CurrentConditionsViewName = "CurrentConditions";
private WeatherDataSourceView _currentConditionsView;
private WeatherDataSourceView CurrentConditionsView {
get {
if (_currentConditionsView == null) {
_currentConditionsView = new WeatherDataSourceView(this, CurrentConditionsViewName);
}
return _currentConditionsView;
}
}
public string ZipCode {
get {
string s = (string)ViewState["ZipCode"];
return (s != null) ? s : String.Empty;
}
set {
if (String.Compare(value, ZipCode,
StringComparison.Ordinal) != 0) {
ViewState["ZipCode"] = value;
CurrentConditionsView.RaiseChangedEvent();
}
}
}
protected override DataSourceView GetView(string viewName) {
if (String.IsNullOrEmpty(viewName) ||
(String.Compare(viewName, CurrentConditionsViewName,
StringComparison.OrdinalIgnoreCase) == 0)) {
return CurrentConditionsView;
}
throw new ArgumentOutOfRangeException("viewName");
}
protected override ICollection GetViewNames() {
return new string[] { CurrentConditionsViewName };
}
public Weather GetWeather() {
return CurrentConditionView.GetWeather();
}
}
在此选择从 DataSourceControl 中派生。有一点是不易察觉的,事实上数据绑定控件要查找 IDataSource 界面,而 DataSource 控件通过实现 GetView 和 GetViewNames 来实现该界面。之所以需要界面是为了使
数据源控件能够既是表格格式又是分层的(如果可能的话),在这种情况下从主要模型中派生并将另一个模型作为界面来实现)。其次,还允许在各种方案中转换其他控件,以使数据源的容量加倍。 另外还要注意公共 ZipCode 属性和返回强类型化 Weather 对象的 GetWeather 方法。此 API 适合于页面开发人员。页面开发人员无需考虑 DataSourceControl 和 DataSourceView。
默认情况下,DataSourceView 类从诸如 CanUpdate 等的属性返回 false,而从 Update 和相关方法抛出 NotSupportedException。在此,在 WeatherDataSourceView 中唯一需要做的就是替代抽象的 ExecuteSelect 方法,返回包含“选定”天气数据的 IEnumerable。在实现过程中,使用了帮助程序 WeatherService 类,该类仅使用 WebRequest 对象来查询 weather(英文),方法是使用所选的邮政编码(这没什么特别的)。
数据访问代码就被封装在
数据源控件中。此外,通过此模型,weather(英文)能够发布一个组件,该组件还可以封装特定于其服务的详细信息。但愿它会好用。此外,抽象的数据源界面允许 FormView 仅针对天气数据进行工作。