Пример #1
0
        /// <summary>
        /// Attempts to get an expression for an index parameter.
        /// </summary>
        /// <param name="indexes">The operation indexes parameter.</param>
        /// <param name="expression">A <see cref="Expression"/> to be initialized to the index expression if the operation is successful, otherwise an error expression.</param>
        /// <returns>true the operation is successful, false otherwise.</returns>
        private static bool TryGetIndexExpression(DynamicMetaObject[] indexes, out Expression expression)
        {
            if (indexes.Length == 1 && indexes[0] != null && indexes[0].Value != null)
            {
                DynamicMetaObject index = indexes[0];
                Type indexType          = indexes[0].Value.GetType();

                switch (Type.GetTypeCode(indexType))
                {
                case TypeCode.Char:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Byte:
                case TypeCode.SByte:
                    Expression argExp  = Expression.Convert(index.Expression, typeof(object));
                    Expression typeExp = Expression.Constant(typeof(int));
                    expression = Expression.Convert(Expression.Call(ChangeTypeMethodInfo, new Expression[] { argExp, typeExp }), typeof(int));
                    return(true);

                case TypeCode.Int32:
                case TypeCode.String:
                    expression = index.Expression;
                    return(true);
                }

                expression = Expression.Throw(Expression.Constant(new ArgumentException(SG.GetString(SR.InvalidIndexType, indexType))), typeof(object));
                return(false);
            }

            expression = Expression.Throw(Expression.Constant(new ArgumentException(SG.GetString(SR.NonSingleNonNullIndexNotSupported))), typeof(object));
            return(false);
        }
Пример #2
0
        /// <summary>
        /// Implements dynamic cast for JsonValue types.
        /// </summary>
        /// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
        /// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
        public override DynamicMetaObject BindConvert(ConvertBinder binder)
        {
            if (binder == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("binder"));
            }

            Expression expression = this.Expression;

            bool implicitCastSupported =
                binder.Type.IsAssignableFrom(this.LimitType) ||
                binder.Type == typeof(IEnumerable <KeyValuePair <string, JsonValue> >) ||
                binder.Type == typeof(IDynamicMetaObjectProvider) ||
                binder.Type == typeof(object);

            if (!implicitCastSupported)
            {
                if (JsonValue.IsSupportedExplicitCastType(binder.Type))
                {
                    Expression instance = Expression.Convert(this.Expression, this.LimitType);
                    expression = Expression.Call(CastValueMethodInfo.MakeGenericMethod(binder.Type), new Expression[] { instance });
                }
                else
                {
                    string exceptionMessage = SG.GetString(SR.CannotCastJsonValue, this.LimitType.FullName, binder.Type.FullName);
                    expression = Expression.Throw(Expression.Constant(new InvalidCastException(exceptionMessage)), typeof(object));
                }
            }

            expression = Expression.Convert(expression, binder.Type);

            return(new DynamicMetaObject(expression, this.DefaultRestrictions));
        }
Пример #3
0
        /// <summary>
        /// Adds a specified collection of key/value pairs to this instance.
        /// </summary>
        /// <param name="items">The collection of key/value pairs to add.</param>
        /// <exception cref="System.ArgumentNullException">If items is null.</exception>
        /// <exception cref="System.ArgumentException">If the value of any of the items in the collection
        /// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
        /// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public void AddRange(IEnumerable <KeyValuePair <string, JsonValue> > items)
        {
            if (items == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("items");
            }

            if (this.ChangingListenersCount > 0)
            {
                foreach (KeyValuePair <string, JsonValue> item in items)
                {
                    this.RaiseItemChanging(item.Value, JsonValueChange.Add, item.Key);
                }
            }

            foreach (KeyValuePair <string, JsonValue> item in items)
            {
                if (item.Value != null && item.Value.JsonType == JsonType.Default)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
                }

                this.values.Add(item.Key, item.Value);
                this.RaiseItemChanged(item.Value, JsonValueChange.Add, item.Key);
            }
        }
