-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathUtilities.cs
366 lines (345 loc) · 11.9 KB
/
Utilities.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//-----------------------------------------------------------------------
// <copyright file="Utilities.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Contains utility methods used by the</summary>
//-----------------------------------------------------------------------
using System.Reflection;
using Csla.Reflection;
using System.ComponentModel;
using Csla.Properties;
using System.Diagnostics.CodeAnalysis;
namespace Csla
{
/// <summary>
/// Contains utility methods used by the
/// CSLA .NET framework.
/// </summary>
public static class Utilities
{
#region Replacements for VB runtime functionality
/// <summary>
/// Determines whether the specified
/// value can be converted to a valid number.
/// </summary>
public static bool IsNumeric(object value)
{
double dbl;
return double.TryParse(value.ToString(), System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.InvariantInfo, out dbl);
}
/// <summary>
/// Allows late bound invocation of
/// properties and methods.
/// </summary>
/// <param name="target">Object implementing the property or method.</param>
/// <param name="methodName">Name of the property or method.</param>
/// <param name="callType">Specifies how to invoke the property or method.</param>
/// <param name="args">List of arguments to pass to the method.</param>
/// <returns>The result of the property or method invocation.</returns>
public static object CallByName(
object target, string methodName, CallType callType,
params object[] args)
{
switch (callType)
{
case CallType.Get:
{
return MethodCaller.CallPropertyGetter(target, methodName);
}
case CallType.Let:
case CallType.Set:
{
MethodCaller.CallPropertySetter(target, methodName, args[0]);
return null;
}
case CallType.Method:
{
return MethodCaller.CallMethod(target, methodName, args);
}
}
return null;
}
#endregion
/// <summary>
/// Returns a property's type, dealing with
/// Nullable(Of T) if necessary.
/// </summary>
/// <param name="propertyType">Type of the
/// property as returned by reflection.</param>
#if NET8_0_OR_GREATER
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
public static Type GetPropertyType(
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
Type propertyType)
{
Type type = propertyType;
if (type.IsGenericType &&
(type.GetGenericTypeDefinition() == typeof(Nullable<>)))
return Nullable.GetUnderlyingType(type);
return type;
}
/// <summary>
/// Returns the type of child object
/// contained in a collection or list.
/// </summary>
/// <param name="listType">Type of the list.</param>
public static Type GetChildItemType(
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
Type listType)
{
Type result = null;
if (listType.IsArray)
result = listType.GetElementType();
else
{
var indexer =
(DefaultMemberAttribute)Attribute.GetCustomAttribute(
listType, typeof(DefaultMemberAttribute));
if (indexer != null)
{
foreach (PropertyInfo prop in listType.GetProperties(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.FlattenHierarchy))
{
if (prop.Name == indexer.MemberName)
result = GetPropertyType(prop.PropertyType);
}
}
if (result == null)
{
result = listType.GetMethod("get_Item")?.ReturnType;
}
}
return result;
}
#region CoerceValue
/// <summary>
/// Attempts to coerce a value of one type into
/// a value of a different type.
/// </summary>
/// <param name="desiredType">
/// Type to which the value should be coerced.
/// </param>
/// <param name="valueType">
/// Original type of the value.
/// </param>
/// <param name="oldValue">
/// The previous value (if any) being replaced by
/// the new coerced value.
/// </param>
/// <param name="value">
/// The value to coerce.
/// </param>
/// <remarks>
/// <para>
/// If the desired type is a primitive type or Decimal,
/// empty string and null values will result in a 0
/// or equivalent.
/// </para>
/// <para>
/// If the desired type is a Nullable type, empty string
/// and null values will result in a null result.
/// </para>
/// <para>
/// If the desired type is an enum the value's ToString()
/// result is parsed to convert into the enum value.
/// </para>
/// </remarks>
public static object CoerceValue(
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
Type desiredType,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
Type valueType, object oldValue, object value)
{
if (desiredType.IsAssignableFrom(valueType))
{
// types match, just return value
return value;
}
else
{
if (desiredType.IsGenericType)
{
if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>))
if (value == null)
return null;
else if (valueType.Equals(typeof(string)) && Convert.ToString(value) == string.Empty)
return null;
}
desiredType = GetPropertyType(desiredType);
}
if (desiredType.IsEnum)
{
if (value is byte? && ((byte?) value).HasValue)
return Enum.Parse(desiredType, ((byte?) value).Value.ToString());
if (value is short? && ((short?) value).HasValue)
return Enum.Parse(desiredType, ((short?) value).Value.ToString());
if (value is int? && ((int?) value).HasValue)
return Enum.Parse(desiredType, ((int?) value).Value.ToString());
if (value is long? && ((long?) value).HasValue)
return Enum.Parse(desiredType, ((long?) value).Value.ToString());
}
if (desiredType.IsEnum &&
(valueType.Equals(typeof(string)) || Enum.GetUnderlyingType(desiredType).Equals(valueType)))
return Enum.Parse(desiredType, value.ToString());
if (desiredType.Equals(typeof(SmartDate)) && oldValue != null)
{
if (value == null)
value = string.Empty;
var tmp = (SmartDate)oldValue;
if (valueType.Equals(typeof(DateTime)))
tmp.Date = (DateTime)value;
else
tmp.Text = value.ToString();
return tmp;
}
if ((desiredType.IsPrimitive || desiredType.Equals(typeof(decimal))) &&
valueType.Equals(typeof(string)) && string.IsNullOrEmpty((string)value))
value = 0;
try
{
if (desiredType.Equals(typeof(string)) && value != null)
{
return value.ToString();
}
else
return Convert.ChangeType(value, desiredType);
}
catch
{
TypeConverter cnv = TypeDescriptor.GetConverter(desiredType);
TypeConverter cnv1 = TypeDescriptor.GetConverter(valueType);
if (cnv != null && cnv.CanConvertFrom(valueType))
return cnv.ConvertFrom(value);
else if (cnv1 != null && cnv1.CanConvertTo(desiredType))
return cnv1.ConvertTo(value, desiredType);
else
throw;
}
}
/// <summary>
/// Attempts to coerce a value of one type into
/// a value of a different type.
/// </summary>
/// <typeparam name="D">
/// Type to which the value should be coerced.
/// </typeparam>
/// <param name="valueType">
/// Original type of the value.
/// </param>
/// <param name="oldValue">
/// The previous value (if any) being replaced by
/// the new coerced value.
/// </param>
/// <param name="value">
/// The value to coerce.
/// </param>
/// <remarks>
/// <para>
/// If the desired type is a primitive type or Decimal,
/// empty string and null values will result in a 0
/// or equivalent.
/// </para>
/// <para>
/// If the desired type is a Nullable type, empty string
/// and null values will result in a null result.
/// </para>
/// <para>
/// If the desired type is an enum the value's ToString()
/// result is parsed to convert into the enum value.
/// </para>
/// </remarks>
public static D CoerceValue<
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
D>(
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
Type valueType, object oldValue, object value)
{
return (D)(CoerceValue(typeof(D), valueType, oldValue, value));
}
#endregion
internal static void ThrowIfAsyncMethodOnSyncClient(ApplicationContext applicationContext, bool isSync, System.Reflection.MethodInfo method)
{
if (isSync
&& applicationContext.ExecutionLocation != ApplicationContext.ExecutionLocations.Server
&& MethodCaller.IsAsyncMethod(method))
{
throw new NotSupportedException(string.Format(Resources.AsyncMethodOnSyncClientNotAllowed, method.Name));
}
}
/// <summary>
/// Throws an exception if a synchronous data portal call is trying to invoke an asynchronous method on the client.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
/// <param name="obj">Object containing method.</param>
/// <param name="methodName">Name of the method.</param>
internal static void ThrowIfAsyncMethodOnSyncClient(ApplicationContext applicationContext, bool isSync, object obj, string methodName)
{
if (isSync
&& applicationContext.ExecutionLocation != ApplicationContext.ExecutionLocations.Server
&& MethodCaller.IsAsyncMethod(obj, methodName))
{
throw new NotSupportedException(string.Format(Resources.AsyncMethodOnSyncClientNotAllowed, methodName));
}
}
/// <summary>
/// Throws an exception if a synchronous data portal call is trying to invoke an asynchronous method on the client.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
/// <param name="obj">Object containing method.</param>
/// <param name="methodName">Name of the method.</param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
internal static void ThrowIfAsyncMethodOnSyncClient(ApplicationContext applicationContext, bool isSync, object obj, string methodName, params object[] parameters)
{
if (isSync
&& applicationContext.ExecutionLocation != ApplicationContext.ExecutionLocations.Server
&& MethodCaller.IsAsyncMethod(obj, methodName, parameters))
{
throw new NotSupportedException(string.Format(Resources.AsyncMethodOnSyncClientNotAllowed, methodName));
}
}
}
/// <summary>
/// Valid options for calling a property or method
/// via the <see cref="Csla.Utilities.CallByName"/> method.
/// </summary>
public enum CallType
{
/// <summary>
/// Gets a value from a property.
/// </summary>
Get,
/// <summary>
/// Sets a value into a property.
/// </summary>
Let,
/// <summary>
/// Invokes a method.
/// </summary>
Method,
/// <summary>
/// Sets a value into a property.
/// </summary>
Set
}
}