1 // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
3 using System.Collections.Generic;
5 using System.Linq.Expressions;
6 using System.Reflection;
7 using System.Runtime.Serialization.Json;
12 /// This class provides dynamic behavior support for the JsonValue types.
14 internal class JsonValueDynamicMetaObject : DynamicMetaObject
16 private static readonly MethodInfo _getValueByIndexMethodInfo = typeof(JsonValue).GetMethod("GetValue", new Type[] { typeof(int) });
17 private static readonly MethodInfo _getValueByKeyMethodInfo = typeof(JsonValue).GetMethod("GetValue", new Type[] { typeof(string) });
18 private static readonly MethodInfo _setValueByIndexMethodInfo = typeof(JsonValue).GetMethod("SetValue", new Type[] { typeof(int), typeof(object) });
19 private static readonly MethodInfo _setValueByKeyMethodInfo = typeof(JsonValue).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) });
20 private static readonly MethodInfo _castValueMethodInfo = typeof(JsonValue).GetMethod("CastValue", new Type[] { typeof(JsonValue) });
21 private static readonly MethodInfo _changeTypeMethodInfo = typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) });
24 /// Class constructor.
26 /// <param name="parameter">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
27 /// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param>
28 internal JsonValueDynamicMetaObject(Expression parameter, JsonValue value)
29 : base(parameter, BindingRestrictions.Empty, value)
34 /// Gets the default binding restrictions for this type.
36 private BindingRestrictions DefaultRestrictions
38 get { return BindingRestrictions.GetTypeRestriction(Expression, LimitType); }
42 /// Implements dynamic cast for JsonValue types.
44 /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
45 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
46 public override DynamicMetaObject BindConvert(ConvertBinder binder)
50 throw new ArgumentNullException("binder");
53 Expression expression = Expression;
55 bool implicitCastSupported =
56 binder.Type.IsAssignableFrom(LimitType) ||
57 binder.Type == typeof(IEnumerable<KeyValuePair<string, JsonValue>>) ||
58 binder.Type == typeof(IDynamicMetaObjectProvider) ||
59 binder.Type == typeof(object);
61 if (!implicitCastSupported)
63 if (JsonValue.IsSupportedExplicitCastType(binder.Type))
65 Expression instance = Expression.Convert(Expression, LimitType);
66 expression = Expression.Call(_castValueMethodInfo.MakeGenericMethod(binder.Type), new Expression[] { instance });
70 string exceptionMessage = RS.Format(Properties.Resources.CannotCastJsonValue, LimitType.FullName, binder.Type.FullName);
71 expression = Expression.Throw(Expression.Constant(new InvalidCastException(exceptionMessage)), typeof(object));
75 expression = Expression.Convert(expression, binder.Type);
77 return new DynamicMetaObject(expression, DefaultRestrictions);
81 /// Implements setter for dynamic indexer by index (JsonArray)
83 /// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
84 /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param>
85 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
86 public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
90 throw new ArgumentNullException("binder");
95 throw new ArgumentNullException("indexes");
98 Expression indexExpression;
99 if (!JsonValueDynamicMetaObject.TryGetIndexExpression(indexes, out indexExpression))
101 return new DynamicMetaObject(indexExpression, DefaultRestrictions);
104 MethodInfo methodInfo = indexExpression.Type == typeof(string) ? _getValueByKeyMethodInfo : _getValueByIndexMethodInfo;
105 Expression[] args = new Expression[] { indexExpression };
107 return GetMethodMetaObject(methodInfo, args);
111 /// Implements getter for dynamic indexer by index (JsonArray).
113 /// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
114 /// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param>
115 /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
116 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
117 public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
121 throw new ArgumentNullException("binder");
126 throw new ArgumentNullException("indexes");
131 throw new ArgumentNullException("value");
134 Expression indexExpression;
135 if (!JsonValueDynamicMetaObject.TryGetIndexExpression(indexes, out indexExpression))
137 return new DynamicMetaObject(indexExpression, DefaultRestrictions);
140 MethodInfo methodInfo = indexExpression.Type == typeof(string) ? _setValueByKeyMethodInfo : _setValueByIndexMethodInfo;
141 Expression[] args = new Expression[] { indexExpression, Expression.Convert(value.Expression, typeof(object)) };
143 return GetMethodMetaObject(methodInfo, args);
147 /// Implements getter for dynamic indexer by key (JsonObject).
149 /// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
150 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
151 public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
155 throw new ArgumentNullException("binder");
158 PropertyInfo propInfo = LimitType.GetProperty(binder.Name, BindingFlags.Instance | BindingFlags.Public);
160 if (propInfo != null)
162 return base.BindGetMember(binder);
165 Expression[] args = new Expression[] { Expression.Constant(binder.Name) };
167 return GetMethodMetaObject(_getValueByKeyMethodInfo, args);
171 /// Implements setter for dynamic indexer by key (JsonObject).
173 /// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
174 /// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
175 /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
176 public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
180 throw new ArgumentNullException("binder");
185 throw new ArgumentNullException("value");
188 Expression[] args = new Expression[] { Expression.Constant(binder.Name), Expression.Convert(value.Expression, typeof(object)) };
190 return GetMethodMetaObject(_setValueByKeyMethodInfo, args);
194 /// Performs the binding of the dynamic invoke member operation.
195 /// Implemented to support extension methods defined in <see cref="JsonValueExtensions"/> type.
197 /// <param name="binder">An instance of the InvokeMemberBinder that represents the details of the dynamic operation.</param>
198 /// <param name="args">An array of DynamicMetaObject instances - arguments to the invoke member operation.</param>
199 /// <returns>The new DynamicMetaObject representing the result of the binding.</returns>
200 public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
204 throw new ArgumentNullException("binder");
209 throw new ArgumentNullException("args");
212 List<Type> argTypeList = new List<Type>();
214 for (int idx = 0; idx < args.Length; idx++)
216 argTypeList.Add(args[idx].LimitType);
219 MethodInfo methodInfo = Value.GetType().GetMethod(binder.Name, argTypeList.ToArray());
221 if (methodInfo == null)
223 argTypeList.Insert(0, typeof(JsonValue));
225 Type[] argTypes = argTypeList.ToArray();
227 methodInfo = JsonValueDynamicMetaObject.GetExtensionMethod(typeof(JsonValueExtensions), binder.Name, argTypes);
229 if (methodInfo != null)
231 Expression thisInstance = Expression.Convert(Expression, LimitType);
232 Expression[] argsExpression = new Expression[argTypes.Length];
234 argsExpression[0] = thisInstance;
235 for (int i = 0; i < args.Length; i++)
237 argsExpression[i + 1] = args[i].Expression;
240 Expression callExpression = Expression.Call(methodInfo, argsExpression);
242 if (methodInfo.ReturnType == typeof(void))
244 callExpression = Expression.Block(callExpression, Expression.Default(binder.ReturnType));
248 callExpression = Expression.Convert(Expression.Call(methodInfo, argsExpression), binder.ReturnType);
251 return new DynamicMetaObject(callExpression, DefaultRestrictions);
255 return base.BindInvokeMember(binder, args);
259 /// Returns the enumeration of all dynamic member names.
261 /// <returns>An <see cref="IEnumerable{T}"/> of string reprenseting the dynamic member names.</returns>
262 public override IEnumerable<string> GetDynamicMemberNames()
264 JsonValue jsonValue = Value as JsonValue;
266 if (jsonValue != null)
268 List<string> names = new List<string>();
270 foreach (KeyValuePair<string, JsonValue> pair in jsonValue)
278 return base.GetDynamicMemberNames();
282 /// Gets a <see cref="MethodInfo"/> instance for the specified method name in the specified type.
284 /// <param name="extensionProviderType">The extension provider type.</param>
285 /// <param name="methodName">The name of the method to get the info for.</param>
286 /// <param name="argTypes">The types of the method arguments.</param>
287 /// <returns>A <see cref="MethodInfo"/>instance or null if the method cannot be resolved.</returns>
288 private static MethodInfo GetExtensionMethod(Type extensionProviderType, string methodName, Type[] argTypes)
290 MethodInfo methodInfo = null;
291 MethodInfo[] methods = extensionProviderType.GetMethods();
293 foreach (MethodInfo info in methods)
295 if (info.Name == methodName)
299 if (!info.IsGenericMethodDefinition)
301 bool paramsMatch = true;
302 ParameterInfo[] args = methodInfo.GetParameters();
304 if (args.Length == argTypes.Length)
306 for (int idx = 0; idx < args.Length; idx++)
308 if (!args[idx].ParameterType.IsAssignableFrom(argTypes[idx]))
328 /// Attempts to get an expression for an index parameter.
330 /// <param name="indexes">The operation indexes parameter.</param>
331 /// <param name="expression">A <see cref="Expression"/> to be initialized to the index expression if the operation is successful, otherwise an error expression.</param>
332 /// <returns>true the operation is successful, false otherwise.</returns>
333 private static bool TryGetIndexExpression(DynamicMetaObject[] indexes, out Expression expression)
335 if (indexes.Length == 1 && indexes[0] != null && indexes[0].Value != null)
337 DynamicMetaObject index = indexes[0];
338 Type indexType = indexes[0].Value.GetType();
340 switch (Type.GetTypeCode(indexType))
344 case TypeCode.UInt16:
347 Expression argExp = Expression.Convert(index.Expression, typeof(object));
348 Expression typeExp = Expression.Constant(typeof(int));
349 expression = Expression.Convert(Expression.Call(_changeTypeMethodInfo, new Expression[] { argExp, typeExp }), typeof(int));
353 case TypeCode.String:
354 expression = index.Expression;
358 expression = Expression.Throw(Expression.Constant(new ArgumentException(RS.Format(Properties.Resources.InvalidIndexType, indexType))), typeof(object));
362 expression = Expression.Throw(Expression.Constant(new ArgumentException(Properties.Resources.NonSingleNonNullIndexNotSupported)), typeof(object));
367 /// Gets a <see cref="DynamicMetaObject"/> for a method call.
369 /// <param name="methodInfo">Info for the method to be performed.</param>
370 /// <param name="args">expression array representing the method arguments</param>
371 /// <returns>A meta object for the method call.</returns>
372 private DynamicMetaObject GetMethodMetaObject(MethodInfo methodInfo, Expression[] args)
374 Expression instance = Expression.Convert(Expression, LimitType);
375 Expression methodCall = Expression.Call(instance, methodInfo, args);
376 BindingRestrictions restrictions = DefaultRestrictions;
378 DynamicMetaObject metaObj = new DynamicMetaObject(methodCall, restrictions);