Пример #4
0
        /// <summary>
        /// Adds the elements from a collection of type <see cref="System.Json.JsonValue"/> to this instance.
        /// </summary>
        /// <param name="items">Collection of items to add.</param>
        /// <exception cref="System.ArgumentNullException">If items is null.</exception>
        /// <exception cref="System.ArgumentException">If any of the items in the collection
        /// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
        /// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public void AddRange(IEnumerable <JsonValue> items)
        {
            if (items == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("items");
            }

            if (this.ChangingListenersCount > 0)
            {
                int index = this.Count;
                foreach (JsonValue toBeAdded in items)
                {
                    this.RaiseItemChanging(toBeAdded, JsonValueChange.Add, index++);
                }
            }

            foreach (JsonValue item in items)
            {
                if (item != null && item.JsonType == JsonType.Default)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
                }

                this.values.Add(item);
                this.RaiseItemChanged(item, JsonValueChange.Add, this.values.Count - 1);
            }
        }
Пример #5
0
        /// <summary>
        /// Insert a JSON CLR type into the array at a specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which the item should be inserted.</param>
        /// <param name="item">The <see cref="System.Json.JsonValue"/> object to insert.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">If index is less than zero or larger than
        /// the size of the array.</exception>
        /// <exception cref="System.ArgumentException">If the object to insert has a
        /// <see cref="System.Json.JsonValue.JsonType"/> property of value
        /// <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public void Insert(int index, JsonValue item)
        {
            if (item != null && item.JsonType == JsonType.Default)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
            }

            this.RaiseItemChanging(item, JsonValueChange.Add, index);
            this.values.Insert(index, item);
            this.RaiseItemChanged(item, JsonValueChange.Add, index);
        }
Пример #6
0
        /// <summary>
        /// Adds a key/value pair to this <see cref="System.Json.JsonObject"/> instance.
        /// </summary>
        /// <param name="key">The key for the element added.</param>
        /// <param name="value">The <see cref="System.Json.JsonValue"/> for the element added.</param>
        /// <exception cref="System.ArgumentException">If the value is a <see cref="System.Json.JsonValue"/>
        /// with <see cref="System.Json.JsonValue.JsonType"/> property of
        /// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public void Add(string key, JsonValue value)
        {
            if (value != null && value.JsonType == JsonType.Default)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
            }

            this.RaiseItemChanging(value, JsonValueChange.Add, key);
            this.values.Add(key, value);
            this.RaiseItemChanged(value, JsonValueChange.Add, key);
        }
Пример #7
0
        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <param name="key">The key of the value to get or set.</param>
        /// <returns>The <see cref="System.Json.JsonValue"/> associated to the specified key.</returns>
        /// <exception cref="System.ArgumentNullException">If key is null.</exception>
        /// <exception cref="System.ArgumentException">The property is set and the value is a
        /// <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/>
        /// property of value <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public override JsonValue this[string key]
        {
            get
            {
                if (key == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
                }

                return(this.values[key]);
            }

            set
            {
                if (value != null && value.JsonType == JsonType.Default)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
                }

                if (key == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
                }

                bool      replacement = this.values.ContainsKey(key);
                JsonValue oldValue    = null;
                if (replacement)
                {
                    oldValue = this.values[key];
                    this.RaiseItemChanging(value, JsonValueChange.Replace, key);
                }
                else
                {
                    this.RaiseItemChanging(value, JsonValueChange.Add, key);
                }

                this.values[key] = value;
                if (replacement)
                {
                    this.RaiseItemChanged(oldValue, JsonValueChange.Replace, key);
                }
                else
                {
                    this.RaiseItemChanged(value, JsonValueChange.Add, key);
                }
            }
        }
Пример #8
0
        public static JsonValue JXMLToJsonValue(string jsonString)
        {
            if (jsonString == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("jsonString");
            }

            if (jsonString.Length == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new ArgumentException(SG.GetString(SR.JsonStringCannotBeEmpty), "jsonString"));
            }

            byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);

            return(JXMLToJsonValue(null, jsonBytes));
        }
