Пример #1
0
        //////////////////////////////

        public static String ToString(Object Object)
        {
            Type objectType = Object != null?Object.GetType() : null;

            if (Object == null)
            {
                return("NULL");
            }
            else if (MyTypeHelper.IsDateTime(objectType))
            {
                return("todatetime('" + UniConvert.ToUniString(Object) + "')");
            }
            else if (objectType == typeof(InternalDateTime))
            {
                DateTime?dateTime = objectType == null ?
                                    null :
                                    (DateTime?)new DateTime(((InternalDateTime)Object).Ticks);

                return("todatetime('" + UniConvert.ToUniString(dateTime) + "')");
            }
            else if (MyTypeHelper.IsNumeric(objectType))
            {
                return(UniConvert.ToUniString(Object));
            }
            else if (MyTypeHelper.IsString(objectType))
            {
                return("'" + Object.ToString().Replace("'", "\\'") + "'");
            }
            else
            {
                throw new NotSupportedException("Objects of type " + objectType.Name + " are not supported in expressions");
            }
        }
Пример #2
0
        public override void Commit()
        {
            base.Commit();


            if (this.Parent == null)
            {
                return;
            }

            string lastKey = null;

            foreach (S4JToken child in this.Children)
            {
                Object val = child.ToJson().ParseJsonOrText();

                if (child.IsObjectKey)
                {
                    lastKey            = null;
                    lastKey            = UniConvert.ToString(val);
                    this.Tags[lastKey] = null;
                }
                else if (child.IsObjectValue)
                {
                    this.Tags[lastKey] = UniConvert.ToString(val);
                }
                else
                {
                    lastKey = null;
                    this.Tags[UniConvert.ToString(val)] = null;
                }
            }
        }
Пример #3
0
        public override void Commit()
        {
            base.Commit();

            S4JTokenRoot root = this;

            // ustalenie root name
            if (root.Children.Count > 1 && (root.Children.FirstOrDefault() is S4JTokenTextValue nameToken))
            {
                // dodanie tagów do root'a
                foreach (var tagKV in nameToken.Tags)
                {
                    this.Tags[tagKV.Key] = tagKV.Value;
                }

                root.Name = UniConvert.ToString(nameToken.ToJson().ParseJsonOrText());
                root.RemoveChild(nameToken, null);
            }

            // ustalenie parameters
            if ((root.Children.FirstOrDefault() is S4JTokenParameters parametersToken))
            {
                // dodanie tagów do root'a
                foreach (var tagKV in parametersToken.Tags)
                {
                    this.Tags[tagKV.Key] = tagKV.Value;
                }

                root.ParametersDefinitions = new Dictionary <string, S4JFieldDescription>();
                root.Parameters            = new Dictionary <string, object>();

                string lastKey = null;
                foreach (S4JToken child in parametersToken.Children)
                {
                    Object val = child.ToJson().ParseJsonOrText();

                    if (child.IsObjectSingleKey)
                    {
                        lastKey = null;
                        root.ParametersDefinitions[UniConvert.ToString(val)] = null;
                        root.Parameters[UniConvert.ToString(val)]            = null;
                    }
                    else if (child.IsObjectKey)
                    {
                        lastKey = null;
                        lastKey = UniConvert.ToString(val);
                        root.ParametersDefinitions[lastKey] = null;
                        root.Parameters[lastKey]            = null;
                    }
                    else if (child.IsObjectValue)
                    {
                        root.ParametersDefinitions[lastKey] = S4JFieldDescription.Parse(lastKey, UniConvert.ToString(val));
                        root.Parameters[lastKey]            = null;
                    }
                }
                root.RemoveChild(parametersToken, null);
            }
        }
Пример #4
0
        ////////////////////////////////////////////////////////////////////////

        public static Object Execute(DynContext EvaluateContext, Object obj, IList <Object> Parameters)
        {
            Boolean isValueSet = false;

            String propertyPath = UniConvert.ToUniString(Parameters != null && Parameters.Count > 0 ? Parameters[0] : null);
            Object value        = (Parameters != null && Parameters.Count > 1 ? Parameters[1] : null);

            if (obj is IDictionaryWithGetter)
            {
                IDictionaryWithGetter dict = obj as IDictionaryWithGetter;
                if (dict.CanSetValueToDictionary(propertyPath))
                {
                    dict[propertyPath] = value;
                    isValueSet         = true;
                }
            }

            else if (obj is IDictionary)
            {
                IDictionary dict = obj as IDictionary;
                dict[propertyPath] = value;
                isValueSet         = true;
            }

            else if (obj is IDictionary <string, object> )
            {
                IDictionary <string, object> dict = obj as IDictionary <string, object>;
                dict[propertyPath] = value;
                isValueSet         = true;
            }

            if (obj is DynLanObject)
            {
#if CASE_INSENSITIVE
                propertyPath = propertyPath.ToUpper();
#endif
                DynLanObject DynLanObj = obj as DynLanObject;
                DynLanObj[propertyPath] = value;
                return(null);
            }

            if (!isValueSet)
            {
                isValueSet = RefSensitiveHelper.I.SetValue(obj, propertyPath, value);
            }

            //if (!isValueSet)
            //    isValueSet = RefUnsensitiveHelper.I.SetValue(obj, propertyPath, value);

            if (isValueSet)
            {
                return(value);
            }

            return(null);
        }
Пример #5
0
        private static IEnumerable <DbDataColumnValue> GetItemValuesForDbFields(Object Item, DbDataColumns DbFields)
        {
            if (Item is IDictionary <string, object> dictKeyValue)
            {
                foreach (var val in dictKeyValue)
                {
                    DbDataColumn dataColumn = null;
                    DbFields.TryGetValue(val.Key, out dataColumn);
                    if (dataColumn == null)
                    {
                        continue;
                    }

                    yield return(new DbDataColumnValue()
                    {
                        Name = dataColumn.Name,
                        Value = val.Value
                    });
                }
            }
            else if (Item is IDictionary dict)
            {
                foreach (var key in dict.Keys)
                {
                    DbDataColumn dataColumn = null;
                    DbFields.TryGetValue(UniConvert.ToString(key), out dataColumn);
                    if (dataColumn == null)
                    {
                        continue;
                    }

                    yield return(new DbDataColumnValue()
                    {
                        Name = dataColumn.Name,
                        Value = dict[key]
                    });
                }
            }
            else
            {
                foreach (DbDataColumn databaseColumn in DbFields.Values)
                {
                    PropertyInfo itemProperty = ReflectionHelper.GetProperty(Item, databaseColumn.Name);
                    if (itemProperty != null)
                    {
                        yield return(new DbDataColumnValue()
                        {
                            Name = databaseColumn.Name,
                            Value = itemProperty.GetValue(Item, null)
                        });
                    }
                }
            }
        }
Пример #6
0
        public static ExpressionValue GetValueFromText(IList <Char> chars)
        {
            if (chars == null)
            {
                return(null);
            }

            if (StringHelper.IsString(chars, '\''))
            {
                var name = StringHelper.ToString2(chars);
                return(new ExpressionValue(
                           name.Substring(1, name.Length - 2).Replace("\\'", "'")));
            }
            else if (StringHelper.IsInteger(chars))
            {
                return(new ExpressionValue(
                           UniConvert.ParseUniInt64(StringHelper.ToString2(StringHelper.Replace2(chars, ',', '.')))));
            }
            else if (StringHelper.IsNumber(chars))
            {
                return(new ExpressionValue(
                           UniConvert.ParseUniDecimal(StringHelper.ToString2(StringHelper.Replace2(chars, ',', '.')))));
            }
            else if (StringHelper.SequenceEqualInsensitive(chars, OperatorTypeHelper.symbol_null))
            {
                return(new ExpressionValue(null));
            }
            else if (StringHelper.SequenceEqualInsensitive(chars, OperatorTypeHelper.symbol_false))
            {
                return(new ExpressionValue(false));
            }
            else if (StringHelper.SequenceEqualInsensitive(chars, OperatorTypeHelper.symbol_true))
            {
                return(new ExpressionValue(true));
            }
            else if (StringHelper.SequenceEqual(chars, OperatorTypeHelper.symbol_new_line))
            {
                return(new ExpressionValue("\r\n"));
            }
            else if (StringHelper.SequenceEqualInsensitive(chars, OperatorTypeHelper.symbol_undefined))
            {
                return(new ExpressionValue(new Undefined()));
            }
            return(null);
        }
Пример #7
0
        public static String Join(
            this IEnumerable <Object> Items,
            String Separator = ",")
        {
            StringBuilder str = new StringBuilder();

            if (Items != null)
            {
                foreach (Object item in Items)
                {
                    if (str.Length > 0)
                    {
                        str.Append(Separator);
                    }
                    str.Append(UniConvert.ToString(item));
                }
            }
            return(str.ToString());
        }
