Exemple #1
0
        public static Task <IEnumerable <HttpContent> > ReadAsMultipartAsync(this HttpContent content, IMultipartStreamProvider streamProvider, int bufferSize)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (streamProvider == null)
            {
                throw new ArgumentNullException("streamProvider");
            }

            if (bufferSize < MinBufferSize)
            {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, MinBufferSize));
            }

            return(content.ReadAsStreamAsync().Then(stream =>
            {
                TaskCompletionSource <IEnumerable <HttpContent> > taskCompletionSource = new TaskCompletionSource <IEnumerable <HttpContent> >();
                MimeMultipartBodyPartParser parser = new MimeMultipartBodyPartParser(content, streamProvider);
                byte[] data = new byte[bufferSize];
                MultipartAsyncContext context = new MultipartAsyncContext(stream, taskCompletionSource, parser, data);

                // Start async read/write loop
                MultipartReadAsync(context);

                // Return task and complete later
                return taskCompletionSource.Task;
            }));
        }
Exemple #2
0
        // Helper to invoke parser around a query string
        private static IEnumerable <KeyValuePair <string, string> > ParseQueryString(string query)
        {
            List <KeyValuePair <string, string> > result = new List <KeyValuePair <string, string> >();

            if (String.IsNullOrWhiteSpace(query))
            {
                return(result);
            }

            if (query.Length > 0 && query[0] == '?')
            {
                query = query.Substring(1);
            }

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(query);

            FormUrlEncodedParser parser = new FormUrlEncodedParser(result, Int64.MaxValue);

            int         bytesConsumed = 0;
            ParserState state         = parser.ParseBuffer(bytes, bytes.Length, ref bytesConsumed, isFinal: true);

            if (state != ParserState.Done)
            {
                throw new InvalidOperationException(RS.Format(Properties.Resources.FormUrlEncodedParseError, bytesConsumed));
            }

            return(result);
        }
Exemple #3
0
        public void SupportedMediaTypesAddThrowsWithMediaRange(MediaTypeHeaderValue mediaType)
        {
            MockMediaTypeFormatter            formatter           = new MockMediaTypeFormatter();
            Collection <MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;

            Assert.ThrowsArgument(() => supportedMediaTypes.Add(mediaType), "item", RS.Format(Properties.Resources.CannotUseMediaRangeForSupportedMediaType, typeof(MediaTypeHeaderValue).Name, mediaType.MediaType));
        }
Exemple #4
0
        private Task <HttpContent> PrepareContentAsync()
        {
            if (Content == null)
            {
                return(_nullContentTask);
            }

            return(_streamTask.Value.Then(readStream =>
            {
                // If the content needs to be written to a target stream a 2nd time, then the stream must support
                // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target
                // stream (e.g. a NetworkStream).
                if (_contentConsumed)
                {
                    if (readStream != null && readStream.CanRead)
                    {
                        readStream.Position = 0;
                    }
                    else
                    {
                        throw new InvalidOperationException(
                            RS.Format(Properties.Resources.HttpMessageContentAlreadyRead,
                                      FormattingUtilities.HttpContentType.Name,
                                      HttpRequestMessage != null
                                          ? FormattingUtilities.HttpRequestMessageType.Name
                                          : FormattingUtilities.HttpResponseMessageType.Name));
                    }

                    _contentConsumed = true;
                }

                return Content;
            }));
        }
        /// <summary>
        /// Determines the best <see cref="Encoding"/> amongst the supported encodings
        /// for reading or writing an HTTP entity body based on the provided <paramref name="contentHeaders"/>.
        /// </summary>
        /// <param name="contentHeaders">The content headers provided as part of the request or response.</param>
        /// <returns>The <see cref="Encoding"/> to use when reading the request or writing the response.</returns>
        protected Encoding SelectCharacterEncoding(HttpContentHeaders contentHeaders)
        {
            Encoding encoding = null;

            if (contentHeaders != null && contentHeaders.ContentType != null)
            {
                // Find encoding based on content type charset parameter
                string charset = contentHeaders.ContentType.CharSet;
                if (!String.IsNullOrWhiteSpace(charset))
                {
                    encoding =
                        SupportedEncodings.FirstOrDefault(
                            enc => charset.Equals(enc.WebName, StringComparison.OrdinalIgnoreCase));
                }
            }

            if (encoding == null)
            {
                // We didn't find a character encoding match based on the content headers.
                // Instead we try getting the default character encoding.
                encoding = SupportedEncodings.FirstOrDefault();
            }

            if (encoding == null)
            {
                // No supported encoding was found so there is no way for us to start reading or writing.
                throw new InvalidOperationException(RS.Format(Properties.Resources.MediaTypeFormatterNoEncoding, GetType().Name));
            }

            return(encoding);
        }