Пример #9
0
        /// <summary>
        /// Validates that this object contains a member with the given name.
        /// </summary>
        /// <param name="value">The <see cref="System.Json.JsonObject"/> to which the validation will be applied.</param>
        /// <param name="key">The key of the member to search.</param>
        /// <returns>This object, so that other validation operations can be chained.</returns>
        /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException">If the validation failed.</exception>
        public static JsonObject ValidatePresence(this JsonObject value, string key)
        {
            if (value == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
            }

            if (value.ContainsKey(key))
            {
                return(value);
            }
            else
            {
                ValidationResult failedResult = new ValidationResult(SG.GetString(SR.NamedValueNotPresent, key), new List <string> {
                    key
                });
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ValidationException(failedResult, null, null));
            }
        }
Пример #10
0
        /// <summary>
        /// Gets or sets the JSON value at a specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the element to get or set.</param>
        /// <returns>The <see cref="System.Json.JsonValue"/> element at the specified index.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">If index is not a valid index for this array.</exception>
        /// <exception cref="System.ArgumentException">The property is set and the value is a
        /// <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/>
        /// property of value <see cref="F:System.Json.JsonType.Default"/>.</exception>
        public override JsonValue this[int index]
        {
            get
            {
                return(this.values[index]);
            }

            set
            {
                if (value != null && value.JsonType == JsonType.Default)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SG.GetString(SR.UseOfDefaultNotAllowed));
                }

                JsonValue oldValue = this.values[index];
                this.RaiseItemChanging(value, JsonValueChange.Replace, index);
                this.values[index] = value;
                this.RaiseItemChanged(oldValue, JsonValueChange.Replace, index);
            }
        }
Пример #11
0
        /// <summary>
        /// Returns an expression representing a 'throw' instruction based on the specified <see cref="OperationSupport"/> value.
        /// </summary>
        /// <param name="supportValue">The <see cref="OperationSupport"/> value.</param>
        /// <param name="operation">The operation type.</param>
        /// <param name="thisValue">The operation left operand.</param>
        /// <param name="operand">The operation right operand.</param>
        /// <returns>A <see cref="Expression"/> representing a 'throw' instruction.</returns>
        private static Expression GetOperationErrorExpression(OperationSupport supportValue, ExpressionType operation, JsonValue thisValue, object operand)
        {
            string exceptionMessage;
            string operandTypeName = operand != null?operand.GetType().FullName : "<null>";

            switch (supportValue)
            {
            default:
            case OperationSupport.NotSupported:
            case OperationSupport.NotSupportedOnJsonType:
            case OperationSupport.NotSupportedOnValueType:
                exceptionMessage = SG.GetString(SR.OperatorNotDefinedForJsonType, operation, thisValue.JsonType);
                break;

            case OperationSupport.NotSupportedOnOperand:
                exceptionMessage = SG.GetString(SR.OperatorNotAllowedOnOperands, operation, thisValue.GetType().FullName, operandTypeName);
                break;
            }

            return(Expression.Throw(Expression.Constant(new InvalidOperationException(exceptionMessage)), typeof(object)));
        }
Пример #12
0
        public static JsonObject ValidateTypeOf <T>(this JsonObject value, string key)
        {
            if (value == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
            }

            value.ValidatePresence(key);

            T tempOfT;

            if (!value[key].TryReadAs <T>(out tempOfT))
            {
                ValidationResult failedResult = new ValidationResult(SG.GetString(SR.NamedValueNotOfType, key, typeof(T).FullName), new List <string> {
                    key
                });
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ValidationException(failedResult, null, null));
            }

            return(value);
        }
