Beispiel #1
0
 /// <summary>
 ///     Tries to normalize variable by searching InstancePool and converting of variable to the desired <see cref="Type" />
 /// </summary>
 /// <param name="variable">The variable to normalize</param>
 /// <param name="normalizeType">The <see cref="Type" /> to convert variable to</param>
 /// <param name="throwOnException">
 ///     A boolean value indicating if the method should throw an exception or just returns
 ///     <see langword="null" /> in case of errors
 /// </param>
 /// <returns>
 ///     New <see langword="object" /> created or casted from the variable in the desired <see cref="Type" />, or
 ///     <see langword="null" />
 /// </returns>
 /// <exception cref="InvalidCastException">
 ///     The passed variable can not be converted to the desired <see cref="Type" />
 /// </exception>
 public static object NormalizeVariable(object variable, Type normalizeType, bool throwOnException)
 {
     if (variable != null)
     {
         try
         {
             var javaScriptClass = variable as JObject;
             if (javaScriptClass != null)
             {
                 var instanceIdProperty =
                     javaScriptClass.Property("__instanceId")?.Value?.ToString(Formatting.None).Trim('"', ' ');
                 if (!string.IsNullOrWhiteSpace(instanceIdProperty))
                 {
                     var instance = GlobalPool.GetInstance(instanceIdProperty);
                     if (instance != null && (normalizeType == null || normalizeType.IsInstanceOfType(instance)))
                     {
                         return(instance);
                     }
                 }
                 return(normalizeType == null
                     ? variable
                     : javaScriptClass.ToObject(normalizeType));
             }
             return(normalizeType == null || normalizeType.IsInstanceOfType(variable)
                 ? variable
                 : Convert.ChangeType(variable, normalizeType, null));
         }
         catch (InvalidCastException)
         {
             if (throwOnException)
             {
                 throw;
             }
         }
         catch (ArgumentException e)
         {
             if (throwOnException)
             {
                 throw new InvalidCastException(e.Message, e);
             }
         }
     }
     return(normalizeType != null && normalizeType.IsValueType ? Activator.CreateInstance(normalizeType) : null);
 }
Beispiel #2
0
 /// <summary>
 ///     Returns an instance of the generic type from global pool using instance id
 /// </summary>
 /// <param name="instanceId">The identification string of the instance</param>
 /// <returns>The registered instance</returns>
 public static T GetInstance(string instanceId)
 {
     return(GlobalPool.GetInstance <T>(instanceId));
 }