微软企业库5.0学习笔记(四十五)实战数据验证模块----高级篇

  1、添加自定义的提示信息

  验证失败的提示信息可以自定义,企业库的验证模块也提供了自定义的功能。是通过读取资源文件的设置来实现的。首先添加资源文件,在项目的右键菜单中选择【属性】,然后点击【资源】添加文件并且定义三个字符串类型的资源。

  

微软企业库5.0学习笔记(四十五)实战数据验证模块----高级篇_第1张图片  

微软企业库5.0学习笔记(四十五)实战数据验证模块----高级篇_第2张图片

  在上一章中的Customer类的attribute上多添加一些参数,引入资源的命名空间,具体如下所示,就是指明要用的资源名称和类型。

  

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> public   class  Customer 

    [StringLengthValidator(
1 25
        MessageTemplateResourceType 
=   typeof (Resources), 
        MessageTemplateResourceName 
=   " FirstNameMessage " )] 
    
public   string  FirstName {  get set ; } 
    [StringLengthValidator(
1 25
        MessageTemplateResourceType 
=   typeof (Resources), 
        MessageTemplateResourceName 
=   " LastNameMessage " )] 
    
public   string  LastName {  get set ; } 
    [RegexValidator(
@" ^\d\d\d-\d\d-\d\d\d\d$ "
        MessageTemplateResourceType 
=   typeof (Resources), 
        MessageTemplateResourceName 
=   " SSNMessage " )] 
    
public   string  SSN {  get set ; } 
    [ObjectValidator] 
    
public  Address Address {  get set ; } 

 

  继续运行程序,就会发现提示信息变成了自定义的内容。

  2、实现自己验证

  首先在Customer类上添加[HasSelfValidation] 特性(attribute),然后为自验证添加一个方法,参数是ValidationResults .

  

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> using  System;
using  System.Text.RegularExpressions;
using  Microsoft.Practices.EnterpriseLibrary.Validation;
using  Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

namespace  ValidationHOL.BusinessLogic
{
    [HasSelfValidation]
    
public   class  Customer
    {
        
public   string  FirstName {  get set ; }
        
public   string  LastName {  get set ; }
        
public   string  SSN {  get set ; }
        
public  Address Address {  get set ; }

        
static  Regex ssnCaptureRegex  =
            
new  Regex( @" ^(?<area>\d{3})-(?<group>\d{2})-(?<serial>\d{4})$ " );

        [SelfValidation]
        
public   void  ValidateSSN(ValidationResults validationResults)
        {
            
//  validation logic according to 
            
//   http://ssa-custhelp.ssa.gov/cgi-bin/ssa.cfg/php/enduser/std_adp.php?p_faqid=425

            Match match 
=  ssnCaptureRegex.Match( this .SSN);
            
if  (match.Success)
            {
                
string  area  =  match.Groups[ " area " ].Value;
                
string  group  =  match.Groups[ " group " ].Value;
                
string  serial  =  match.Groups[ " serial " ].Value;

                
if  (area  ==   " 666 "
                    
||   string .Compare(area,  " 772 " , StringComparison.Ordinal)  >   0 )
                {
                    validationResults.AddResult(
                        
new  ValidationResult(
                            
" Invalid area " ,
                            
this ,
                            
" SSN " ,
                            
null ,
                            
null ));
                }
                
else   if  (area  ==   " 000 "   ||  group  ==   " 00 "   ||  serial  ==   " 0000 " )
                {
                    validationResults.AddResult(
                        
new  ValidationResult(
                            
" SSN elements cannot be all '0' " ,
                            
this ,
                            
" SSN " ,
                            
null ,
                            
null ));
                }
            }
            
else
            {
                validationResults.AddResult(
                    
new  ValidationResult(
                        
" Must match the pattern '###-##-####' " ,
                        
this ,
                        
" SSN " ,
                        
null ,
                        
null ));
            }
        }
    }
}

 

  3、自定义验证

  继承Validator类,重写里面的方法DoValidate 即可。

  

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />-->   public   class  SSNValidator : Validator < string >
    {
        
public  SSNValidator( string  tag)
            : 
this (tag,  false )
        {
        }

        
public  SSNValidator( string  tag,  bool  ignoreHypens)
            : 
base ( string .Empty, tag)
        {
            
this .ignoreHypens  =  ignoreHypens;
        }

        
static  Regex ssnCaptureRegex  =
            
new  Regex( @" ^(?<area>\d{3})-(?<group>\d{2})-(?<serial>\d{4})$ " );
        
static  Regex ssnCaptureNoHypensRegex  =
            
new  Regex( @" ^(?<area>\d{3})(?<group>\d{2})(?<serial>\d{4})$ " );
        
private   bool  ignoreHypens;

        
protected   override   string  DefaultMessageTemplate
        {
            
get  {  throw   new  NotImplementedException(); }
        }

        
protected   override   void  DoValidate(
            
string  objectToValidate,
            
object  currentTarget,
            
string  key,
            ValidationResults validationResults)
        {
            
//  validation logic according to 
            
//   http://ssa-custhelp.ssa.gov/cgi-bin/ssa.cfg/php/enduser/std_adp.php?p_faqid=425

            Match match 
=
                (ignoreHypens 
?  ssnCaptureNoHypensRegex : ssnCaptureRegex)
                    .Match(objectToValidate);
            
if  (match.Success)
            {
                
string  area  =  match.Groups[ " area " ].Value;
                
string  group  =  match.Groups[ " group " ].Value;
                
string  serial  =  match.Groups[ " serial " ].Value;

                
if  (area  ==   " 666 "
                    
||   string .Compare(area,  " 772 " , StringComparison.Ordinal)  >   0 )
                {
                    LogValidationResult(
                        validationResults,
                        
" Invalid area " ,
                        currentTarget,
                        key);
                }
                
else   if  (area  ==   " 000 "   ||  group  ==   " 00 "   ||  serial  ==   " 0000 " )
                {
                    LogValidationResult(
                        validationResults,
                        
" SSN elements cannot be all '0' " ,
                        currentTarget,
                        key);
                }
            }
            
else
            {
                LogValidationResult(
                    validationResults,
                    
this .ignoreHypens
                        
?   " Must be 9 digits "
                        : 
" Must match the pattern '###-##-####' " ,
                    currentTarget,
                    key);
            }
        }
    }

 

  继承ValidatorAttribute ,实现一个自定义验证的attribute。

  

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />-->   public   class  SSNValidatorAttribute : ValidatorAttribute
    {
        
protected   override  Validator DoCreateValidator(Type targetType)
        {
            
return   new  SSNValidator( this .Tag);
        }
    }

 

  在属性上添加自定义验证的attribute  

 