Пример #13
0
        public static JsonValue JXMLToJsonValue(XmlDictionaryReader jsonReader)
        {
            if (jsonReader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("jsonReader");
            }

            const string      RootObjectName = "RootObject";
            Stack <JsonValue> jsonStack      = new Stack <JsonValue>();
            string            nodeType       = null;
            bool      isEmptyElement         = false;
            JsonValue parent = new JsonObject();

            jsonStack.Push(parent);
            string currentName = RootObjectName;

            try
            {
                MoveToRootNode(jsonReader);
                while (jsonStack.Count > 0 && jsonReader.NodeType != XmlNodeType.None)
                {
                    if (parent is JsonObject && currentName == null)
                    {
                        currentName = GetMemberName(jsonReader);
                    }

                    nodeType = jsonReader.GetAttribute(TypeAttributeName) ?? StringAttributeValue;

                    if (parent is JsonArray)
                    {
                        // For arrays, the element name has to be "item"
                        if (jsonReader.Name != ItemElementName)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
                        }
                    }

                    switch (nodeType)
                    {
                    case NullAttributeValue:
                    case BooleanAttributeValue:
                    case StringAttributeValue:
                    case NumberAttributeValue:
                        JsonPrimitive jsonPrimitive = ReadPrimitive(nodeType, jsonReader);
                        InsertJsonValue(jsonStack, ref parent, ref currentName, jsonPrimitive, true);
                        break;

                    case ArrayAttributeValue:
                        JsonArray jsonArray = CreateJsonArray(jsonReader, ref isEmptyElement);
                        InsertJsonValue(jsonStack, ref parent, ref currentName, jsonArray, isEmptyElement);
                        break;

                    case ObjectAttributeValue:
                        JsonObject jsonObject = CreateObjectWithTypeHint(jsonReader, ref isEmptyElement);
                        InsertJsonValue(jsonStack, ref parent, ref currentName, jsonObject, isEmptyElement);
                        break;

                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
                    }

                    while (jsonReader.NodeType == XmlNodeType.EndElement && jsonStack.Count > 0)
                    {
                        jsonReader.Read();
                        SkipWhitespace(jsonReader);
                        jsonStack.Pop();
                        if (jsonStack.Count > 0)
                        {
                            parent = jsonStack.Peek();
                        }
                    }
                }
            }
            catch (XmlException xmlException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat), xmlException));
            }

            if (jsonStack.Count != 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
            }

            return(parent[RootObjectName]);
        }
Пример #14
0
        private static JsonValue ConvertStringToJsonNumber(string value)
        {
            if (value.IndexOfAny(FloatingPointChars) < 0)
            {
                int intVal;
                if (int.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out intVal))
                {
                    return(intVal);
                }

                long longVal;
                if (long.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out longVal))
                {
                    return(longVal);
                }
            }

            decimal decValue;

            if (decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue) && decValue != 0)
            {
                return(decValue);
            }

            double dblValue;

            if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dblValue))
            {
                return(dblValue);
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SG.GetString(SR.InvalidJsonPrimitive, value)));
        }
Пример #15
0
        private static void MoveToRootNode(XmlDictionaryReader jsonReader)
        {
            while (!jsonReader.EOF && (jsonReader.NodeType == XmlNodeType.None || jsonReader.NodeType == XmlNodeType.XmlDeclaration))
            {
                // read into <root> node
                jsonReader.Read();
                SkipWhitespace(jsonReader);
            }

            if (jsonReader.NodeType != XmlNodeType.Element || !string.IsNullOrEmpty(jsonReader.NamespaceURI) || jsonReader.Name != RootElementName)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
            }
        }
Пример #16
0
        private static string GetMemberName(XmlDictionaryReader jsonReader)
        {
            string name;

            if (jsonReader.NamespaceURI == ItemElementName && jsonReader.LocalName == ItemElementName)
            {
                // JXML special case for names which aren't valid XML names
                name = jsonReader.GetAttribute(ItemElementName);

                if (name == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
                }
            }
            else
            {
                name = jsonReader.Name;
            }

            return(name);
        }
Пример #17
0
 private static JsonValue JXMLToJsonValue(Stream jsonStream, byte[] jsonBytes)
 {
     try
     {
         using (XmlDictionaryReader jsonReader = jsonStream != null ?
                                                 JsonReaderWriterFactory.CreateJsonReader(jsonStream, XmlDictionaryReaderQuotas.Max) :
                                                 JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
         {
             return(JXMLToJsonValue(jsonReader));
         }
     }
     catch (XmlException)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
     }
 }