forked from haoduotnt/aspnetwebstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicHttpApplicationState.cs
80 lines (71 loc) · 3.05 KB
/
DynamicHttpApplicationState.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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Dynamic;
using System.Web.WebPages.Resources;
namespace System.Web.WebPages
{
internal class DynamicHttpApplicationState : DynamicObject
{
private HttpApplicationStateBase _state;
public DynamicHttpApplicationState(HttpApplicationStateBase state)
{
_state = state;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = _state[binder.Name];
// We return true here because HttpApplicationState returns null if the key is not
// in the dictionary, so we simply pass on the returned value.
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_state[binder.Name] = value;
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes == null || indexes.Length != 1)
{
throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);
}
result = null;
string key = indexes[0] as string;
if (key != null)
{
result = _state[key];
}
else if (indexes[0] is int)
{
result = _state[(int)indexes[0]];
}
else
{
// HttpApplicationState only supports keys of type string and int when getting values, so any attempt
// to use other types will result in an error. We throw an exception here to explain to the user what is wrong.
// Returning false will instead cause a runtime binder exception which might be confusing to the user.
throw new ArgumentException(WebPageResources.DynamicHttpApplicationState_UseOnlyStringOrIntToGet);
}
return true;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes == null || indexes.Length != 1)
{
throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);
}
string key = indexes[0] as string;
if (key != null)
{
_state[key] = value;
return true;
}
else
{
// HttpApplicationState only supports keys of type string when setting values, so any attempt
// to use other types will result in an error. We throw an exception here to explain to the user what is wrong.
// Returning false will instead cause a runtime binder error which might be confusing to the user.
throw new ArgumentException(WebPageResources.DynamicHttpApplicationState_UseOnlyStringToSet);
}
}
}
}