企业库验证应用程序模块之配置文件模式:
1. 新建一个控制台应用程序,并创建一个Customer类,其代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
public class Customer
{
public string CustomerName;
public Customer(string customerName)
{
this.CustomerName = customerName;
}
public int Test()
{
return -5;
}
}
}
2. 运行EntLibConfig.exe, 选择Blocks菜单 ,单击 Add Validation Settings .
3. 点击Validated Types 区块右上角的加号按钮,然后点击 Add Type to Validate,这时会要你选择要验证的类,因为我们是想对Customer类的属性进行验证,所以我们要导入我们刚刚创建的类,点击并Add from File找到我们的应用程序Debug文件夹下的ConsoleApplication1.exe(根据你创建时起的名字而不同),Customer类就包含在这个程序内:
4. 导入后,我们就可以看到多了个ConsoleApplication1程序集,接着我们要选择它所包含的Customer类,如下图所示,选择后点击OK:
5. 在Customer面板上右键— Add Validation Ruleset:
6. 在设置Customer面板中的Defaule Ruleset属性为新创建的Validation Ruleset,接着在Validation Ruleset面板右键—Select Members,在弹出的选择框中选择
7. 在弹出的成员选择界面,我们选择要测试的Test方法和CustomerName属性:
8. 在Field:CustomerName面板上右键—Add Validators –Add Not Null Validator:
9. 对该验证器的设置如下图所示:
10. 在Method:Test面板上右键—Add Validators –Add Range Validator:
11. 对该验证器的设置如下图所示:
12. 点击 File 菜单,单击 Save,保存为一个App.config文件,可以先保存到桌面,之后要用到它.
13. 将App.config添加到工程中,并添加需要的引用,如图所示:
14. 测试:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Validator<Customer> customerValidator = ValidationFactory.CreateValidator<Customer>("Validation Ruleset");
Customer myCustomer = new Customer(null);
ValidationResults r = customerValidator.Validate(myCustomer);
if (!r.IsValid)
{
for (int i = 0; i < r.Count; i++)
{
Console.WriteLine("出错{0}:" + r.ElementAt(i).Message, i + 1);
}
}
else
{
Console.WriteLine("正确");
}
}
}
public class Customer
{
public string CustomerName;
public Customer(string customerName)
{
this.CustomerName = customerName;
}
public int Test()
{
return -5;
}
}
}
15. 运行结果:
Demo下载 \( ̄[]  ̄ \)