Пример #8
0
        ////////////////////////////////////////////////////////////////////////

        public static DynMethodResult Execute(DynContext EvaluateContext, IList <Object> Parameters)
        {
            String variableName = UniConvert.ToUniString(Parameters != null && Parameters.Count > 0 ? Parameters[0] : null);
            Object value        = Parameters != null && Parameters.Count > 1 ? Parameters[1] : null;

            if (EvaluateContext != null)
            {
                Boolean isValueSet = EvaluateContext.SetValue(
                    EvaluateContext,
                    variableName,
                    value);

                if (isValueSet)
                {
                    return(new DynMethodResult(value));
                }
            }
            return(null);
        }
Пример #9
0
 public static DateTime?ToDatetime(Object val)
 {
     if (val != null)
     {
         if (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?))
         {
             return(new DateTime().AddSeconds(((TimeSpan)val).TotalSeconds));
         }
         else if (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?))
         {
             return((DateTime)val);
         }
         else if (val.GetType() == typeof(String))
         {
             return(UniConvert.ToDateTime((String)val));
         }
     }
     return(null);
 }
Пример #10
0
        ////////////////////////////////////////////////////////////////////////

        public static Object Execute(PainContext EvaluateContext, Object obj, IList <Object> Parameters)
        {
            Boolean isValueSet = false;

            String propertyPath = UniConvert.ToUniString(Parameters != null && Parameters.Count > 0 ? Parameters[0] : null);
            Object value        = (Parameters != null && Parameters.Count > 1 ? Parameters[1] : null);

            if (obj is IDictionary)
            {
                IDictionary dict = obj as IDictionary;
                dict[propertyPath] = value;
                isValueSet         = true;
            }

            if (obj is PainObject)
            {
                propertyPath = propertyPath.ToUpper();
                PainObject painObj = obj as PainObject;
                painObj[propertyPath] = value;
                return(null);
            }

            if (!isValueSet)
            {
                isValueSet = RefSensitiveHelper.I.SetValue(obj, propertyPath, value);
            }

            if (!isValueSet)
            {
                isValueSet = RefUnsensitiveHelper.I.SetValue(obj, propertyPath, value);
            }

            if (isValueSet)
            {
                return(value);
            }

            return(null);
        }
Пример #11
0
        ////////////////////////////////////////////////////////////////////////

        public static Object Execute(PainContext EvaluateContext, Object obj, IList <Object> Parameters)
        {
            Object Collection = obj;
            Object value      = Parameters != null && Parameters.Count > 0 ? Parameters[0] : null;
            Object Key        = Parameters != null && Parameters.Count > 1 ? Parameters[1] : null;

            if (Collection == null)
            {
                return(null);
            }

            if (Collection is PainObject)
            {
                PainObject painObj = Collection as PainObject;

                String finalKey = (String)(Key.GetType() == typeof(String) ? Key :
                                           Convert.ChangeType(Key, typeof(String), System.Globalization.CultureInfo.InvariantCulture));

                Object finValue = value == null ? null : (value.GetType() == typeof(Object) ? value :
                                                          Convert.ChangeType(value, typeof(Object), System.Globalization.CultureInfo.InvariantCulture));

                painObj[finalKey] = finValue;

                return(value);
            }

            if (Collection is IDictionary)
            {
                IDictionary dict = (IDictionary)Collection;

                Type[] arguments = dict.GetType().GetGenericArguments();
                Type   keyType   = arguments[0];
                Type   valueType = arguments[1];

                Object finalKey = Key.GetType() == keyType ? Key :
                                  Convert.ChangeType(Key, keyType, System.Globalization.CultureInfo.InvariantCulture);

                Object finValue = value == null ? null : (value.GetType() == valueType ? value :
                                                          Convert.ChangeType(value, valueType, System.Globalization.CultureInfo.InvariantCulture));

                lock (dict)
                {
                    dict.Remove(finalKey);
                    dict.Add(finalKey, finValue);
                }

                return(value);
            }

            if (Collection is IList)
            {
                Int32?index = UniConvert.ToInt32N(Key);
                if (index == null || index < 0)
                {
                    return(null);
                }

                IList list = (IList)Collection;
                if (index >= list.Count)
                {
                    return(null);
                }

                Type listType = MyTypeHelper.GetListType(list);

                Object finValue = value == null ? null : (value.GetType() == listType ? value :
                                                          Convert.ChangeType(value, listType, System.Globalization.CultureInfo.InvariantCulture));

                list[index.Value] = finValue;

                return(value);
            }

            return(null);
        }
Пример #12
0
        ////////////////////////////////////////////////////////////////////////

        public static Object Execute(DynContext EvaluateContext, Object obj, IList <Object> Parameters)
        {
            Object Collection = obj;

#if !NET20
            Object Key = Parameters == null ? null : Parameters.FirstOrDefault();
#else
            Object Key = Parameters == null ? null : Linq2.FirstOrDefault(Parameters);
#endif
            if (Collection == null)
            {
                return(null);
            }

            if (Collection is String)
            {
                Int32?index = UniConvert.ToInt32N(Key);
                if (index == null || index < 0)
                {
                    return(null);
                }

                String str = (String)Collection;
                if (index >= str.Length)
                {
                    return(null);
                }

                return(str[index.Value]);
            }

            if (Collection is DynLanObject)
            {
                DynLanObject DynLanObj = Collection as DynLanObject;

                if (DynLanObj.TotalCount == 0)
                {
                    return(null);
                }

                /*IDictionary<String, Object> dict = ((DynLanObject)Collection).Values;
                 * if (dict.Count == 0)
                 *  return null;*/

                String finalKey = ((String)(Key.GetType() == typeof(String) ? Key :
                                            Convert.ChangeType(Key, typeof(String), System.Globalization.CultureInfo.InvariantCulture)));

                return(DynLanObj[finalKey]);
            }

            if (Collection is IDictionaryWithGetter)
            {
                IDictionaryWithGetter dict = Collection as IDictionaryWithGetter;
                if (dict.CanGetValueFromDictionary(Key))
                {
                    return(dict.GetValueFromDictionary(Key));
                }
            }
            else if (Collection is IDictionary)
            {
                IDictionary dict = (IDictionary)Collection;
                if (dict.Count == 0)
                {
                    return(null);
                }

                Type[] arguments = dict.GetType().GetGenericArguments();
                Type   keyType   = arguments[0];

                Object finalKey = Key.GetType() == keyType ? Key :
                                  Convert.ChangeType(Key, keyType, System.Globalization.CultureInfo.InvariantCulture);

                return(dict[finalKey]);
            }
            else if (Collection is IDictionary <string, object> )
            {
                IDictionary <string, object> dict = (IDictionary <string, object>)Collection;
                if (dict.Count == 0)
                {
                    return(null);
                }
                return(dict[UniConvert.ToString(Key)]);
            }

            if (Collection is IList)
            {
                Int32?index = UniConvert.ToInt32N(Key);
                if (index == null || index < 0)
                {
                    return(null);
                }

                IList list = (IList)Collection;
                if (index >= list.Count)
                {
                    return(null);
                }

                return(list[index.Value]);
            }

            if (Collection is IEnumerable)
            {
                Int32?index = UniConvert.ToInt32N(Key);
                if (index == null || index < 0)
                {
                    return(null);
                }

                Int32 i = -1;
                foreach (Object item in ((IEnumerable)Collection))
                {
                    i++;
                    if (i == index.Value)
                    {
                        return(item);
                    }
                }
            }

            return(null);
        }
