public ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(serialized, "serialized");
            ExceptionUtilities.CheckArgumentNotNull(payloadContext, "payloadContext");

            string encodingName = payloadContext.EncodingName;

            ODataPayloadElement errorPayload = null;
            if (this.payloadErrorDeserializer.TryDeserializeErrorPayload(serialized, encodingName, out errorPayload))
            {
                return errorPayload;
            }

            var encoding = HttpUtilities.GetEncodingOrDefault(encodingName);

            XDocument document = null;
            using (StreamReader reader = new StreamReader(new MemoryStream(serialized), encoding))
            {
                document = XDocument.Load(reader);
            }

            ExceptionUtilities.Assert(document != null, "Deserialized document cannot be null.");

            return this.xmlConverter.ConvertToPayloadElement(document.Root);
        }
        /// <summary>
        /// Deserializes the payload using the JsonParser, then converts the resulting clr objects into payload element form
        /// Throws an TaupoInvalidOperationException if the json does not evaluate successfully.
        /// </summary>
        /// <param name="serialized">A raw json payload</param>
        /// <param name="payloadContext">Additional payload information to aid deserialization</param>
        /// <returns>A PayloadElement representation of the payload</returns>
        public ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(serialized, "serialized");
            ExceptionUtilities.CheckArgumentNotNull(payloadContext, "payloadContext");

            string encodingName = payloadContext.EncodingName;

            ODataPayloadElement errorPayload = null;
            if (this.payloadErrorDeserializer.TryDeserializeErrorPayload(serialized, encodingName, out errorPayload))
            {
                return errorPayload;
            }

            // Evaluate the given JSON text
            Encoding encoding = HttpUtilities.GetEncodingOrDefault(encodingName);
            string payload = encoding.GetString(serialized, 0, serialized.Length);

            JsonValue jsonData = null;
            using (StringReader reader = new StringReader(payload))
            {
                JsonTokenizer tokenizer = new JsonTokenizer(reader);
                JsonParser parser = new JsonParser(tokenizer);
                jsonData = parser.ParseValue();
            }

            // convert the deserialized JsonValue objects into payload elements
            return this.payloadConverter.ConvertToPayloadElement(jsonData);
        }
        private static void SetExpectedEntitySetAndTypeFromUri(ODataPayloadContext payloadContext, ODataUri uri)
        {
            EntitySet  entitySet  = null;
            EntityType entityType = null;

            uri.TryGetExpectedEntitySetAndType(out entitySet, out entityType);
            payloadContext.ExpectedEntitySet  = entitySet;
            payloadContext.ExpectedEntityType = entityType;
        }
        /// <summary>
        /// Deserializes the given binary payload as a long integer value
        /// </summary>
        /// <param name="serialized">The serialized value</param>
        /// <param name="payloadContext">Additional payload information to aid deserialization</param>
        /// <returns>A primitive value containing the binary payload</returns>
        public override ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
        {
            var value = base.DeserializeFromBinary(serialized, payloadContext) as PrimitiveValue;
            ExceptionUtilities.CheckObjectNotNull(value, "Value unexpectedly null or not a primitive value");
            
            var stringValue = value.ClrValue as string;
            ExceptionUtilities.CheckObjectNotNull(stringValue, "Primitive value unexpectedly null or not a string");

            value.ClrValue = this.XmlPrimitiveConverter.DeserializePrimitive(stringValue, typeof(long));
            return value;
        }
        /// <summary>
        /// Builds a new instance of the ODataPayloadContext class based on an ODataRequest.
        /// </summary>
        /// <param name="request">The request to build the payload context from.</param>
        /// <returns>The payload context for the request.</returns>
        public static ODataPayloadContext BuildPayloadContextFromRequest(HttpRequestData<ODataUri, ODataPayloadBody> request)
        {
            var payloadContext = new ODataPayloadContext();

            ODataUri uri = request.Uri;
            if (uri != null)
            {
                payloadContext = BuildODataPayloadContextFromODataUri(uri);
            }

            payloadContext.EffectiveRequestVerb = request.GetEffectiveVerb();

            return payloadContext;
        }
        /// <summary>
        /// Builds a new instance of the ODataPayloadContext class based on an ODataRequest.
        /// </summary>
        /// <param name="request">The request to build the payload context from.</param>
        /// <returns>The payload context for the request.</returns>
        public static ODataPayloadContext BuildPayloadContextFromRequest(HttpRequestData <ODataUri, ODataPayloadBody> request)
        {
            var payloadContext = new ODataPayloadContext();

            ODataUri uri = request.Uri;

            if (uri != null)
            {
                payloadContext = BuildODataPayloadContextFromODataUri(uri);
            }

            payloadContext.EffectiveRequestVerb = request.GetEffectiveVerb();

            return(payloadContext);
        }
        /// <summary>
        /// Deserializes the given binary payload as a text value
        /// </summary>
        /// <param name="serialized">The serialized value</param>
        /// <param name="payloadContext">Additional payload information to aid deserialization</param>
        /// <returns>A primitive value containing the binary payload</returns>
        public override ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(serialized, "serialized");
            ExceptionUtilities.CheckArgumentNotNull(payloadContext, "payloadContext");

            string encodingName = payloadContext.EncodingName;

            ODataPayloadElement errorPayloadElement = null;
            if (this.HtmlPayloadErrorDeserializer.TryDeserializeErrorPayload(serialized, encodingName, out errorPayloadElement))
            {
                return errorPayloadElement;
            }

            Encoding encoding = HttpUtilities.GetEncodingOrDefault(encodingName);
            
            // cannot guess type, must deserialize as a string
            return new PrimitiveValue(null, encoding.GetString(serialized, 0, serialized.Length));
        }
 /// <summary>
 /// Deserializes the given binary payload as a primitive binary value
 /// </summary>
 /// <param name="serialized">The serialized value</param>
 /// <param name="payloadContext">Additional payload information to aid deserialization</param>
 /// <returns>A primitive value containing the binary payload</returns>
 public override ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
 {
     ExceptionUtilities.CheckArgumentNotNull(serialized, "serialized");
     return new PrimitiveValue(null, serialized);
 }
        /// <summary>
        /// Builds the ODataPayloadContext context from OODataUri.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>A OData Payload Context</returns>
        public static ODataPayloadContext BuildODataPayloadContextFromODataUri(ODataUri uri)
        {
            var payloadContext = new ODataPayloadContext();

            payloadContext.PayloadUri          = uri;
            payloadContext.ExpectedPayloadKind = uri.GetExpectedPayloadType();

            switch (payloadContext.ExpectedPayloadKind)
            {
            case ODataPayloadElementType.EntitySetInstance:
            case ODataPayloadElementType.EntityInstance:
                SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);
                break;

            case ODataPayloadElementType.PrimitiveProperty:
            case ODataPayloadElementType.PrimitiveMultiValueProperty:
            case ODataPayloadElementType.ComplexProperty:
            case ODataPayloadElementType.ComplexMultiValueProperty:
            case ODataPayloadElementType.EmptyCollectionProperty:
                var propertySegment = uri.Segments.OfType <PropertySegment>().LastOrDefault();
                if (propertySegment != null)
                {
                    payloadContext.ExpectedMemberProperty = propertySegment.Property;
                    SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);

                    var parentPropertySegment = uri.Segments.GetSecondToLastOrDefault <PropertySegment>();
                    if (parentPropertySegment != null)
                    {
                        var collectionDataType = parentPropertySegment.Property.PropertyType as CollectionDataType;
                        if (collectionDataType != null)
                        {
                            var elementComplexDataType = collectionDataType.ElementDataType as ComplexDataType;
                            ExceptionUtilities.CheckObjectNotNull(elementComplexDataType, "Expected non complex DataType");
                            payloadContext.ExpectedPropertyDeclaringParentType = elementComplexDataType.Definition;
                        }
                        else
                        {
                            var complexDataType = parentPropertySegment.Property.PropertyType as ComplexDataType;
                            ExceptionUtilities.CheckObjectNotNull(complexDataType, "Expected non null complex DataType");
                            payloadContext.ExpectedPropertyDeclaringParentType = complexDataType.Definition;
                        }
                    }
                    else
                    {
                        payloadContext.ExpectedPropertyDeclaringParentType = payloadContext.ExpectedEntityType;
                    }
                }
                else
                {
                    ExceptionUtilities.Assert(
                        uri.IsFunction() || uri.IsServiceOperation() || uri.IsAction(),
                        "Property uri contains no property segments and is not a function/service operation/action.");
                    var functionSegment = uri.Segments.Last() as FunctionSegment ?? uri.Segments[uri.Segments.Count - 2] as FunctionSegment;
                    ExceptionUtilities.CheckObjectNotNull(functionSegment, "Failed to find function segment in finction/service operation uri");
                    payloadContext.ExpectedFunction = functionSegment.Function;
                }

                break;

            case ODataPayloadElementType.DeferredLink:
            case ODataPayloadElementType.LinkCollection:
                var navigationSegment = uri.Segments.OfType <NavigationSegment>().Last();
                ExceptionUtilities.CheckObjectNotNull(navigationSegment, "No navigation segments found for expected navigation property uri");
                payloadContext.ExpectedNavigationProperty = navigationSegment.NavigationProperty;
                SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);
                break;
            }

            return(payloadContext);
        }
 /// <summary>
 /// Deserializes the given binary payload as an html form payload
 /// </summary>
 /// <param name="serialized">The serialized value</param>
 /// <param name="payloadContext">Additional payload information to aid deserialization</param>
 /// <returns>A ODataPayloadElement corresponding to the binary payload</returns>
 public override ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext)
 {
     throw new TaupoNotSupportedException("Deserialization not supported");
 }
 /// <summary>
 /// Deserializes the given binary payload
 /// </summary>
 /// <param name="serialized">The serialized value</param>
 /// <param name="payloadContext">Additional payload information to aid deserialization</param>
 /// <returns>A primitive value containing the binary payload</returns>
 public abstract ODataPayloadElement DeserializeFromBinary(byte[] serialized, ODataPayloadContext payloadContext);
        /// <summary>
        /// Builds the ODataPayloadContext context from OODataUri.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>A OData Payload Context</returns>
        public static ODataPayloadContext BuildODataPayloadContextFromODataUri(ODataUri uri)
        {
            var payloadContext = new ODataPayloadContext();
            payloadContext.PayloadUri = uri;
            payloadContext.ExpectedPayloadKind = uri.GetExpectedPayloadType();

            switch (payloadContext.ExpectedPayloadKind)
            {
                case ODataPayloadElementType.EntitySetInstance:
                case ODataPayloadElementType.EntityInstance:
                    SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);
                    break;

                case ODataPayloadElementType.PrimitiveProperty:
                case ODataPayloadElementType.PrimitiveMultiValueProperty:
                case ODataPayloadElementType.ComplexProperty:
                case ODataPayloadElementType.ComplexMultiValueProperty:
                case ODataPayloadElementType.EmptyCollectionProperty:
                    var propertySegment = uri.Segments.OfType<PropertySegment>().LastOrDefault();
                    if (propertySegment != null)
                    {
                        payloadContext.ExpectedMemberProperty = propertySegment.Property;
                        SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);

                        var parentPropertySegment = uri.Segments.GetSecondToLastOrDefault<PropertySegment>();
                        if (parentPropertySegment != null)
                        {
                            var collectionDataType = parentPropertySegment.Property.PropertyType as CollectionDataType;
                            if (collectionDataType != null)
                            {
                                var elementComplexDataType = collectionDataType.ElementDataType as ComplexDataType;
                                ExceptionUtilities.CheckObjectNotNull(elementComplexDataType, "Expected non complex DataType");
                                payloadContext.ExpectedPropertyDeclaringParentType = elementComplexDataType.Definition;
                            }
                            else
                            {
                                var complexDataType = parentPropertySegment.Property.PropertyType as ComplexDataType;
                                ExceptionUtilities.CheckObjectNotNull(complexDataType, "Expected non null complex DataType");
                                payloadContext.ExpectedPropertyDeclaringParentType = complexDataType.Definition;
                            }
                        }
                        else
                        {
                            payloadContext.ExpectedPropertyDeclaringParentType = payloadContext.ExpectedEntityType;
                        }
                    }
                    else
                    {
                        ExceptionUtilities.Assert(
                            uri.IsFunction() || uri.IsServiceOperation() || uri.IsAction(),
                            "Property uri contains no property segments and is not a function/service operation/action.");
                        var functionSegment = uri.Segments.Last() as FunctionSegment ?? uri.Segments[uri.Segments.Count - 2] as FunctionSegment;
                        ExceptionUtilities.CheckObjectNotNull(functionSegment, "Failed to find function segment in finction/service operation uri");
                        payloadContext.ExpectedFunction = functionSegment.Function;
                    }

                    break;

                case ODataPayloadElementType.DeferredLink:
                case ODataPayloadElementType.LinkCollection:
                    var navigationSegment = uri.Segments.OfType<NavigationSegment>().Last();
                    ExceptionUtilities.CheckObjectNotNull(navigationSegment, "No navigation segments found for expected navigation property uri");
                    payloadContext.ExpectedNavigationProperty = navigationSegment.NavigationProperty;
                    SetExpectedEntitySetAndTypeFromUri(payloadContext, uri);
                    break;
            }

            return payloadContext;
        }
        private static void SetExpectedEntitySetAndTypeFromUri(ODataPayloadContext payloadContext, ODataUri uri)
        {
            EntitySet entitySet = null;
            EntityType entityType = null;

            uri.TryGetExpectedEntitySetAndType(out entitySet, out entityType);
            payloadContext.ExpectedEntitySet = entitySet;
            payloadContext.ExpectedEntityType = entityType;
        }