<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />-->   [SSNValidator] 
  
public   string  SSN {  get set ; } 

 

  4、 通过配置实现自定义的验证

  首先还是要编写自定义的验证类和attribute,然后在配置中添加自定义自定义验证的时候,选择自定义验证类对应的程序集,进而选择程序集中的自定义验证类就可以了。

  5、验证方法的参数

  可以配合CallHandler来实现。

  

代码
<!--<br/ /><br/ />Code highlighting produced by Actipro CodeHighlighter (freeware)<br/ />http://www.CodeHighlighter.com/<br/ /><br/ />--> using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  Microsoft.Practices.EnterpriseLibrary.Validation;
using  Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

namespace  UnityAOP
{
    
public   interface  IOutput
    {
        
void  Output([StringLengthValidator( 5 10 )]  string  x);
    }
  
    [MyHandler ]
    
public   class  OutputImplement1 : IOutput
    {
        
#region  IOutput Members

        
public   void  Output([StringLengthValidator ( 5 , 10 )]  string  x)
        {
            
throw   new  Exception();
            Console.WriteLine(
" output : {0} " , x);
        }

        
#endregion
    }
}


using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  Microsoft.Practices.Unity;
using  Microsoft.Practices.Unity.InterceptionExtension;
using  Microsoft.Practices.EnterpriseLibrary.Validation;
using  Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

namespace  UnityAOP
{
    
public   class  MyHandler : ICallHandler
    {
        
#region  ICallHandler Members

        
public  IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn retvalue 
=   null ;
            Console.WriteLine(
" 方法名: {0}  " , input.MethodBase.Name);
            Console.WriteLine(
" 参数: " );

            
#region  验证参数
            Validator validator 
=  ParameterValidatorFactory.CreateValidator(input.Arguments.GetParameterInfo( 0 ));
            ValidationResults vrs
=  validator.Validate(input.Arguments[ 0 ]);

            
#endregion

            
for  (var i  =   0 ; i  <  input.Arguments.Count; i ++ )
            {
                Console.WriteLine(
" {0}: {1} " , input.Arguments.ParameterName(i), input.Arguments[i]);
            }
            Console.WriteLine(
" 执行 " );

            retvalue 
=  getNext()(input, getNext);

            
if  (retvalue.Exception  !=   null )
            {
                Console.WriteLine(
" 出现异常 " );
                
try  {

                }
                
catch  (Exception ex)
                {
                }

            }
            
else
            {
                Console.WriteLine(
" 正常结束 " );
            }
            
return  retvalue;
        }

        
public   int  Order
        {
            
get ;
            
set ;
        }

        
#endregion
    }
    
public   class  MyHandlerAttribute : HandlerAttribute
    {
        
public   override  ICallHandler CreateHandler(IUnityContainer container)
        {
            
return   new  MyHandler();
        }
    }
}


using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
using  Microsoft.Practices.ObjectBuilder2;
using  Microsoft.Practices.Unity;
using  Microsoft.Practices.Unity.InterceptionExtension;
using  Microsoft.Practices.EnterpriseLibrary.Common;
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using  Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using  Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjection;

namespace  UnityAOP.Main
{
    
class  Program
    {
        
static   void  Main( string [] args)
        {      
            var container1 
=   new  UnityContainer()
                .AddNewExtension
< Interception > ()
                .RegisterType
< IOutput, UnityAOP.OutputImplement1 > ();
            container1.Configure
< Interception > ()
                .SetDefaultInterceptorFor
< IOutput > ( new  InterfaceInterceptor());
            var op1 
=  container1.Resolve < IOutput > ();
            op1.Output(
" 1dfsdfssdfsdfsdfdf0 " );
            Console.ReadLine();
        }
    }
}

 

 

你可能感兴趣的:(PHP,Microsoft,cgi,LINQ)