-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathRegistryValueAttribute.cs
64 lines (56 loc) · 1.56 KB
/
RegistryValueAttribute.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
using Microsoft.Win32;
using PostSharp.Aspects;
using PostSharp.Extensibility;
using PostSharp.Reflection;
using PostSharp.Serialization;
using System;
namespace PostSharp.Samples.Persistence
{
[PSerializable]
[LinesOfCodeAvoided(5)]
[MulticastAttributeUsage(TargetMemberAttributes = MulticastAttributes.Static)]
public sealed class RegistryValueAttribute : LocationInterceptionAspect
{
private bool isFetched;
private string keyFullName;
private string keyName;
private string valueName;
public RegistryValueAttribute(string keyName)
{
this.keyName = keyName;
}
public override void CompileTimeInitialize(LocationInfo targetLocation, AspectInfo aspectInfo)
{
keyFullName = "HKEY_CURRENT_USER\\Software\\" + keyName;
valueName = targetLocation.Name;
}
public override void OnGetValue(LocationInterceptionArgs args)
{
if (isFetched)
{
args.ProceedGetValue();
}
else
{
isFetched = true;
var stringValue = Registry.GetValue(keyFullName, valueName, null) as string;
if (stringValue != null)
{
var value = Convert.ChangeType(stringValue, args.Location.LocationType);
args.SetNewValue(value);
args.Value = value;
}
else
{
args.ProceedGetValue();
}
}
}
public override void OnSetValue(LocationInterceptionArgs args)
{
args.ProceedSetValue();
Registry.SetValue(keyFullName, valueName, Convert.ToString(args.Value));
isFetched = true;
}
}
}