Exemple #6
0
        /// <summary>
        /// Gets the output stream.
        /// </summary>
        /// <returns>The output stream to write the body part to.</returns>
        public Stream GetOutputStream()
        {
            if (_outputStream == null)
            {
                try
                {
                    _outputStream = _streamProvider.GetStream(_headers);
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException(RS.Format(Properties.Resources.ReadAsMimeMultipartStreamProviderException, _streamProvider.GetType().Name), e);
                }

                if (_outputStream == null)
                {
                    throw new InvalidOperationException(
                              RS.Format(Properties.Resources.ReadAsMimeMultipartStreamProviderNull, _streamProvider.GetType().Name, _streamType.Name));
                }

                if (!_outputStream.CanWrite)
                {
                    throw new InvalidOperationException(
                              RS.Format(Properties.Resources.ReadAsMimeMultipartStreamProviderReadOnly, _streamProvider.GetType().Name, _streamType.Name));
                }

                HttpContent = new StreamContent(_outputStream);
                _headers.CopyTo(HttpContent.Headers);
            }

            return(_outputStream);
        }
Exemple #7
0
        public void TryMatchMediaTypeThrowsWithNullUriInHttpRequestMessage(string uriPathExtension, string mediaType)
        {
            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);
            string errorMessage             = RS.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, typeof(UriPathExtensionMapping).Name);

            Assert.Throws <InvalidOperationException>(() => mapping.TryMatchMediaType(new HttpRequestMessage()), errorMessage);
        }
Exemple #8
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 new ArgumentNullException("binder");
            }

            Expression expression = Expression;

            bool implicitCastSupported =
                binder.Type.IsAssignableFrom(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(Expression, LimitType);
                    expression = Expression.Call(_castValueMethodInfo.MakeGenericMethod(binder.Type), new Expression[] { instance });
                }
                else
                {
                    string exceptionMessage = RS.Format(Properties.Resources.CannotCastJsonValue, 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, DefaultRestrictions));
        }
        /// <summary>
        /// Called during deserialization to read an object of the specified <paramref name="type"/>
        /// from the specified <paramref name="stream"/>.
        /// </summary>
        /// <param name="type">The type of object to read.</param>
        /// <param name="stream">The <see cref="Stream"/> from which to read.</param>
        /// <param name="contentHeaders">The <see cref="HttpContentHeaders"/> for the content being read.</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 stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            return(TaskHelpers.RunSynchronously <object>(() =>
            {
                IEnumerable <KeyValuePair <string, string> > nameValuePairs = ReadFormUrlEncoded(stream, ReadBufferSize);

                if (type == typeof(FormDataCollection))
                {
                    return new FormDataCollection(nameValuePairs);
                }

                if (FormattingUtilities.IsJTokenType(type))
                {
                    return FormUrlEncodedJson.Parse(nameValuePairs, _maxDepth);
                }

                // Passed us an unsupported type. Should have called CanReadType() first.
                throw new InvalidOperationException(
                    RS.Format(Properties.Resources.SerializerCannotSerializeType, GetType().Name, type.Name));
            }));
        }