Пример #13
0
        ////////////////////////////////////////////////

        public static Object Do(
            OperatorType OperationType,
            Object Value1,
            Object Value2,
            Boolean ForceDecimals)
        {
            Object result = null;

            Type type1 = (Value1 == null ?
                          null : MyTypeHelper.GetNonNullableType(Value1.GetType()));

            Type type2 = (Value2 == null ?
                          null : MyTypeHelper.GetNonNullableType(Value2.GetType()));

            if (Value1 is Undefined || Value2 is Undefined)
            {
                if (OperationType == OperatorType.EQUAL)
                {
                    return(Value1 is Undefined && Value2 is Undefined);
                }
                else if (OperationType == OperatorType.NOT_EQUAL)
                {
                    return(!(Value1 is Undefined && Value2 is Undefined));
                }
                return(null);
            }

            if (type1 == null || type2 == null)
            {
                if (OperationType == OperatorType.EQUAL)
                {
                    return(type1 == null && type2 == null);
                }
                else if (OperationType == OperatorType.NOT_EQUAL)
                {
                    return(!(type1 == null && type2 == null));
                }

                return(null);
            }

            if (OperationType == OperatorType.EQUAL)
            {
                Boolean r = MyTypeHelper.IsEqualWithNumericConvert(Value1, Value2);
                return(r);
            }
            else if (OperationType == OperatorType.NOT_EQUAL)
            {
                Boolean r = !MyTypeHelper.IsEqualWithNumericConvert(Value1, Value2);
                return(r);
            }
            else if (OperationType == OperatorType.PROPERTY)
            {
                Object outValue = MyReflectionHelper.GetValue(InternalTypeConverter.ToOuter(Value1), UniConvert.ToString(Value2));
                return(InternalTypeConverter.ToInner(outValue));
            }
            else if (MyTypeHelper.IsNumeric(type1) && MyTypeHelper.IsNumeric(type2))
            {
                result = ExecuteOperatorOnNumericValues(Value1, Value2, OperationType, ForceDecimals);
            }
            else
            {
                if (type1 == typeof(TimeSpan) || type2 == typeof(TimeSpan))
                {
                    throw new DynLanInvalidOperationException("Invalid operation type " + OperationType + " (TimeSpan & TimeSpan)");
                }
                else if (OperationType == OperatorType.MULTIPLY && MyTypeHelper.IsNumeric(type1) && type2 == typeof(String))
                {
                    StringBuilder outString = new StringBuilder();
                    for (var i = 0; i < UniConvert.ToInt32(Value1); i++)
                    {
                        outString.Append(Value2);
                    }
                    return(outString.ToString());
                }
                else if (OperationType == OperatorType.MULTIPLY && MyTypeHelper.IsNumeric(type2) && type1 == typeof(String))
                {
                    StringBuilder outString = new StringBuilder();
                    for (var i = 0; i < UniConvert.ToInt32(Value2); i++)
                    {
                        outString.Append(Value1);
                    }
                    return(outString.ToString());
                }
                else if (type1 == typeof(String) || type2 == typeof(String))
                {
                    String str1          = (UniConvert.ToUniString(InternalTypeConverter.ToOuter(Value1)) ?? "");
                    String str2          = (UniConvert.ToUniString(InternalTypeConverter.ToOuter(Value2)) ?? "");
                    Int32  compareResult = str1.CompareTo(str2);

                    if (OperationType == OperatorType.GREATER)
                    {
                        result = compareResult > 0;
                    }
                    else if (OperationType == OperatorType.SMALLER)
                    {
                        result = compareResult < 0;
                    }
                    else if (OperationType == OperatorType.GREATER_OR_EQUAL)
                    {
                        result = compareResult >= 0;
                    }
                    else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
                    {
                        result = compareResult <= 0;
                    }
                    else if (OperationType == OperatorType.EQUAL)
                    {
                        result = compareResult == 0;
                    }
                    else if (OperationType == OperatorType.NOT_EQUAL)
                    {
                        result = compareResult != 0;
                    }
                    else
                    {
                        return(str1 + str2);
                    }
                }
                else if (type1 == typeof(InternalDateTime) && type2 == typeof(InternalDateTime))
                {
                    var lN1 = (InternalDateTime)Value1;
                    var lN2 = (InternalDateTime)Value2;
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN1.Ticks + lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime(lN1.Ticks - lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.GREATER)
                    {
                        result = lN1.Ticks > lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.SMALLER)
                    {
                        result = lN1.Ticks < lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.GREATER_OR_EQUAL)
                    {
                        result = lN1.Ticks >= lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
                    {
                        result = lN1.Ticks <= lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.EQUAL)
                    {
                        result = lN1.Ticks == lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.NOT_EQUAL)
                    {
                        result = lN1.Ticks != lN2.Ticks;
                    }
                    else
                    {
                        throw new DynLanInvalidOperationException();
                    }
                }
                else if (MyTypeHelper.IsNumeric(type1) && type2 == typeof(InternalDateTime))
                {
                    var lN1 = UniConvert.ToDecimal(Value1);
                    var lN2 = (InternalDateTime)Value2;
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN2.Ticks + (Int64)(ticks_one_day * lN1));
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime((Int64)(lN1 * ticks_one_day) - lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.MULTIPLY)
                    {
                        result = new InternalDateTime((Int64)(lN1 * lN2.Ticks));
                    }
                    else if (OperationType == OperatorType.DIVIDE)
                    {
                        result = new InternalDateTime((Int64)(lN1 / lN2.Ticks));
                    }
                    else
                    {
                        throw new DynLanInvalidOperationException("Invalid operation type " + OperationType + " (numeric & DateTime)");
                    }
                }
                else if (type1 == typeof(InternalDateTime) && MyTypeHelper.IsNumeric(type2))
                {
                    var lN1 = (InternalDateTime)Value1;
                    var lN2 = UniConvert.ToDecimal(Value2);
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN1.Ticks + (Int64)(ticks_one_day * lN2));
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime(lN1.Ticks - (Int64)(ticks_one_day * lN2));
                    }
                    else if (OperationType == OperatorType.MULTIPLY)
                    {
                        result = new InternalDateTime((Int64)(lN1.Ticks * lN2));
                    }
                    else if (OperationType == OperatorType.DIVIDE)
                    {
                        result = new InternalDateTime((Int64)(lN1.Ticks / lN2));
                    }
                    else
                    {
                        throw new DynLanInvalidOperationException("Invalid operation type " + OperationType + " (DateTime & numeric)");
                    }
                }
                else
                {
                    throw new DynLanInvalidOperationException("Invalid operation type " + OperationType + " (" + (type1 == null ? "null" : type1.Name) + " & " + (type2 == null ? "null" : type2.Name) + ")");
                }
            }

            return(result);
        }
Пример #14
0
        private static object ExecuteOperatorOnDecimals(Object Value1, Object Value2, OperatorType OperationType)
        {
            Object result = null;

            Decimal value1 = UniConvert.
                             ToDecimal(Value1);

            Decimal value2 = UniConvert.
                             ToDecimal(Value2);

            if (OperationType == OperatorType.PLUS)
            {
                result = value1 + value2;
            }
            else if (OperationType == OperatorType.DIVIDE)
            {
                result = value1 / value2;
            }
            else if (OperationType == OperatorType.MULTIPLY)
            {
                result = value1 * value2;
            }
            else if (OperationType == OperatorType.SUBTRACT)
            {
                result = value1 - value2;
            }
            else if (OperationType == OperatorType.GREATER)
            {
                result = value1 > value2;
            }
            else if (OperationType == OperatorType.SMALLER)
            {
                result = value1 < value2;
            }
            else if (OperationType == OperatorType.GREATER_OR_EQUAL)
            {
                result = value1 >= value2;
            }
            else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
            {
                result = value1 <= value2;
            }
            else if (OperationType == OperatorType.EQUAL)
            {
                result = value1 == value2;
            }
            else if (OperationType == OperatorType.NOT_EQUAL)
            {
                result = value1 != value2;
            }
            else if (OperationType == OperatorType.AND)
            {
                result = (value1 != 0) && (value2 != 0);
            }
            else if (OperationType == OperatorType.OR)
            {
                result = (value1 != 0) || (value2 != 0);
            }
            else
            {
                throw new DynLanInvalidOperationException();
            }

            return(result);
        }
