做自動更新機制時,從網路下載的 XML 清單(manifest)在反序列化之前一定要先驗一遍結構,否則一個欄位拼錯就可能讓整個更新流程在執行期爆掉。Microsoft Updater Application Block 2.0 裡的 SchemaValidator 就是專門處理這件事的輔助類別,設計簡潔,很值得當範式來讀。
//============================================================================================================
// Microsoft Updater Application Block for .Net
//
// SchemaValidator.cs
//
// Contains the implementation of the schema validator.
//
// For more information see the Updater Application Block Implementation Overview.
//
//============================================================================================================
// Copyright ?Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//============================================================================================================
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
namespace Microsoft.ApplicationBlocks.Updater.Utilities
{
/// <summary>
/// Helper class to perform schema validations.
/// </summary>
public sealed class SchemaValidator
{
#region Private members
/// <summary>
/// The schemas that will be used for validation.
/// </summary>
private ArrayList schemas = new ArrayList(2);
/// <summary>
/// The errors detected during the validation.
/// </summary>
private ArrayList errors = new ArrayList(5);
/// <summary>
/// Whether the document is valid or not.
/// </summary>
private bool isValid;
#endregion
#region Constructors
/// <summary>
/// Creates an instance of the SchemaValidator using the document and the schemas.
/// </summary>
/// <param name="document">The document to validate.</param>
/// <param name="schemas">A list of schemas to validate the document against.</param>
public SchemaValidator( string document, params Stream[] schemas )
{
this.schemas.Add( document );
foreach( Stream s in schemas )
{
this.schemas.Add( s );
}
isValid = true;
}
#endregion
#region Public members
/// <summary>
/// Validates the document and returns the result of the validation.
/// </summary>
/// <returns><c>true</c> if the document has succeeded the validation,
/// otherwise <c>false</c>.</returns>
public bool Validate()
{
errors.Clear();
XmlValidatingReader vr = null;
object doc = schemas[0];
if ( doc is Stream )
{
vr = new XmlValidatingReader( (Stream)doc, XmlNodeType.Element, null );
}
else if ( doc is String )
{
vr = new XmlValidatingReader( (string)doc, XmlNodeType.Element, null );
}
try
{
for( int i = 1; i < schemas.Count; i++ )
{
vr.Schemas.Add( null, new XmlTextReader( (Stream)schemas[i] ) );
}
vr.ValidationEventHandler +=
new System.Xml.Schema.ValidationEventHandler( ValidationEventHandler );
while( vr.Read() );
return isValid;
}
finally
{
vr.Close();
}
}
/// <summary>
/// Contains the validation errors encountered in the last validation operation.
/// </summary>
public ValidationEventArgs[] Errors
{
get
{
return (ValidationEventArgs[])errors.ToArray( typeof( ValidationEventArgs ) );
}
}
/// <summary>
/// Helper method to capture the event handlers.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The information about the event.</param>
private void ValidationEventHandler( object sender, System.Xml.Schema.ValidationEventArgs e )
{
errors.Add( e );
if ( e.Severity == XmlSeverityType.Warning )
{
return;
}
isValid = false;
}
#endregion
}
}
建構子用 params Stream[] 收 schema,第一個參數則是待驗證的文件,兩者一起塞進同一個 ArrayList,靠索引 0 與索引 1 之後來區分角色。這種寫法很省字,但也讓程式碼可讀性依賴讀者知道這個約定。
Validate() 把驗證結果分成「有沒有錯誤」和「有哪些錯誤」兩條線:回傳值是布林,細節則透過 Errors 屬性以 ValidationEventArgs[] 陣列取回。事件處理常式刻意把 Warning 與 Error 分開對待——警告照樣記錄但不影響 isValid,只有嚴重度達 Error 以上才會把旗標翻成 false。這個判斷是整支程式最關鍵的一行。
下面的程式示範如何在下載後先驗證、再反序列化:
/// <summary>
/// Download and validates the manifest using the Uri location.
/// </summary>
/// <param name="type">The type that represents the manifest class.</param>
/// <param name="location">The location of the manifest.</param>
/// <param name="schemaResource">The resource where the embedded XSD resides in the assembly.</param>
/// <returns>The Manifest instance.</returns>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
private object ValidateAndDeserialize( Type type, Uri location, string schemaResource )
{
object result = null;
try
{
string doc = DownloadFile( location );
using ( Stream schema = Assembly.GetExecutingAssembly()
.GetManifestResourceStream( schemaResource ) )
{
SchemaValidator validator = new SchemaValidator( doc, schema );
if ( !validator.Validate() )
{
Logger.LogAndThrowException(
new ApplicationUpdaterException(
Resource.ResourceManager[
Resource.MessageKey.ManifestSchemaError,
location, schemaResource ] ) );
}
XmlSerializer xser = new XmlSerializer( type );
result = xser.Deserialize( new XmlTextReader( doc, XmlNodeType.Document, null ) );
}
}
catch( Exception ex )
{
Logger.LogAndThrowException( ex );
}
return result;
}
這裡有兩個實務上的好習慣:XSD 以「內嵌資源」形式隨組譯碼一起散布,避免外部檔案被竄改或版本不一致;驗證失敗時拋出自訂例外並帶上位置與資源名稱,讓日誌能直接指向問題來源。整體流程是「先驗結構、再談內容」,把錯誤攔在反序列化之前,這正是處理遠端 XML 時最該堅持的順序。