Exemple #10
0
        public void TryMatchMediaTypeThrowsWithNullUriInHttpRequestMessage(string queryStringParameterName, string queryStringParameterValue, string mediaType)
        {
            QueryStringMapping mapping      = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);
            string             errorMessage = RS.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, typeof(QueryStringMapping).Name);

            Assert.Throws <InvalidOperationException>(() => mapping.TryMatchMediaType(new HttpRequestMessage()), errorMessage);
        }
Exemple #11
0
 public void Constructor1ThrowsWithNullFormatterInCollection()
 {
     Assert.ThrowsArgument(
         () => new MediaTypeFormatterCollection(new MediaTypeFormatter[] { null }), "formatters",
         RS.Format(Properties.Resources.CannotHaveNullInList,
                   typeof(MediaTypeFormatter).Name));
 }
Exemple #12
0
        // JsonObject passed in is semantically an array
        private static bool AddToArray(JObject parent, string[] path, string value, bool throwOnError)
        {
            Contract.Assert(parent != null, "Parent cannot be null");
            Contract.Assert(path.Length >= 2, "The path must be at least 2, one for the ending [], and one for before the '[' (which can be empty)");

            string parentPath = path[path.Length - 2];

            Contract.Assert(((IDictionary <string, JToken>)parent).ContainsKey(parentPath), "It was added on insert to get to this point");
            JObject jo = parent[parentPath] as JObject;

            if (jo == null)
            {
                // a[b][c]=1&a[b][]=2 => invalid
                if (throwOnError)
                {
                    throw new ArgumentException(RS.Format(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, path.Length - 1)));
                }

                return(false);
            }
            else
            {
                string index = GetIndex(jo, throwOnError);
                if (index == null)
                {
                    return(false);
                }

                jo.Add(index, value);
            }

            return(true);
        }
        private void VerifyAndSetObject(object value)
        {
            Contract.Assert(ObjectType != null, "Type cannot be null");

            if (value == null)
            {
                // Null may not be assigned to value types (unless Nullable<T>)
                if (!IsTypeNullable(ObjectType))
                {
                    throw new InvalidOperationException(RS.Format(Properties.Resources.CannotUseNullValueType, typeof(ObjectContent).Name, ObjectType.Name));
                }
            }
            else
            {
                // Non-null objects must be a type assignable to Type
                Type objectType = value.GetType();
                if (!ObjectType.IsAssignableFrom(objectType))
                {
                    throw new ArgumentException(RS.Format(Properties.Resources.ObjectAndTypeDisagree, objectType.Name, ObjectType.Name), "value");
                }

                if (!_formatter.CanWriteType(objectType))
                {
                    throw new InvalidOperationException(RS.Format(Properties.Resources.ObjectContent_FormatterCannotWriteType, _formatter.GetType().FullName, objectType.Name));
                }
            }

            _value = value;
        }
Exemple #14
0
        // TODO: consider optimize it by only look at the last one
        private static string GetIndex(JObject jsonObject, bool throwOnError)
        {
            int max = -1;

            if (jsonObject.Count > 0)
            {
                IEnumerable <string> keys = ((IDictionary <string, JToken>)jsonObject).Keys;
                foreach (var key in keys)
                {
                    int tempInt;
                    if (Int32.TryParse(key, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out tempInt) && tempInt > max)
                    {
                        max = tempInt;
                    }
                    else
                    {
                        if (throwOnError)
                        {
                            throw new ArgumentException(RS.Format(Properties.Resources.FormUrlEncodedMismatchingTypes, key));
                        }

                        return(null);
                    }
                }
            }

            max++;
            return(max.ToString(CultureInfo.InvariantCulture));
        }