Пример #15
0
        ////////////////////////////////////////////////

        public static Object Do(
            OperatorType OperationType,
            Object Value1,
            Object Value2)
        {
            Object result = null;

            Type type1 = (Value1 == null ?
                          null : MyTypeHelper.GetNonNullableType(Value1.GetType()));

            Type type2 = (Value2 == null ?
                          null : MyTypeHelper.GetNonNullableType(Value2.GetType()));

            if (type1 == null || type2 == null)
            {
                return(null);
            }

            if (OperationType == OperatorType.EQUAL)
            {
                Boolean r = Value1.IsEqualWithNumericConvert(Value2);
                return(r);
            }
            else if (OperationType == OperatorType.NOT_EQUAL)
            {
                Boolean r = !Value1.IsEqualWithNumericConvert(Value2);
                return(r);
            }
            else if (OperationType == OperatorType.PROPERTY)
            {
                Object outValue = InternalTypeConverter.ToOuter(Value1).GetValue(UniConvert.ToString(Value2));
                return(InternalTypeConverter.ToInner(outValue));
            }

            /*else if (OperationType == OperatorType.METHODCALL)
             * {
             *  Object outValue = InternalTypeConverter.ToOuter(Value1).GetValue(UniConvert.ToString(Value2));
             *  return InternalTypeConverter.ToInner(outValue);
             * }*/
            else if (MyTypeHelper.IsNumeric(type1) && MyTypeHelper.IsNumeric(type2))
            {
                Decimal value1 = UniConvert.
                                 ToDecimal(Value1);

                Decimal value2 = UniConvert.
                                 ToDecimal(Value2);

                if (OperationType == OperatorType.PLUS)
                {
                    result = value1 + value2;
                }
                else if (OperationType == OperatorType.DIVIDE)
                {
                    result = value1 / value2;
                }
                else if (OperationType == OperatorType.MULTIPLY)
                {
                    result = value1 * value2;
                }
                else if (OperationType == OperatorType.SUBTRACT)
                {
                    result = value1 - value2;
                }
                else if (OperationType == OperatorType.GREATER)
                {
                    result = value1 > value2;
                }
                else if (OperationType == OperatorType.SMALLER)
                {
                    result = value1 < value2;
                }
                else if (OperationType == OperatorType.GREATER_OR_EQUAL)
                {
                    result = value1 >= value2;
                }
                else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
                {
                    result = value1 <= value2;
                }
                else if (OperationType == OperatorType.EQUAL)
                {
                    result = value1 == value2;
                }
                else if (OperationType == OperatorType.NOT_EQUAL)
                {
                    result = value1 != value2;
                }
                else if (OperationType == OperatorType.AND)
                {
                    result = (value1 != 0) && (value2 != 0);
                }
                else if (OperationType == OperatorType.OR)
                {
                    result = (value1 != 0) || (value2 != 0);
                }
                else
                {
                    throw new PainInvalidOperationException();
                }
            }
            else
            {
                if (type1 == typeof(TimeSpan) || type2 == typeof(TimeSpan))
                {
                    throw new PainInvalidOperationException("Invalid operation type " + OperationType + " (TimeSpan & TimeSpan)");
                }
                else if (OperationType == OperatorType.MULTIPLY && type1.IsNumeric() && type2 == typeof(String))
                {
                    StringBuilder outString = new StringBuilder();
                    for (var i = 0; i < UniConvert.ToInt32(Value1); i++)
                    {
                        outString.Append(Value2);
                    }
                    return(outString.ToString());
                }
                else if (OperationType == OperatorType.MULTIPLY && type2.IsNumeric() && type1 == typeof(String))
                {
                    StringBuilder outString = new StringBuilder();
                    for (var i = 0; i < UniConvert.ToInt32(Value2); i++)
                    {
                        outString.Append(Value1);
                    }
                    return(outString.ToString());
                }
                else if (type1 == typeof(String) || type2 == typeof(String))
                {
                    String str1          = (UniConvert.ToUniString(InternalTypeConverter.ToOuter(Value1)) ?? "");
                    String str2          = (UniConvert.ToUniString(InternalTypeConverter.ToOuter(Value2)) ?? "");
                    Int32  compareResult = str1.CompareTo(str2);

                    if (OperationType == OperatorType.GREATER)
                    {
                        result = compareResult > 0;
                    }
                    else if (OperationType == OperatorType.SMALLER)
                    {
                        result = compareResult < 0;
                    }
                    else if (OperationType == OperatorType.GREATER_OR_EQUAL)
                    {
                        result = compareResult >= 0;
                    }
                    else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
                    {
                        result = compareResult <= 0;
                    }
                    else if (OperationType == OperatorType.EQUAL)
                    {
                        result = compareResult == 0;
                    }
                    else if (OperationType == OperatorType.NOT_EQUAL)
                    {
                        result = compareResult != 0;
                    }
                    else
                    {
                        return(str1 + str2);
                    }
                }
                else if (type1 == typeof(InternalDateTime) && type2 == typeof(InternalDateTime))
                {
                    var lN1 = (InternalDateTime)Value1;
                    var lN2 = (InternalDateTime)Value2;
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN1.Ticks + lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime(lN1.Ticks - lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.GREATER)
                    {
                        result = lN1.Ticks > lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.SMALLER)
                    {
                        result = lN1.Ticks < lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.GREATER_OR_EQUAL)
                    {
                        result = lN1.Ticks >= lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.SMALLER_OR_EQUAL)
                    {
                        result = lN1.Ticks <= lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.EQUAL)
                    {
                        result = lN1.Ticks == lN2.Ticks;
                    }
                    else if (OperationType == OperatorType.NOT_EQUAL)
                    {
                        result = lN1.Ticks != lN2.Ticks;
                    }
                    else
                    {
                        throw new PainInvalidOperationException();
                    }
                }
                else if (MyTypeHelper.IsNumeric(type1) && type2 == typeof(InternalDateTime))
                {
                    var lN1 = UniConvert.ToDecimal(Value1);
                    var lN2 = (InternalDateTime)Value2;
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN2.Ticks + (Int64)(ticks_one_day * lN1));
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime((Int64)(lN1 * ticks_one_day) - lN2.Ticks);
                    }
                    else if (OperationType == OperatorType.MULTIPLY)
                    {
                        result = new InternalDateTime((Int64)(lN1 * lN2.Ticks));
                    }
                    else if (OperationType == OperatorType.DIVIDE)
                    {
                        result = new InternalDateTime((Int64)(lN1 / lN2.Ticks));
                    }
                    else
                    {
                        throw new PainInvalidOperationException("Invalid operation type " + OperationType + " (numeric & DateTime)");
                    }
                }
                else if (type1 == typeof(InternalDateTime) && MyTypeHelper.IsNumeric(type2))
                {
                    var lN1 = (InternalDateTime)Value1;
                    var lN2 = UniConvert.ToDecimal(Value2);
                    if (OperationType == OperatorType.PLUS)
                    {
                        result = new InternalDateTime(lN1.Ticks + (Int64)(ticks_one_day * lN2));
                    }
                    else if (OperationType == OperatorType.SUBTRACT)
                    {
                        result = new InternalDateTime(lN1.Ticks - (Int64)(ticks_one_day * lN2));
                    }
                    else if (OperationType == OperatorType.MULTIPLY)
                    {
                        result = new InternalDateTime((Int64)(lN1.Ticks * lN2));
                    }
                    else if (OperationType == OperatorType.DIVIDE)
                    {
                        result = new InternalDateTime((Int64)(lN1.Ticks / lN2));
                    }
                    else
                    {
                        throw new PainInvalidOperationException("Invalid operation type " + OperationType + " (DateTime & numeric)");
                    }
                }
                else
                {
                    throw new PainInvalidOperationException("Invalid operation type " + OperationType + " (" + (type1 == null ? "null" : type1.Name) + " & " + (type2 == null ? "null" : type2.Name) + ")");
                }
            }

            return(result);
        }
