Microsoft Enterprise Library 5.0 系列(三) Validation Application Block (高级)
企业库验证应用程序模块之配置文件模式:
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下载 \( ̄[]  ̄ \)
本文来自博客园,作者:jevan,转载请注明原文链接:https://www.cnblogs.com/DoNetCShap/archive/2011/12/21/2295561.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端