Exemple #15
0
        public ByteRangeStream(Stream innerStream, RangeItemHeaderValue range)
            : base(innerStream)
        {
            if (range == null)
            {
                throw new ArgumentNullException("range");
            }
            if (!innerStream.CanSeek)
            {
                throw new ArgumentException(RS.Format(Resources.ByteRangeStreamNotSeekable, typeof(ByteRangeStream).Name), "innerStream");
            }
            if (innerStream.Length < 1)
            {
                throw new ArgumentOutOfRangeException("innerStream", innerStream.Length,
                                                      RS.Format(Resources.ByteRangeStreamEmpty, typeof(ByteRangeStream).Name));
            }
            if (range.From.HasValue && range.From.Value > innerStream.Length)
            {
                throw new ArgumentOutOfRangeException("range", range.From,
                                                      RS.Format(Resources.ByteRangeStreamInvalidFrom, innerStream.Length));
            }

            // Ranges are inclusive so 0-9 means the first 10 bytes
            long maxLength = innerStream.Length - 1;
            long upperbounds;

            if (range.To.HasValue)
            {
                if (range.From.HasValue)
                {
                    // e.g bytes=0-499 (the first 500 bytes offsets 0-499)
                    upperbounds  = Math.Min(range.To.Value, maxLength);
                    _lowerbounds = range.From.Value;
                }
                else
                {
                    // e.g bytes=-500 (the final 500 bytes)
                    upperbounds  = maxLength;
                    _lowerbounds = Math.Max(innerStream.Length - range.To.Value, 0);
                }
            }
            else
            {
                if (range.From.HasValue)
                {
                    // e.g bytes=500- (from byte offset 500 and up)
                    upperbounds  = maxLength;
                    _lowerbounds = range.From.Value;
                }
                else
                {
                    // e.g. bytes=- (invalid so will never get here)
                    upperbounds  = maxLength;
                    _lowerbounds = 0;
                }
            }

            _totalCount  = upperbounds - _lowerbounds + 1;
            ContentRange = new ContentRangeHeaderValue(_lowerbounds, upperbounds, innerStream.Length);
        }
        /// <summary>
        /// Creates the request URI by combining scheme (provided) with parsed values of
        /// host and path.
        /// </summary>
        /// <param name="uriScheme">The URI scheme to use for the request URI.</param>
        /// <param name="httpRequest">The unsorted HTTP request.</param>
        /// <returns>A fully qualified request URI.</returns>
        private static Uri CreateRequestUri(string uriScheme, HttpUnsortedRequest httpRequest)
        {
            Contract.Assert(httpRequest != null, "httpRequest cannot be null.");
            Contract.Assert(uriScheme != null, "uriScheme cannot be null");

            IEnumerable <string> hostValues;

            if (httpRequest.HttpHeaders.TryGetValues(FormattingUtilities.HttpHostHeader, out hostValues))
            {
                int hostCount = hostValues.Count();
                if (hostCount != 1)
                {
                    throw new IOException(RS.Format(Properties.Resources.HttpMessageParserInvalidHostCount, FormattingUtilities.HttpHostHeader, hostCount));
                }
            }
            else
            {
                throw new IOException(RS.Format(Properties.Resources.HttpMessageParserInvalidHostCount, FormattingUtilities.HttpHostHeader, 0));
            }

            // We don't use UriBuilder as hostValues.ElementAt(0) contains 'host:port' and UriBuilder needs these split out into separate host and port.
            string requestUri = String.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", uriScheme, hostValues.ElementAt(0), httpRequest.RequestUri);

            return(new Uri(requestUri));
        }
        private static JsonValue ConvertStringToJsonNumber(string value)
        {
            if (value.IndexOfAny(_floatingPointChars) < 0)
            {
                int intVal;
                if (Int32.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out intVal))
                {
                    return(intVal);
                }

                long longVal;
                if (Int64.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 new ArgumentException(RS.Format(Properties.Resources.InvalidJsonPrimitive, value.ToString()), "value");
        }
 public override bool Read()
 {
     if (Depth > _maxDepth)
     {
         throw new JsonReaderQuotaException(RS.Format(Properties.Resources.JsonTooDeep, _maxDepth));
     }
     return(base.Read());
 }
Exemple #19
0
        private static NameValueCollection GetQueryString(Uri uri)
        {
            if (uri == null)
            {
                throw new InvalidOperationException(RS.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, _queryStringMappingType.Name));
            }

            return(new FormDataCollection(uri).ReadAsNameValueCollection());
        }