Пример #16
0
        //////////////////////////////////////////////

        private static Boolean GotoNextLine(
            DynContext DynLanContext,
            DynLanState currentState,
            Object currentValue)
        {
            try
            {
                DynLanCodeLines lines       = currentState.GetCurrentLines();
                DynLanCodeLine  currentLine = currentState.GetCurrentLine();

                // jesli return to konczymy
                if (currentLine.OperatorType == EOperatorType.RETURN)
                {
                    return(ExitCurrentContext(
                               DynLanContext,
                               currentValue,
                               null));
                }
                // throw błędu
                else if (currentLine.OperatorType == EOperatorType.THROW)
                {
                    if (currentValue is Exception)
                    {
                        throw (Exception)currentValue;
                    }
                    else
                    {
                        String message = UniConvert.ToString(currentValue ?? "");
                        throw String.IsNullOrEmpty(message) ? new Exception() : new Exception(message);
                    }

                    /*return ExitCurrentContext(
                     *  DynLanContext,
                     *  new Exception(message));*/
                }
                // jesli return to konczymy
                else if (currentLine.OperatorType == EOperatorType.BREAK)
                {
                    return(ExitCurrentLoop(
                               DynLanContext,
                               currentValue,
                               null));
                }

                if (currentLine.OperatorType == EOperatorType.WHILE ||
                    currentLine.OperatorType == EOperatorType.IF ||
                    currentLine.OperatorType == EOperatorType.ELIF)
                {
                    Boolean conditionResult = BooleanHelper.IfTrue(currentValue);
                    if (conditionResult)
                    {
                        DynLanCodeLine nextLine = DynLanCodeLinesExtender.
                                                  NextOnSameOrHigher(lines, currentLine);

                        if (nextLine != null)
                        {
                            currentState.CurrentLineID = nextLine.ID;
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        DynLanCodeLine nextLine = DynLanCodeLinesExtender.
                                                  NextOnSameOrLower(lines, currentLine);

                        if (nextLine == null)
                        {
                            return(ExitCurrentContext(
                                       DynLanContext,
                                       null));
                        }
                        else
                        {
                            if (nextLine.Depth < currentLine.Depth)
                            {
                                while (
                                    nextLine != null &
                                    (nextLine.OperatorType == EOperatorType.ELSE ||
                                     nextLine.OperatorType == EOperatorType.ELIF /*||
                                                                                  * nextLine.OperatorType == EOperatorType.FINALLY*/))
                                {
                                    nextLine = DynLanCodeLinesExtender.ExitParentIf(lines, nextLine);

                                    if (nextLine == null)
                                    {
                                        break;
                                    }
                                }

                                if (nextLine == null)
                                {
                                    return(ExitCurrentContext(
                                               DynLanContext,
                                               null));
                                }

                                if (nextLine.Depth < currentLine.Depth)
                                {
                                    //DynLanCodeLine prevIf = lines.
                                    //    PrevLineWithLessDepth(currentLine, l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF);

                                    while (true)
                                    {
                                        DynLanCodeLine prevConditionLine = DynLanCodeLinesExtender.PrevLineWithLessDepth(
                                            lines,
                                            currentLine,
                                            l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF || l.OperatorType == EOperatorType.ELSE || l.OperatorType == EOperatorType.WHILE);

                                        if (prevConditionLine != null &&
                                            prevConditionLine.Depth >= nextLine.Depth &&
                                            prevConditionLine.OperatorType == EOperatorType.WHILE)
                                        {
                                            currentState.CurrentLineID = prevConditionLine.ID;
                                            break;
                                        }
                                        else if (prevConditionLine != null)
                                        {
                                            currentLine = prevConditionLine;
                                        }
                                        else
                                        {
                                            currentState.CurrentLineID = nextLine.ID;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    currentState.CurrentLineID = nextLine.ID;
                                }
                            }
                            else
                            {
                                currentState.CurrentLineID = nextLine.ID;
                            }
                        }
                    }
                }
                else if (
                    currentLine.OperatorType == EOperatorType.TRY ||
                    currentLine.OperatorType == EOperatorType.ELSE)
                {
                    DynLanCodeLine nextLine = DynLanCodeLinesExtender.
                                              NextOnSameOrHigher(lines, currentLine);

                    if (nextLine != null)
                    {
                        currentState.CurrentLineID = nextLine.ID;
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else if (
                    (currentLine.OperatorType == EOperatorType.FINALLY))
                {
                    throw new NotImplementedException("FINALLY");
                }
                else if (
                    (currentLine.OperatorType == EOperatorType.CATCH))
                {
                    if (DynLanContext.Error != null)
                    {
                        DynLanContext.Error = null;
                        DynLanCodeLine nextLine = DynLanCodeLinesExtender.
                                                  NextOnSameOrHigher(lines, currentLine);

                        if (nextLine != null)
                        {
                            currentState.CurrentLineID = nextLine.ID;
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }
                    }
                    else
                    {
                        DynLanCodeLine nextLine = DynLanCodeLinesExtender.NextOnSameOrLower(
                            lines, currentLine);

                        if (nextLine != null)
                        {
                            currentState.CurrentLineID = nextLine.ID;
                        }
                        else
                        {
                            return(ExitCurrentContext(
                                       DynLanContext,
                                       null));
                        }
                    }
                }
                else if (currentLine.OperatorType == EOperatorType.NONE || currentLine.OperatorType == EOperatorType.PASS)
                {
                    DynLanCodeLine nextLine = DynLanCodeLinesExtender.NextLine(lines, currentLine);
                    if (nextLine != null)
                    {
                        while (
                            nextLine != null &
                            (nextLine.OperatorType == EOperatorType.ELSE ||
                             nextLine.OperatorType == EOperatorType.ELIF /*||
                                                                          * nextLine.OperatorType == EOperatorType.FINALLY*/))
                        {
                            nextLine = DynLanCodeLinesExtender.ExitParentIf(lines, nextLine);

                            if (nextLine == null)
                            {
                                return(ExitCurrentContext(
                                           DynLanContext,
                                           null));
                            }
                        }

                        if (nextLine == null)
                        {
                            return(ExitCurrentContext(
                                       DynLanContext,
                                       null));
                        }

                        if (nextLine.Depth < currentLine.Depth)
                        {
                            //DynLanCodeLine prevIf = lines.
                            //    PrevLineWithLessDepth(currentLine, l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF);

                            while (true)
                            {
                                DynLanCodeLine prevConditionLine = DynLanCodeLinesExtender.
                                                                   PrevLineWithLessDepth(
                                    lines,
                                    currentLine,
                                    l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF || l.OperatorType == EOperatorType.ELSE || l.OperatorType == EOperatorType.WHILE);

                                if (prevConditionLine != null &&
                                    prevConditionLine.Depth >= nextLine.Depth &&
                                    prevConditionLine.OperatorType == EOperatorType.WHILE)
                                {
                                    currentState.CurrentLineID = prevConditionLine.ID;
                                    break;
                                }
                                else if (prevConditionLine != null)
                                {
                                    currentLine = prevConditionLine;
                                }
                                else
                                {
                                    currentState.CurrentLineID = nextLine.ID;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            currentState.CurrentLineID = nextLine.ID;
                        }
                    }
                    // jeśli ostatnia linia i jesteśmy w while'u
                    else
                    {
                        //DynLanCodeLine prevIf = lines.
                        //    PrevLineWithLessDepth(currentLine, l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF);

                        while (true)
                        {
                            DynLanCodeLine prevConditionLine = DynLanCodeLinesExtender.
                                                               PrevLineWithLessDepth(
                                lines,
                                currentLine,
                                l => l.OperatorType == EOperatorType.IF || l.OperatorType == EOperatorType.ELIF || l.OperatorType == EOperatorType.ELSE || l.OperatorType == EOperatorType.WHILE);

                            if (prevConditionLine != null &&
                                prevConditionLine.OperatorType == EOperatorType.WHILE)
                            {
                                currentState.CurrentLineID = prevConditionLine.ID;
                                break;
                            }
                            else if (prevConditionLine != null)
                            {
                                currentLine = prevConditionLine;
                            }
                            else
                            {
                                return(ExitCurrentContext(
                                           DynLanContext,
                                           null));
                            }
                        }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #17
0
 private static String From_Numeric(Object NumericValue)
 {
     return(UniConvert.ToString(NumericValue).Replace(",", "."));
 }
Пример #18
0
 private static String From_Int(Object NumericValue)
 {
     return(UniConvert.ToString(NumericValue));
 }
Пример #19
0
        ////////////////////////////////////////////////////////////////////

        private static IEnumerable <DynMethod> BuildMethods()
        {
            yield return(new DynMethod()
            {
                Names = new[] { MethodSetValue.Name },
                Body = MethodSetValue.Execute
            });

            /*yield return new ExpressionMethod()
             * {
             *  OperationNames = new[] { "check" },
             *  CalculateValueDelegate = (DynLanContext, Parameters) =>
             *  {
             *      Object condition = Parameters != null && Parameters.Count > 0 ? Parameters[0] : null;
             *      Object ifTrue = Parameters != null && Parameters.Count > 1 ? Parameters[1] : null;
             *      Object ifFalse = Parameters != null && Parameters.Count > 2 ? Parameters[2] : null;
             *
             *      if (condition != null)
             *      {
             *          Type conditionType = condition.GetType();
             *
             *          if ((MyTypeHelper.IsNumeric(conditionType) && Convert.ToDecimal(condition) > 0) ||
             *              (conditionType == typeof(String) && Convert.ToString(condition).Length > 0))
             *          {
             *              return new ExpressionMethodResult(ifTrue);
             *          }
             *          else
             *          {
             *              return new ExpressionMethodResult(ifFalse);
             *          }
             *      }
             *
             *      return new ExpressionMethodResult(null);
             *  }
             * };*/
            yield return(new DynMethod()
            {
                Names = new[] { "getdatetime" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(DateTime.Now);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getdatetimeastext" },
                Body = (DynLanContext, Parameters) =>
                {
                    DateTime now = DateTime.Now.Date;
                    String nowText = StringHelper.FormatDate(now, "yyyymmddThhmiss");
                    return new DynMethodResult(nowText);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getdate" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(DateTime.Now.Date);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getdateastext" },
                Body = (DynLanContext, Parameters) =>
                {
                    DateTime now = DateTime.Now.Date;
                    String nowText = StringHelper.FormatDate(now, "yyyymmdd");
                    return new DynMethodResult(nowText);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "return" },
                Body = (DynLanContext, Parameters) =>
                {
#if !NET20
                    return new DynMethodResult(Parameters.FirstOrDefault());
#else
                    return new DynMethodResult(Linq2.FirstOrDefault(Parameters));
#endif
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "substring" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        String str = UniConvert.ToUniString(Parameters[0] ?? "");
                        if (Parameters.Count > 2)
                        {
                            Int32 start = Convert.ToInt32(Parameters[1]);
                            Int32 len = Convert.ToInt32(Parameters[2]);
                            if (start < str.Length)
                            {
                                if (start + len <= str.Length)
                                {
                                    return new DynMethodResult(str.Substring(start, len));
                                }
                                else
                                {
                                    return new DynMethodResult(str.Substring(start));
                                }
                            }
                            return new DynMethodResult("");
                        }
                        else if (Parameters.Count == 2)
                        {
                            Int32 start = Convert.ToInt32(Parameters[1]);
                            if (start < str.Length)
                            {
                                return new DynMethodResult(str.Substring(start));
                            }
                            return new DynMethodResult("");
                        }
                        return new DynMethodResult(str);
                    }
                    return new DynMethodResult("");
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "split" },
                Body = (DynLanContext, Parameters) =>
                {
#if NETCE
                    throw new NotImplementedException();
#else
                    if (Parameters.Count > 0)
                    {
                        List <String> list = new List <String>();
                        String str = UniConvert.ToUniString(Parameters[0] ?? "");
                        if (Parameters.Count > 1)
                        {
                            List <String> splitParams = new List <String>();
                            for (Int32 i = 1; i < Parameters.Count; i++)
                            {
                                splitParams.Add(UniConvert.ToString(Parameters[i] ?? ""));
                            }

#if NET20
                            foreach (String item in str.Split(splitParams.ToArray(), StringSplitOptions.None))
#else
                            foreach (String item in str.Split(splitParams.ToArray(), StringSplitOptions.None))
#endif
                            { list.Add(item); }
                        }
                        else
                        {
                            list.Add(str);
                        }
                        return new DynMethodResult(list);
                    }
                    return new DynMethodResult("");
#endif
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "str" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        return new DynMethodResult(
                            UniConvert.ToString(Parameters[0]));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "lower" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        if (Parameters[0] == null)
                        {
                            return null;
                        }
                        return new DynMethodResult(
                            UniConvert.ToString(Parameters[0]).ToLower());
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "upper" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        if (Parameters[0] == null)
                        {
                            return null;
                        }
                        return new DynMethodResult(
                            UniConvert.ToString(Parameters[0]).ToUpper());
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "ceil" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        return new DynMethodResult(
                            UniConvert.ToDecimal(Math.Ceiling(UniConvert.ToDouble(Parameters[0]))));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "eval" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
#if !NET20
                        DynLanProgram program = new Compiler().Compile(
                            UniConvert.ToString(Parameters.First()));
#else
                        DynLanProgram program = new Compiler().Compile(
                            UniConvert.ToString(Linq2.FirstOrDefault(Parameters)));
#endif

                        EvaluatorForMethods.EvaluateMethod(
                            null,
                            program,
                            null,
                            DynLanContext);

                        return new DynMethodResult()
                        {
                            NewContextCreated = true
                        };
                    }
                    return new DynMethodResult(null);
                }
            });

            /*yield return new ExpressionMethod()
             * {
             *  OperationNames = new[] { "bindtoevent" },
             *  CalculateValueDelegate = (DynLanContext, Parameters) =>
             *  {
             *      if (Parameters.Count > 0)
             *      {
             *          Object obj = Parameters != null && Parameters.Count > 0 ? Parameters[0] : null;
             *          String eventName = ((Parameters != null && Parameters.Count > 1 ? Parameters[1] : null) ?? "").ToString().Trim();
             *          Object method = Parameters != null && Parameters.Count > 2 ? Parameters[2] : null;
             *
             *          throw new NotImplementedException();
             *
             *          MyReflectionHelper.BindToEvent(
             *              obj,
             *              eventName,
             *              (s, o) =>
             *              {
             *
             *              });
             *      }
             *      return new ExpressionMethodResult(null);
             *  }
             * };*/
            /*yield return new ExpressionMethod()
             * {
             *  OperationNames = new[] { "create" },
             *  CalculateValueDelegate = (DynLanContext, Parameters) =>
             *  {
             *      if (Parameters.Count <= 0)
             *          return new ExpressionMethodResult(null);
             *
             *      String typeName = UniConvert.ToString(Parameters[0]) ?? "";
             *
             *      foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
             *      {
             *          var type = assembly.GetType(typeName);
             *          if (type == null)
             *              continue;
             *
             *          if (type.IsStatic())
             *          {
             *              return null;
             *          }
             *          else
             *          {
             *              var r = Activator.CreateInstance(type);
             *              return new ExpressionMethodResult(r);
             *          }
             *      }
             *
             *      return new ExpressionMethodResult(null);
             *  }
             * };*/
            yield return(new DynMethod()
            {
                Names = new[] { "type" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count <= 0)
                    {
                        return new DynMethodResult(null);
                    }

                    String typeName = UniConvert.ToString(Parameters[0]) ?? "";
                    var type = MyAssemblyHelper.FindType(typeName);
                    return new DynMethodResult(type);
                }
            });

#if !PCL
            yield return(new DynMethod()
            {
                Names = new[] { "sleep" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Int32 milliseconds = UniConvert.ToInt32(Parameters[0]);
                        Thread.Sleep(milliseconds);
                        return new DynMethodResult(milliseconds);
                    }
                    return new DynMethodResult(0);
                }
            });
#endif
            yield return(new DynMethod()
            {
                Names = new[] { "new" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count <= 0)
                    {
                        return new DynMethodResult(null);
                    }

                    String typeName = UniConvert.ToString(Parameters[0]) ?? "";
                    var obj = MyAssemblyHelper.CreateType(typeName);
                    return new DynMethodResult(obj);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "list" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(new List <Object>());
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "dictionary" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(new Dictionary <String, Object>());
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "typeof" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
#if !NET20
                        if (Parameters.First() != null)
                        {
                            return new DynMethodResult(
                                Parameters.First().GetType());
                        }
#else
                        if (Linq2.FirstOrDefault(Parameters) != null)
                        {
                            return new DynMethodResult(
                                Linq2.FirstOrDefault(Parameters).GetType());
                        }
#endif
                    }
                    return new DynMethodResult(null);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "istypeof" },
                Body = (DynLanContext, Parameters) =>
                {
                    Boolean result = false;
                    if (Parameters.Count > 1)
                    {
                        Object obj = Parameters[0];
                        Object type = Parameters[1];

                        if (obj != null && type != null)
                        {
                            if (type is Type)
                            {
                                result = MyTypeHelper.Is(obj.GetType(), (Type)type);
                            }
                            else
                            {
                                String typeName = UniConvert.ToString(type);
                                result = MyTypeHelper.Is(obj.GetType(), typeName);
                            }
                        }
                    }
                    return new DynMethodResult(result);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "isnottypeof" },
                Body = (DynLanContext, Parameters) =>
                {
                    Boolean result = true;
                    if (Parameters.Count > 1)
                    {
                        Object obj = Parameters[0];
                        Object type = Parameters[1];

                        if (obj != null && type != null)
                        {
                            if (type is Type)
                            {
                                result = !MyTypeHelper.Is(obj.GetType(), (Type)type);
                            }
                            else
                            {
                                String typeName = UniConvert.ToString(type);
                                result = !MyTypeHelper.Is(obj.GetType(), typeName);
                            }
                        }
                    }
                    return new DynMethodResult(result);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "mod" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 1)
                    {
                        return new DynMethodResult(
                            UniConvert.ToDecimal(
                                UniConvert.ToDecimal(Parameters[0]) % UniConvert.ToDecimal(Parameters[1])));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "newguid" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(Guid.NewGuid());
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "trim" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        object val = Parameters[0];
                        if (val == null)
                        {
                            return null;
                        }

                        return new DynMethodResult(
                            UniConvert.ToString(val).Trim());
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "float", "double", "tofloat", "todouble", "decimal", "todecimal" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        return new DynMethodResult(
                            UniConvert.ToDecimal(Parameters[0]));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "isfloat", "isdouble", "isdecimal", "isnumeric" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null)
                        {
                            if (MyTypeHelper.IsNumeric(val))
                            {
                                return new DynMethodResult(
                                    UniConvert.ToDecimal(true));
                            }
                            String strval = UniConvert.ToString(val);
                            Boolean result = false;

#if NETCE
                            try
                            {
                                Decimal.Parse(strval);
                                result = true;
                            }
                            catch { }
#else
                            Decimal numval = 0;
                            if (Decimal.TryParse(strval, out numval))
                            {
                                result = true;
                            }
#endif

                            return new DynMethodResult(
                                UniConvert.ToDecimal(result));
                        }
                    }
                    return new DynMethodResult(false);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "int", "toint" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        return new DynMethodResult(
                            UniConvert.ToInt64(Parameters[0]));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "floor" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        return new DynMethodResult(
                            UniConvert.ToDecimal(
                                Math.Floor(
                                    UniConvert.ToDouble(Parameters[0]))));
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "round" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        if (Parameters.Count == 1)
                        {
                            return new DynMethodResult(
                                UniConvert.ToDecimal(
                                    Math.Round(
                                        UniConvert.ToDouble(Parameters[0]))));
                        }
                        else
                        {
                            return new DynMethodResult(
                                UniConvert.ToDecimal(
                                    Math.Round(
                                        UniConvert.ToDouble(Parameters[0]),
                                        Convert.ToInt32(Parameters[1]))));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "abs" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        if (Parameters.Count == 1)
                        {
                            return new DynMethodResult(
                                UniConvert.ToDecimal(
                                    Math.Abs(
                                        UniConvert.ToDouble(Parameters[0]))));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "coalesce" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        var value = Parameters[0];
                        if (value == null || value is Undefined)
                        {
                            for (var i = 1; i < Parameters.Count; i++)
                            {
                                var nextVal = Parameters[i];
                                if (nextVal != null && !(nextVal is Undefined))
                                {
                                    return new DynMethodResult(nextVal);
                                }
                            }
                        }
                        return new DynMethodResult(value);
                    }
                    return new DynMethodResult(null);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "not" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = (Parameters[0] ?? "");
                        if (val != null && !(val is Undefined))
                        {
                            Type type = val.GetType();
                            if (MyTypeHelper.IsNumeric(type))
                            {
                                Decimal numVal = UniConvert.ToDecimal(val);
                                return new DynMethodResult(Math.Sign(numVal) == 0 ? true : false);
                            }
                            else if (type.Name == "String")
                            {
                                return new DynMethodResult(
                                    String.IsNullOrEmpty(
                                        (String)val));
                            }
                            else
                            {
                                return new DynMethodResult(false);
                            }
                        }
                        else
                        {
                            return new DynMethodResult(true);
                        }
                    }
                    return new DynMethodResult(null);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getyear" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(((DateTime)val).Year);
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "len", "length" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        String val = Convert.ToString(Parameters[0] ?? "");
                        return new DynMethodResult(val.Length);
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getmonth" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(((DateTime)val).Month);
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "getday" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(((DateTime)val).Day);
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "hours" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(((TimeSpan)val).TotalHours));
                        }
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(TimeSpan.FromTicks(((DateTime)val).Ticks).TotalHours));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "days" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(((TimeSpan)val).TotalDays));
                        }
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(TimeSpan.FromTicks(((DateTime)val).Ticks).TotalDays));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "minutes" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(((TimeSpan)val).TotalMinutes));
                        }
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(TimeSpan.FromTicks(((DateTime)val).Ticks).TotalMinutes));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "seconds" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(((TimeSpan)val).TotalSeconds));
                        }
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(TimeSpan.FromTicks(((DateTime)val).Ticks).TotalSeconds));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "milliseconds" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        if (val != null && (val.GetType() == typeof(TimeSpan) || val.GetType() == typeof(TimeSpan?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(((TimeSpan)val).TotalMilliseconds));
                        }
                        if (val != null && (val.GetType() == typeof(DateTime) || val.GetType() == typeof(DateTime?)))
                        {
                            return new DynMethodResult(Convert.ToDecimal(TimeSpan.FromTicks(((DateTime)val).Ticks).TotalMilliseconds));
                        }
                    }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "weekofyear" },
                Body = (DynLanContext, Parameters) =>
                {
                    Int32?val = null;
                    if (Parameters.Count > 0)
                    {
                        try
                        {
                            DateTime?val2 = UniConvert.ToDateTimeN(Parameters[0]);
                            if (val2 != null)
                            {
                                return new DynMethodResult(
                                    (Int32)Math.Floor(val2.Value.DayOfYear / 7.0) + 1);
                            }
                        }
                        catch { }
                    }
                    return new DynMethodResult(val);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "todatetime" },
                Body = (DynLanContext, Parameters) =>
                {
                    DateTime date = new DateTime();
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        String str = UniConvert.ToUniString(val ?? "");
                        if (UniConvert.TryParseUniDateTime(str, out date))
                        {
                        }
                    }
                    return new DynMethodResult(date);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "todate" },
                Body = (DynLanContext, Parameters) =>
                {
                    DateTime date = new DateTime();
                    if (Parameters.Count > 0)
                    {
                        Object val = Parameters[0];
                        String str = UniConvert.ToUniString(val ?? "");
                        if (UniConvert.TryParseUniDateTime(str, out date))
                        {
                        }
                    }
                    return new DynMethodResult(date.Date);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "format" },
                Body = (DynLanContext, Parameters) =>
                {
                    String r = "";
                    if (Parameters.Count > 1)
                    {
                        Object val = Parameters[0];
                        String format = Convert.ToString(Parameters[1] ?? "");
                        if (val != null && (val is DateTime || val is DateTime?))
                        {
                            r = StringHelper.FormatDate((DateTime)val, format);
                        }
                    }
                    return new DynMethodResult(r);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "tostring" },
                Body = (DynLanContext, Parameters) =>
                {
                    if (Parameters.Count > 0)
                    {
                        var result = UniConvert.ToUniString(Parameters[0] ?? "");
                        if (Parameters.Count > 1)
                        {
                            var len = Convert.ToInt32(Parameters[1]);
                            var txt = (Convert.ToString(Parameters[2]) ?? "");
                            txt = txt.Replace("\"", "").Replace("'", "");

                            while (result.Length < len)
                            {
                                result = txt + result;
                            }
                        }
                        return new DynMethodResult(result);
                    }
                    return new DynMethodResult("");
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "sqrt" },
                Body = (DynLanContext, Parameters) =>
                {
                    try
                    {
                        if (Parameters.Count > 0)
                        {
                            Object val = Parameters[0];
                            Decimal result = UniConvert.ToDecimal(val);
                            return new DynMethodResult((decimal)Math.Sqrt((double)result));
                        }
                    }
                    catch { }
                    return new DynMethodResult(0);
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "adddays" },
                Body = (DynLanContext, Parameters) =>
                {
                    try
                    {
                        if (Parameters.Count > 0)
                        {
                            Object v = Parameters[0];
                            if (v != null && (v.GetType() == typeof(DateTime) || v.GetType() == typeof(DateTime?)))
                            {
                                DateTime date = (DateTime)v;
                                if (Parameters.Count > 0)
                                {
                                    var days = UniConvert.ToInt32(Parameters[1]);
                                    date = date.AddDays(days);
                                }
                                return new DynMethodResult(date);
                            }
                        }
                        return new DynMethodResult(
                            new DateTime());
                    }
                    catch
                    {
                        return new DynMethodResult(0);
                    }
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "addyears" },
                Body = (DynLanContext, Parameters) =>
                {
                    try
                    {
                        if (Parameters.Count > 0)
                        {
                            Object v = Parameters[0];
                            if (v != null && (v.GetType() == typeof(DateTime) || v.GetType() == typeof(DateTime?)))
                            {
                                DateTime date = (DateTime)v;
                                if (Parameters.Count > 0)
                                {
                                    var years = UniConvert.ToInt32(Parameters[1]);
                                    date = date.AddYears(years);
                                }
                                return new DynMethodResult(date);
                            }
                        }
                        return new DynMethodResult(new DateTime());
                    }
                    catch
                    {
                        return new DynMethodResult(0);
                    }
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "addmonths" },
                Body = (DynLanContext, Parameters) =>
                {
                    try
                    {
                        if (Parameters.Count > 0)
                        {
                            Object v = Parameters[0];
                            if (v != null && (v.GetType() == typeof(DateTime) || v.GetType() == typeof(DateTime?)))
                            {
                                DateTime date = (DateTime)v;
                                if (Parameters.Count > 0)
                                {
                                    var months = UniConvert.ToInt32(Parameters[1]);
                                    date = date.AddMonths(months);
                                }
                                return new DynMethodResult(date);
                            }
                        }
                        return new DynMethodResult(new DateTime());
                    }
                    catch
                    {
                        return new DynMethodResult(0);
                    }
                }
            });

            yield return(new DynMethod()
            {
                Names = new[] { "rand" },
                Body = (DynLanContext, Parameters) =>
                {
                    return new DynMethodResult(
                        Convert.ToDecimal(
                            new Random(DateTime.Now.Millisecond).NextDouble()));
                }
            });
        }
