/// <summary>Add HTTP content to a collection of <see cref="T:NMasters.Silverlight.Net.Http.HttpContent" /> objects that get serialized to multipart/form-data MIME type.</summary>
 /// <param name="content">The HTTP content to add to the collection.</param>
 /// <param name="name">The name for the HTTP content to add.</param>
 /// <exception cref="T:System.ArgumentException">The <paramref name="name" /> was null or contains only white space characters.</exception>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="content" /> was null.</exception>
 public void Add(HttpContent content, string name)
 {
     if (content == null)
     {
         throw new ArgumentNullException("content");
     }
     if (string.IsNullOrWhiteSpace(name))
     {
         throw new ArgumentException(SR.net_http_argument_empty_string, "name");
     }
     this.AddInternal(content, name, null);
 }
 /// <summary>Add HTTP content to a collection of <see cref="T:NMasters.Silverlight.Net.Http.HttpContent" /> objects that get serialized to multipart/form-data MIME type.</summary>
 /// <param name="content">The HTTP content to add to the collection.</param>
 /// <exception cref="T:System.ArgumentNullException">The <paramref name="content" /> was null.</exception>
 public override void Add(HttpContent content)
 {
     if (content == null)
     {
         throw new ArgumentNullException("content");
     }
     if (content.Headers.ContentDisposition == null)
     {
         content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
     }
     base.Add(content);
 }
 private void AddInternal(HttpContent content, string name, string fileName)
 {
     if (content.Headers.ContentDisposition == null)
     {
         // SL fixes
         //ContentDispositionHeaderValue value2 = new ContentDispositionHeaderValue("form-data") {
         //    Name = name,
         //    FileName = fileName,
         //    FileNameStar = fileName
         //};
         //content.Headers.ContentDisposition = value2;
     }
     base.Add(content);
 }
        /// <summary>
        /// Called during serialization to write an object of the specified <paramref name="type"/>
        /// to the specified <paramref name="writeStream"/>.
        /// </summary>
        /// <param name="type">The type of object to write.</param>
        /// <param name="value">The object to write.</param>
        /// <param name="writeStream">The <see cref="Stream"/> to which to write.</param>
        /// <param name="content">The <see cref="HttpContent"/> for the content being written.</param>        
        /// <returns>A <see cref="Task"/> that will write the value to the stream.</returns>
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

            if (UseDataContractJsonSerializer && Indent)
            {
                throw Error.NotSupported(FSR.UnsupportedIndent, typeof(DataContractJsonSerializer));
            }

            return TaskHelpers.RunSynchronously(() =>
            {
                Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers);

                if (UseDataContractJsonSerializer)
                {
                    if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type))
                    {
                        if (value != null)
                        {
                            value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value });
                        }
                    }

                    DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);

                    dataContractSerializer.WriteObject(writeStream, value);
                    //using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(writeStream, effectiveEncoding, ownsStream: false))
                    //{
                    //    dataContractSerializer.WriteObject(writer, value);
                    //}
                }
                else
                {
                    using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, effectiveEncoding)) { CloseOutput = false })
                    {
                        if (Indent)
                        {
                            jsonTextWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                        }
                        JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                        jsonSerializer.Serialize(jsonTextWriter, value);
                        jsonTextWriter.Flush();
                    }
                }
            });
        }
        /// <summary>
        /// Called during deserialization to read an object of the specified <paramref name="type"/>
        /// from the specified <paramref name="readStream"/>.
        /// </summary>
        /// <param name="type">The type of object to read.</param>
        /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
        /// <param name="content">The <see cref="HttpContent"/> for the content being written.</param>
        /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
        /// <returns>A <see cref="Task"/> whose result will be the object instance that has been read.</returns>
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            return TaskHelpers.RunSynchronously<object>(() =>
            {
                HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

                // If content length is 0 then return default value for this type
                if (contentHeaders != null && contentHeaders.ContentLength == 0)
                {
                    return GetDefaultValueForType(type);
                }

                // Get the character encoding for the content
                Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);

                try
                {
                    if (UseDataContractJsonSerializer)
                    {
                        DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);
                        return dataContractSerializer.ReadObject(readStream);
                        // todo: SL has no encoding param
                        //using (XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(new NonClosingDelegatingStream(readStream), _readerQuotas))
                        //{

                        //    return dataContractSerializer.ReadObject(reader);
                        //}
                    }

                    using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(readStream, effectiveEncoding)) { CloseInput = false, MaxDepth = _maxDepth })
                    {
                        JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                        if (formatterLogger != null)
                        {
                            // Error must always be marked as handled
                            // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
                            jsonSerializer.Error += (sender, e) =>
                            {
                                Exception exception = e.ErrorContext.Error;
                                formatterLogger.LogError(e.ErrorContext.Path, exception);
                                e.ErrorContext.Handled = true;
                            };
                        }
                        return jsonSerializer.Deserialize(jsonTextReader, type);
                    }

                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }
                    formatterLogger.LogError(String.Empty, e);
                    return GetDefaultValueForType(type);
                }
            });
        }