Exemple #20
0
        private static bool ValidateQueryString(string key, bool throwOnError)
        {
            bool hasUnMatchedLeftBraket = false;

            for (int i = 0; i < key.Length; i++)
            {
                switch (key[i])
                {
                case '[':
                    if (!hasUnMatchedLeftBraket)
                    {
                        hasUnMatchedLeftBraket = true;
                    }
                    else
                    {
                        if (throwOnError)
                        {
                            throw new ArgumentException(RS.Format(Properties.Resources.NestedBracketNotValid, ApplicationFormUrlEncoded, i));
                        }

                        return(false);
                    }

                    break;

                case ']':
                    if (hasUnMatchedLeftBraket)
                    {
                        hasUnMatchedLeftBraket = false;
                    }
                    else
                    {
                        if (throwOnError)
                        {
                            throw new ArgumentException(RS.Format(Properties.Resources.UnMatchedBracketNotValid, ApplicationFormUrlEncoded, i));
                        }

                        return(false);
                    }

                    break;
                }
            }

            if (hasUnMatchedLeftBraket)
            {
                if (throwOnError)
                {
                    throw new ArgumentException(RS.Format(Properties.Resources.NestedBracketNotValid, ApplicationFormUrlEncoded, key.LastIndexOf('[')));
                }

                return(false);
            }

            return(true);
        }
        public static Task <HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (bufferSize < MinBufferSize)
            {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, MinBufferSize));
            }

            HttpMessageContent.ValidateHttpMessageContent(content, false, true);

            return(content.ReadAsStreamAsync().Then(stream =>
            {
                HttpUnsortedResponse httpResponse = new HttpUnsortedResponse();
                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(httpResponse);
                ParserState parseStatus;

                byte[] buffer = new byte[bufferSize];
                int bytesRead = 0;
                int headerConsumed = 0;

                while (true)
                {
                    try
                    {
                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                    }
                    catch (Exception e)
                    {
                        throw new IOException(Properties.Resources.HttpMessageErrorReading, e);
                    }

                    try
                    {
                        parseStatus = parser.ParseBuffer(buffer, bytesRead, ref headerConsumed);
                    }
                    catch (Exception)
                    {
                        parseStatus = ParserState.Invalid;
                    }

                    if (parseStatus == ParserState.Done)
                    {
                        // Create and return parsed HttpResponseMessage
                        return CreateHttpResponseMessage(httpResponse, stream, bytesRead - headerConsumed);
                    }
                    else if (parseStatus != ParserState.NeedMoreData)
                    {
                        throw new IOException(RS.Format(Properties.Resources.HttpMessageParserError, headerConsumed, buffer));
                    }
                }
            }));
        }
        protected override async Task <HttpResponseMessage> CreateItemDeleteResponse(FileSystemInfo info, string localFilePath)
        {
            HttpResponseMessage response;

            if (!PrepareBranch(true, out response))
            {
                return(response);
            }

            response = await base.CreateItemDeleteResponse(info, localFilePath);

            // Commit to local branch
            _repository.Commit(String.Format("Committing delete from request {0}", Request.RequestUri), authorName: null);

            try
            {
                // Rebase to get updates from master while checking whether we get a conflict
                _repository.Rebase(MasterBranch);

                // Switch content back to master
                _repository.UpdateRef(VfsUpdateBranch);
            }
            catch (CommandLineException commandLineException)
            {
                Tracer.TraceError(commandLineException);

                // Abort the ongoing rebase operation
                try
                {
                    _repository.RebaseAbort();
                }
                finally
                {
                    _repository.Update();
                }

                // The rebase resulted in a conflict.
                HttpResponseMessage conflictResponse = Request.CreateErrorResponse(HttpStatusCode.Conflict, commandLineException);
                return(conflictResponse);
            }

            // Deploy changes
            DeployResult result = DeployChanges();

            if (result != null && result.Status != DeployStatus.Success)
            {
                HttpResponseMessage deploymentErrorResponse =
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, RS.Format(Resources.VfsScmController_DeploymentError, result.StatusText));
                return(deploymentErrorResponse);
            }

            // Delete succeeded. We add the etag as is has been updated as a result of the delete
            // This allows a client to keep track of the latest etag even for deletes.
            response.Headers.ETag = CreateEtag(_repository.CurrentId);
            return(response);
        }
        /// <summary>
        /// Called during serialization to write an object of the specified <paramref name="type"/>
        /// to the specified <paramref name="stream"/>.
        /// </summary>
        /// <param name="type">The type of object to write.</param>
        /// <param name="value">The object to write.</param>
        /// <param name="stream">The <see cref="Stream"/> to which to write.</param>
        /// <param name="contentHeaders">The <see cref="HttpContentHeaders"/> for the content being written.</param>
        /// <param name="transportContext">The <see cref="TransportContext"/>.</param>
        /// <returns>A <see cref="Task"/> that will write the value to the stream.</returns>
        public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (UseDataContractJsonSerializer && Indent)
            {
                throw new NotSupportedException(RS.Format(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer)));
            }

            return(TaskHelpers.RunSynchronously(() =>
            {
                Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);

                if (!UseDataContractJsonSerializer)
                {
                    using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, effectiveEncoding))
                    {
                        CloseOutput = false
                    })
                    {
                        if (Indent)
                        {
                            jsonTextWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                        }
                        JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                        jsonSerializer.Serialize(jsonTextWriter, value);
                        jsonTextWriter.Flush();
                    }
                }
                else
                {
                    if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type))
                    {
                        if (value != null)
                        {
                            value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value });
                        }
                    }

                    DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);
                    using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, effectiveEncoding, ownsStream: false))
                    {
                        dataContractSerializer.WriteObject(writer, value);
                    }
                }
            }));
        }