Пример #20
0
        public override Dictionary <String, Object> GetParameters()
        {
            Dictionary <String, Object> result = new Dictionary <string, object>();
            String lastKey = null;

            foreach (S4JToken child in Children)
            {
                if (child.IsObjectSingleKey)
                {
                    lastKey = null;
                    if (child is S4JTokenFunction fun)
                    {
                        if (fun.IsEvaluated)
                        {
                            /*lastKey = UniConvert.ToString(fun.Result);
                             * if (lastKey != null)
                             *  result[lastKey] = null;*/
                        }
                    }
                    else if (child is S4JTokenObjectContent obj)
                    {
                        foreach (var keyAndVal in obj.GetParameters())
                        {
                            result[keyAndVal.Key] = keyAndVal.Value;
                        }
                    }
                    else
                    {
                        /*lastKey = UniConvert.ToString(child.ToJson().ParseJsonOrText());
                         * if (lastKey != null)
                         *  result[lastKey] = null;*/
                    }
                }
                else if (child.IsObjectKey)
                {
                    lastKey = null;
                    if (child is S4JTokenFunction fun)
                    {
                        if (fun.IsEvaluated)
                        {
                            lastKey = UniConvert.ToString(fun.Result);
                            if (lastKey != null)
                            {
                                result[lastKey] = null;
                            }
                        }
                    }
                    else
                    {
                        lastKey = UniConvert.ToString(child.ToJson().ParseJsonOrText());
                        if (lastKey != null)
                        {
                            result[lastKey] = null;
                        }
                    }
                }
                else if (lastKey != null)
                {
                    if (child is S4JTokenFunction fun)
                    {
                        if (fun.IsEvaluated)
                        {
                            Object val = fun.Result; // child.ToJson().DeserializeJson();
                            result[lastKey] = val;
                            //throw new NotImplementedException();
                        }
                    }
                    else if (child.State.IsValue)
                    {
                        try
                        {
                            Object val = child.ToJson().ParseJsonOrText();
                            result[lastKey] = val;
                        }
                        catch
                        {
                            throw;
                        }
                    }
                }
            }
            return(result);
        }
