-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathAppSettingsValue.cs
98 lines (84 loc) · 2.35 KB
/
AppSettingsValue.cs
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
87
88
89
90
91
92
93
94
95
96
97
98
using PostSharp.Aspects;
using PostSharp.Extensibility;
using PostSharp.Reflection;
using PostSharp.Serialization;
using System;
using System.Configuration;
namespace PostSharp.Samples.Persistence
{
[PSerializable]
[LinesOfCodeAvoided(2)]
[MulticastAttributeUsage(TargetMemberAttributes = MulticastAttributes.Static)]
public sealed class AppSettingsValueAttribute : LocationInterceptionAspect
{
private bool isFetched;
private string settingName;
public AppSettingsValueAttribute()
{
}
public AppSettingsValueAttribute(string settingName)
{
this.settingName = settingName;
}
public override void CompileTimeInitialize(LocationInfo targetLocation, AspectInfo aspectInfo)
{
if (settingName == null)
{
settingName = targetLocation.Name;
}
}
public override bool CompileTimeValidate(LocationInfo locationInfo)
{
bool isReadOnly;
switch (locationInfo.LocationKind)
{
case LocationKind.Field:
isReadOnly = locationInfo.FieldInfo.IsInitOnly;
break;
case LocationKind.Property:
isReadOnly = locationInfo.PropertyInfo.SetMethod == null;
break;
default:
throw new Exception();
}
if (isReadOnly)
{
Message.Write(locationInfo, SeverityType.Error, "MY001",
"Cannot apply AppSettingsValueAttribute to a read-only field or property {0}.", locationInfo);
return false;
}
return true;
}
public override void OnGetValue(LocationInterceptionArgs args)
{
if (isFetched)
{
args.ProceedGetValue();
}
else
{
isFetched = true;
var stringValue = ConfigurationManager.AppSettings[settingName];
if (!string.IsNullOrEmpty(stringValue))
{
var value = Convert.ChangeType(stringValue, args.Location.LocationType);
args.SetNewValue(value);
args.Value = value;
}
else
{
args.ProceedGetValue();
}
}
}
public override void OnSetValue(LocationInterceptionArgs args)
{
if (isFetched)
{
throw new InvalidOperationException(
"The value of this field or property should not be changed after it has been read for the first time.");
}
base.OnSetValue(args);
}
}
}