Exemple #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="System.Json.JsonValueChangeEventArgs"/> class for
        /// changes in a <see cref="System.Json.JsonArray"/>.
        /// </summary>
        /// <param name="child">The <see cref="System.Json.JsonValue"/> instance which will be or has been modified.</param>
        /// <param name="change">The type of change of the <see cref="System.Json.JsonValue"/> event.</param>
        /// <param name="index">The index of the element being changed in a <see cref="System.Json.JsonArray"/>.</param>
        public JsonValueChangeEventArgs(JsonValue child, JsonValueChange change, int index)
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index", RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, index, 0));
            }

            this.child  = child;
            this.change = change;
            this.index  = index;
        }
            public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
            {
                if (target != null && errorSuggestion == null)
                {
                    string     exceptionMessage = RS.Format(System.Json.Properties.Resources.DynamicPropertyNotDefined, target.LimitType, Name);
                    Expression throwExpression  = Expression.Throw(Expression.Constant(new InvalidOperationException(exceptionMessage)), typeof(object));

                    errorSuggestion = new DynamicMetaObject(throwExpression, target.Restrictions);
                }

                return(errorSuggestion);
            }
Exemple #26
0
        private static JObject ParseInternal(IEnumerable <KeyValuePair <string, string> > nameValuePairs, int maxDepth, bool throwOnError)
        {
            if (nameValuePairs == null)
            {
                throw new ArgumentNullException("nameValuePairs");
            }

            if (maxDepth <= MinDepth)
            {
                throw new ArgumentOutOfRangeException("maxDepth", maxDepth, RS.Format(Properties.Resources.ArgumentMustBeGreaterThan, MinDepth));
            }

            JObject result = new JObject();

            foreach (var nameValuePair in nameValuePairs)
            {
                string key   = nameValuePair.Key;
                string value = nameValuePair.Value;

                // value is preserved, even if it's null, "undefined", "null", String.Empty, etc when converting to JToken.

                if (key == null)
                {
                    if (String.IsNullOrEmpty(value))
                    {
                        if (throwOnError)
                        {
                            throw new ArgumentException(Properties.Resources.QueryStringNameShouldNotNull, "nameValuePairs");
                        }

                        return(null);
                    }

                    string[] path = new string[] { value };
                    if (!Insert(result, path, null, throwOnError))
                    {
                        return(null);
                    }
                }
                else
                {
                    string[] path = GetPath(key, maxDepth, throwOnError);
                    if (path == null || !Insert(result, path, value, throwOnError))
                    {
                        return(null);
                    }
                }
            }

            FixContiguousArrays(result);
            return(result);
        }