Пример #21
0
        public static Boolean EvaluateQueue(
            DynContext DynLanContext)
        {
            ExpressionState   expState   = DynLanContext.CurrentExpressionState;
            ExpressionContext expContext = DynLanContext.CurrentExpressionContext;

            // policzenie nastepnego parametru
            if (expState.AreParametersCalculating)
            {
                expState.ParameterIndex++;
                if (expState.ParameterIndex < expState.ParameterTokens.Count)
                {
                    Boolean result = false;

                    ExpressionToken parameterToken = expState.ParameterTokens[expState.ParameterIndex];
                    if (parameterToken.TokenType == TokenType.VARIABLE)
                    {
                        result = ObjectValueGetter.EvaluateValue(
                            parameterToken.TokenName,
                            DynLanContext);
                    }
                    else if (parameterToken.TokenType == TokenType.VALUE)
                    {
                        ExpressionValue operationValue = StringHelper.
                                                         GetValueFromText(parameterToken.TokenChars);

                        Object value = (
                            operationValue == null ? null : operationValue.Value);

                        expState.Parameters.Add(value);
                    }
                    else
                    {
                        throw new DynLanIncorrectExpressionFormatException();
                    }

                    return(result);
                }
            }

            // czy zakończyć i zapisać wynik
            if (expState.TokenIndex >= expState.Expression.Tokens.Count)
            {
                Object finResult = null;
                if (expState.ValueStack.Count > 0)
                {
                    finResult = MyCollectionsExtenders.Pop(expState.ValueStack);
                }

                expState.ValueStack.Clear();
                expState.Finished = true;
                expState.Result   = InternalTypeConverter.ToOuter(finResult);

                MyCollectionsExtenders.Pop(expContext.Stack);

                if (expContext.Current != null)
                {
                    expContext.Current.PushValue(InternalTypeConverter.ToOuter(finResult));
                    return(false);
                }
                else
                {
                    expContext.Result     = InternalTypeConverter.ToOuter(finResult);
                    expContext.IsFinished = true;
                    return(true);
                }
            }

            Boolean         isFirstToken = expState.TokenIndex == 0;
            ExpressionToken token        = expState.
                                           Expression.
                                           Tokens[expState.TokenIndex];

            ExpressionTokens sequence = new ExpressionTokens(
                new TokenizerQueue().
                GetNextTokensOnSameLevel(expState.Expression.Tokens, expState.TokenIndex));

            Int32 originalSequenceCount = sequence.Count;

            sequence.RemoveBrackets();

            // wykonanie następnej operacji
            if (token.TokenType == TokenType.BRACKET_BEGIN)
            {
                IList <ExpressionToken> prevSequenceTokens = new TokenizerQueue().
                                                             GetPrevTokensOnSameLevel(expState.Expression.Tokens, expState.TokenIndex - 1);

                ExpressionTokens prev_sequence = prevSequenceTokens == null ?
                                                 null : new ExpressionTokens(prevSequenceTokens);

                // jeśli poprzedni operator to @
                if (
                    prev_sequence != null && prev_sequence.Count == 1 &&
                    OnpOnpTokenHelper.IsFunctionOperatorToken(prev_sequence[0]))
                {
                    Boolean result = false;

                    if (sequence.Count == 0 || expState.AreParametersCalculated)
                    {
                        Object obj = expState.ValueStack.Count == 1 ?
                                     new EmptyObject() :
                                     MyCollectionsExtenders.Peek(expState.ValueStack, 1);

                        Object methodObject = MyCollectionsExtenders.
                                              Peek(expState.ValueStack, 0);

                        result = EvaluatorForMethods.EvaluateMethod(
                            obj,
                            methodObject,
                            expState.Parameters,
                            DynLanContext);

                        expState.CleanParametersState();

                        expState.TokenIndex += originalSequenceCount;
                    }
                    else
                    {
                        expState.ParameterTokens = GetParameterTokens(sequence);
                        expState.ParameterIndex  = -1;
                        expState.Parameters      = new List <Object>();
                        result = false;
                    }

                    return(result);
                }
                // jeśli poprzedni operator to .
                else if (
                    prev_sequence != null && prev_sequence.Count == 1 &&
                    OnpOnpTokenHelper.IsPropertyOperatorToken(prev_sequence[0]))
                {
                    throw new DynLanIncorrectExpressionFormatException();
                }
                // jeśli brak poprzedniego operatora
                else if (
                    prev_sequence == null &&
                    sequence.Count == 1)
                {
                    Boolean result = false;

                    if (sequence[0].TokenType == TokenType.VARIABLE)
                    {
                        result = ObjectValueGetter.EvaluateValue(
                            sequence[0].TokenName,
                            DynLanContext);
                    }
                    else if (sequence[0].TokenType == TokenType.VALUE)
                    {
                        ExpressionValue operationValue = StringHelper.
                                                         GetValueFromText(sequence[0].TokenChars);

                        Object value = (
                            operationValue == null ? null : operationValue.Value);

                        expState.PushValue(value);
                    }
                    else
                    {
                        throw new DynLanIncorrectExpressionFormatException();
                    }

                    expState.TokenIndex += originalSequenceCount; // -1;
                    return(result);
                }
                else
                {
                    throw new DynLanInvalidExpressionException("Incorrect expression " + expState.Expression.Tokens.JoinToString(expState.TokenIndex) + "!");
                }
            }
            else if (token.TokenType == TokenType.VALUE)
            {
                ExpressionValue operationValue = StringHelper.
                                                 GetValueFromText(token.TokenChars);

                Object value = (
                    operationValue == null ? null : operationValue.Value);

                if (isFirstToken)
                {
                    expState.PushValue(value);
                }
                else
                {
                    Object prevValue = MyCollectionsExtenders.Peek(expState.ValueStack);

                    prevValue = InternalTypeConverter.
                                ToOuter(prevValue);

                    Object method = ObjectValueGetter.GetValueFromObject(
                        prevValue,
                        UniConvert.ToString(value));

                    expState.PushValue(method);
                }

                expState.TokenIndex += originalSequenceCount; // -1
            }
            else if (token.TokenType == TokenType.PROPERTY_NAME)
            {
                if (isFirstToken)
                {
                    throw new DynLanIncorrectExpressionFormatException();
                }
                else
                {
                    Object prevValue = MyCollectionsExtenders.Peek(expState.ValueStack);

                    prevValue = InternalTypeConverter.
                                ToOuter(prevValue);

                    Object value = ObjectValueGetter.GetValueFromObject(
                        prevValue,
                        token.TokenName);

                    expState.PushValue(value);
                }

                expState.TokenIndex += originalSequenceCount; // -1
            }
            else if (token.TokenType == TokenType.VARIABLE)
            {
                Boolean result = false;

                ExpressionToken next_token = expState.TokenIndex + 1 < expState.Expression.Tokens.Count ?
                                             expState.Expression.Tokens[expState.TokenIndex + 1] :
                                             null;

                Object prevValue = null;
                if (isFirstToken)
                {
                    prevValue = new EmptyObject();

                    /*result = ObjectValueGetter.EvaluateValueOrMethod(
                     *  new EMPTY_OBJECT(),
                     *  sequence[0].TokenName,
                     *  -1,
                     *  DynLanContext);*/
                }
                else
                {
                    prevValue = (
                        expState.ValueStack.Count == 0 ?
                        null :
                        MyCollectionsExtenders.Peek(expState.ValueStack));
                }

                prevValue = InternalTypeConverter.
                            ToOuter(prevValue);

                Int32 paramCount = -1;

                // jeśli następny operator to operator wołania funkcji @ to pobieramy z niego liczbę parametrów dla funkcji
                if (OnpOnpTokenHelper.IsFunctionOperatorToken(next_token) &&
                    next_token.TokenData != null &&
                    next_token.TokenData.FunctionParametersCount != null)
                {
                    paramCount = next_token.TokenData.FunctionParametersCount.Value;
                }
                else
                {
                    paramCount = -1;
                }

                result = ObjectValueGetter.EvaluateValueOrMethod(
                    prevValue,
                    sequence[0].TokenName,
                    paramCount,
                    DynLanContext);

                if (MyCollectionsExtenders.Peek(DynLanContext.CurrentExpressionState.ValueStack) == null)
                {
                    ExpressionToken next_next_token = expState.TokenIndex + 2 < expState.Expression.Tokens.Count ?
                                                      expState.Expression.Tokens[expState.TokenIndex + 2] :
                                                      null;

                    if (next_token.TokenType == TokenType.OPERATOR &&
                        OnpOnpTokenHelper.IsPropertyOperatorToken(next_token) &&
                        next_next_token != null)
                    {
                    }
                    else
                    {
                        next_next_token = null;
                    }

                    if (paramCount < 0)
                    {
                        if (next_next_token != null)
                        {
                            ExpressionToken next_next_next_next_next_token = expState.TokenIndex + 5 < expState.Expression.Tokens.Count ?
                                                                             expState.Expression.Tokens[expState.TokenIndex + 5] :
                                                                             null;

                            if (next_next_token.TokenName == "__EXT_SET" && next_next_next_next_next_token != null)
                            {
                                throw new DynLanMethodNotFoundException("Cannot find property " + next_next_next_next_next_token.TokenName + " in undefined object '" + sequence[0].TokenName + "'");
                            }
                            else
                            {
                                throw new DynLanMethodNotFoundException("Cannot call method '" + next_next_token.TokenName + "' in undefined object '" + sequence[0].TokenName + "'");
                            }
                        }
                        else
                        {
                            throw new DynLanMethodNotFoundException("Undefined object '" + sequence[0].TokenName + "'");
                        }
                    }
                    else
                    {
                        throw new DynLanMethodNotFoundException("Undefined method '" + sequence[0].TokenName + "' " + (prevValue == null ? "in undefined object" : ("in object of type " + prevValue.GetType().Name)));
                    }
                }

                expState.TokenIndex += originalSequenceCount; // -1
                return(result);
            }
            else if (token.TokenType == TokenType.OPERATOR)
            {
                if (!OnpOnpTokenHelper.IsFunctionOperatorToken(token) &&
                    !OnpOnpTokenHelper.IsPropertyOperatorToken(token))
                {
                    throw new DynLanIncorrectExpressionFormatException();
                }

                expState.TokenIndex += originalSequenceCount; // -1
            }

            if (MyCollectionsExtenders.Peek(expState.ValueStack) == null)
            {
                return(false);
            }

            return(false);
        }