1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Laos;
using System.Text.RegularExpressions;
namespace PostSharpTest
{
/// <summary>
/// Überprüft die Eingabe einer Eigenschaft mit einem Regulären Ausdruck.
/// </summary>
/// <remarks>Mit dem Named Property <see cref="math"/> kann eingestellt werden ob eine Exception
/// geworfen wernden soll, wenn keine Übereinstimmung vorliegt (match=false) oder die Ausführung
/// des Codes normal weitergeht (match=true)</remarks>
/// <example>
/// using System;
/// using System.Collections.Generic;
/// using System.Text;
///
/// namespace PostSharpTest
/// {
/// class Program
/// {
/// static void Main(string[] args)
/// {
/// try
/// {
/// MyInputClass myClass = new MyInputClass();
/// myClass.ValidatedProp = "20"; //gültige Eingabe
/// myClass.ValidatedProp = "e20"; //ungültige Eingabe - InvalidInputException
/// myClass.ValidatedProp = "20.0"; //ungültige Eingabe - InvalidInputException
/// }
/// catch (System.ArgumentException e)
/// {
/// Console.WriteLine(e.Message);
/// }
/// }
/// }
///
/// class MyInputClass
/// {
/// private string myField;
///
/// [RegexValidatorAspekt("[^0-9]", match = true)]
/// public string ValidatedProp
/// {
/// get { return myField; }
/// set { myField = value; }
/// }
/// }
/// }
/// </example>
/// <author>Rainer Schuster</author>
[Serializable]
[AttributeUsage(AttributeTargets.Property)]
public class RegexValidatorAspekt: OnMethodBoundaryAspect
{
private Regex pattern;
public bool match = true;
public RegexValidatorAspekt(string excludingRegEx)
{
pattern = new Regex(excludingRegEx, RegexOptions.Compiled);
}
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
object[] objArgs = eventArgs.GetArguments();
//Entweder kam eine NullReference,
//oder wir sind im getter des Property
if( objArgs != null)
{
//... und da gibt es nur einen Parameter.
string value = objArgs[0].ToString();
if( pattern.IsMatch( value ) == match)
{
string message = string.Format("Invalid value:{0} for pattern {1}", value, pattern.ToString());
throw new ArgumentException( message);
}
}
}
}
}
|