Exemple #27
0
        private bool PrepareBranch(bool itemExists, out IActionResult errorResult)
        {
            // Existing resources require an etag to be updated or deleted.
            string startPoint = String.Empty;

            if (itemExists)
            {
                var ifMatch = Request.GetTypedHeaders().IfMatch;
                // TODO double-check semantics on null header (vs empty string or something)
                if (ifMatch == null || ifMatch.Count != 1)
                {
                    // TODO this is janky here, we return an actionresult but set the etag on the response directly
                    errorResult = StatusCode(StatusCodes.Status412PreconditionFailed, Resources.VfsScmController_MissingIfMatch);
                    Response.GetTypedHeaders().ETag = _currentEtag;
                    return(false);
                }

                EntityTagHeaderValue match = ifMatch.First();
                if (match.IsWeak || match.Tag == null)
                {
                    // TODO this is janky here, we return an actionresult but set the etag on the response directly
                    errorResult = StatusCode(StatusCodes.Status412PreconditionFailed, RS.Format(Resources.VfsScmController_WeakEtag, ifMatch.ToString()));
                    Response.GetTypedHeaders().ETag = _currentEtag;
                    return(false);
                }

                // If wild card match then set to current commit ID
                startPoint = match != EntityTagHeaderValue.Any ? match.Tag.ToString().Trim(_quote) : _currentEtag.Tag.ToString().Trim(_quote);
            }

            try
            {
                // Clear out any un-staged files
                _repository.Clean();

                // Create or reset branch for this upload at the given starting point (commit ID)
                _repository.CreateOrResetBranch(VfsUpdateBranch, startPoint);
            }
            catch (Exception e)
            {
                Tracer.TraceError(e);

                // TODO this is janky here, we return an actionresult but set the etag on the response directly
                errorResult = StatusCode(StatusCodes.Status412PreconditionFailed, RS.Format(Resources.VfsScmController_EtagMismatch, startPoint));
                Response.GetTypedHeaders().ETag = _currentEtag;
                return(false);
            }

            errorResult = null;
            return(true);
        }
        private void Initialize(MediaTypeHeaderValue mediaRange)
        {
            if (mediaRange == null)
            {
                throw new ArgumentNullException("mediaRange");
            }

            if (!mediaRange.IsMediaRange())
            {
                throw new InvalidOperationException(RS.Format(Properties.Resources.InvalidMediaRange, mediaRange.ToString()));
            }

            MediaRange = mediaRange;
        }
Exemple #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MultipartFileStreamProvider"/> class.
        /// </summary>
        /// <param name="rootPath">The root path where the content of MIME multipart body parts are written to.</param>
        /// <param name="bufferSize">The number of bytes buffered for writes to the file.</param>
        public MultipartFileStreamProvider(string rootPath, int bufferSize)
        {
            if (String.IsNullOrWhiteSpace(rootPath))
            {
                throw new ArgumentNullException("rootPath");
            }

            if (bufferSize < MinBufferSize)
            {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, MinBufferSize));
            }

            _rootPath   = Path.GetFullPath(rootPath);
            _bufferSize = bufferSize;
        }
            private static void ValidateMediaType(MediaTypeHeaderValue item)
            {
                if (item == null)
                {
                    throw new ArgumentNullException("item");
                }

                ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(item);

                if (parsedMediaType.IsAllMediaRange || parsedMediaType.IsSubTypeMediaRange)
                {
                    throw new ArgumentException(
                              RS.Format(Properties.Resources.CannotUseMediaRangeForSupportedMediaType, _mediaTypeHeaderValueType.Name, item.MediaType),
                              "item");
                }
            }