public void IsReadOnly_CallProperty_AlwaysFalse()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
            HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers);

            Assert.False(collection.IsReadOnly);
        }
        public void AddUserAgentInfoWithVersion()
        {
            string  defaultProductName = "FxVersion";
            string  testProductName = "TestProduct";
            string  testProductVersion = "1.0.0.0";
            Version defaultProductVer, testProductVer;

            FakeServiceClient fakeClient = new FakeServiceClient(new FakeHttpHandler());

            fakeClient.SetUserAgent(testProductName, testProductVersion);
            HttpResponseMessage response = fakeClient.DoStuffSync();
            HttpHeaderValueCollection <ProductInfoHeaderValue> userAgentValueCollection = fakeClient.HttpClient.DefaultRequestHeaders.UserAgent;

            var defaultProduct = userAgentValueCollection.Where <ProductInfoHeaderValue>((p) => p.Product.Name.Equals(defaultProductName)).FirstOrDefault <ProductInfoHeaderValue>();
            var testProduct    = userAgentValueCollection.Where <ProductInfoHeaderValue>((p) => p.Product.Name.Equals(testProductName)).FirstOrDefault <ProductInfoHeaderValue>();

            Version.TryParse(defaultProduct.Product.Version, out defaultProductVer);
            Version.TryParse(testProduct.Product.Version, out testProductVer);

            Assert.True(defaultProduct.Product.Name.Equals(defaultProductName));
            Assert.NotNull(defaultProductVer);

            Assert.True(testProduct.Product.Name.Equals(testProductName));
            Assert.True(testProduct.Product.Version.Equals(testProductVersion));
        }
 private static void MockValidator(HttpHeaderValueCollection <Uri> collection, Uri value)
 {
     if (value == invalidValue)
     {
         throw new MockException();
     }
 }
        public void Add_CallWithNullValue_Throw()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            Assert.Throws<ArgumentNullException>(() => { collection.Add(null); });
        }
        public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownHeader, headers,
                                                                                             specialValue);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.SetSpecialValue();
            collection.Add(new Uri("http://www.example.org/3/"));

            System.Collections.IEnumerable enumerable = collection;

            // The special value we added above, must be part of the collection returned by GetEnumerator().
            int  i            = 1;
            bool specialFound = false;

            foreach (var item in enumerable)
            {
                if (item.Equals(specialValue))
                {
                    specialFound = true;
                }
                else
                {
                    Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
                    i++;
                }
            }

            Assert.True(specialFound);
            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
        }
        public void Add_CallWithNullValue_Throw()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownHeader, headers);

            Assert.Throws <ArgumentNullException>(() => { collection.Add(null); });
        }
        public void IsReadOnly_CallProperty_AlwaysFalse()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
            HttpHeaderValueCollection <string> collection = new HttpHeaderValueCollection <string>(knownHeader, headers);

            Assert.False(collection.IsReadOnly);
        }
        public void Remove_CallWithNullValue_Throw()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownHeader, headers);

            Assert.Throws <ArgumentNullException>(() => { collection.Remove(null); });
        }
示例#9
0
        private static bool TryGetValidAuthenticationChallengeForScheme(string scheme, AuthenticationType authenticationType, Uri uri, ICredentials credentials,
                                                                        HttpHeaderValueCollection <AuthenticationHeaderValue> authenticationHeaderValues, out AuthenticationChallenge challenge)
        {
            challenge = default;

            if (!TryGetChallengeDataForScheme(scheme, authenticationHeaderValues, out string?challengeData))
            {
                return(false);
            }

            NetworkCredential?credential = credentials.GetCredential(uri, scheme);

            if (credential == null)
            {
                // We have no credential for this auth type, so we can't respond to the challenge.
                // We'll continue to look for a different auth type that we do have a credential for.
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.AuthenticationInfo(uri, $"Authentication scheme '{scheme}' supported by server, but not by client.");
                }
                return(false);
            }

            challenge = new AuthenticationChallenge(authenticationType, scheme, credential, challengeData);
            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.AuthenticationInfo(uri, $"Authentication scheme '{scheme}' selected. Client username={challenge.Credential.UserName}");
            }
            return(true);
        }
        public void CopyTo_ArrayTooSmall_Throw()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <string> collection = new HttpHeaderValueCollection <string>(knownStringHeader, headers);

            string[] array = new string[1];
            array[0] = null;

            collection.CopyTo(array, 0); // no exception
            Assert.Null(array[0]);

            Assert.Throws <ArgumentNullException>(() => { collection.CopyTo(null, 0); });
            Assert.Throws <ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); });
            Assert.Throws <ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); });

            headers.Add(knownStringHeader, "special");
            array = new string[0];
            AssertExtensions.Throws <ArgumentException>(null, () => { collection.CopyTo(array, 0); });

            headers.Add(knownStringHeader, "special");
            headers.Add(knownStringHeader, "special");
            array = new string[1];
            AssertExtensions.Throws <ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });

            headers.Add(knownStringHeader, "value1");
            array = new string[0];
            AssertExtensions.Throws <ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });

            headers.Add(knownStringHeader, "value2");
            array = new string[1];
            AssertExtensions.Throws <ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });

            array = new string[2];
            AssertExtensions.Throws <ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 1); });
        }
 protected virtual Task<AuthenticationHeaderValue> CreateAuthorizationHeaderAsync(
     HttpRequestMessage request, 
     HttpHeaderValueCollection<AuthenticationHeaderValue> challenges,  
     CancellationToken cancellationToken)
 {
     return Task.FromResult<AuthenticationHeaderValue>(null);
 }
 private static bool IsRequestedMediaTypeAccepted(HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> acceptHeader)
 {
     return GlobalConfiguration
         .Configuration
         .Formatters
         .Any(formatter => acceptHeader.Any(mediaType => FormatterSuportsMediaType(mediaType, formatter)));
 }
示例#13
0
        /// <summary>
        /// Determines if the body of an HTTP response is acceptable according to the <c>Accept</c>
        /// header sent in the HTTP request.
        /// </summary>
        /// <remarks>
        /// This method may be used by API calls that deserialize the response to avoid deserialization
        /// exceptions in cases where the response does not match any of the supported content types.
        /// If the HTTP request did not specify an <c>Accept</c> header, this method simply returns
        /// <see langword="true"/>.
        /// </remarks>
        /// <param name="responseMessage">The <see cref="HttpResponseMessage"/> representing the HTTP response.</param>
        /// <returns><see langword="true"/> if the content type of the response is acceptable according to the <c>Accept</c> header of the request; otherwise, <see langword="false"/>.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="responseMessage"/> is <see langword="null"/>.</exception>
        public static bool IsAcceptable(HttpResponseMessage responseMessage)
        {
            if (responseMessage == null)
            {
                throw new ArgumentNullException("responseMessage");
            }

            bool acceptable = true;

            if (responseMessage.RequestMessage != null)
            {
                HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> acceptHeaders = responseMessage.RequestMessage.Headers.Accept;
                if (acceptHeaders.Count > 0)
                {
                    MediaTypeHeaderValue contentType = responseMessage.Content.Headers.ContentType;
                    acceptable = false;
                    foreach (var acceptHeader in acceptHeaders)
                    {
                        if (IsAcceptable(acceptHeader, contentType))
                        {
                            acceptable = true;
                            break;
                        }
                    }
                }
            }

            return(acceptable);
        }
        public void CopyTo_EmptyToEmpty_Success()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers);

            Uri[] array = new Uri[0];
            collection.CopyTo(array, 0);
        }
示例#15
0
        // https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/Headers/MediaTypeWithQualityHeaderValue.cs
        internal static void AddPreserved(this HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> collection, string value)
        {
            var header = new MediaTypeWithQualityHeaderValue("text/plain");

            ReflectionCache.MediaTypeHeader.MediaTypeField.SetValue(header, value);

            collection.Add(header);
        }
示例#16
0
        // https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs
        internal static void AddPreserved(this HttpHeaderValueCollection <StringWithQualityHeaderValue> collection, string value)
        {
            var header = (StringWithQualityHeaderValue)Activator.CreateInstance(ReflectionCache.StringWithQualityHeader.Type, true);

            ReflectionCache.StringWithQualityHeader.ValueField.SetValue(header, value);

            collection.Add(header);
        }
        // Prepares Content-Length and Transfer-Encoding headers.
        private Task <bool> PrepareHeadersAsync(
            HttpRequestMessage request,
            HttpResponseMessage response,
            IOwinResponse owinResponse,
            CancellationToken cancellationToken
            )
        {
            Contract.Assert(response != null);
            HttpResponseHeaders responseHeaders = response.Headers;

            Contract.Assert(responseHeaders != null);
            HttpContent content = response.Content;
            bool        isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true;
            HttpHeaderValueCollection <TransferCodingHeaderValue> transferEncoding =
                responseHeaders.TransferEncoding;

            if (content != null)
            {
                HttpContentHeaders contentHeaders = content.Headers;
                Contract.Assert(contentHeaders != null);

                if (isTransferEncodingChunked)
                {
                    // According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer
                    // encoding must not have a content length set. Chunked should take precedence over content
                    // length in this case because chunked is always set explicitly by users while the Content-Length
                    // header can be added implicitly by System.Net.Http.
                    contentHeaders.ContentLength = null;
                }
                else
                {
                    // Copy the response content headers only after ensuring they are complete.
                    // We ask for Content-Length first because HttpContent lazily computes this header and only
                    // afterwards writes the value into the content headers.
                    return(ComputeContentLengthAsync(
                               request,
                               response,
                               owinResponse,
                               cancellationToken
                               ));
                }
            }

            // Ignore the Transfer-Encoding header if it is just "chunked"; the host will likely provide it when no
            // Content-Length is present (and if the host does not, there's not much better this code could do to
            // transmit the current response, since HttpContent is assumed to be unframed; in that case, silently drop
            // the Transfer-Encoding: chunked header).
            // HttpClient sets this header when it receives chunked content, but HttpContent does not include the
            // frames. The OWIN contract is to set this header only when writing chunked frames to the stream.
            // A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as
            // "identity, chunked").
            if (isTransferEncodingChunked && transferEncoding.Count == 1)
            {
                transferEncoding.Clear();
            }

            return(Task.FromResult(true));
        }
        public void GetEnumerator_NoValues_EmptyEnumerator()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers);

            IEnumerator <Uri> enumerator = collection.GetEnumerator();

            Assert.False(enumerator.MoveNext(), "No items expected in enumerator.");
        }
示例#19
0
        public bool IsIn
        (
            HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> httpHeaderValueCollection
        )
        {
            MediaTypeWithQualityHeaderValue mediaType = null;

            return(IsIn(httpHeaderValueCollection, out mediaType));
        }
        public void ParseAdd_CallWithNullValue_NothingAdded()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers);

            collection.ParseAdd(null);
            Assert.Equal(0, collection.Count);
            Assert.Equal(string.Empty, collection.ToString());
        }
        public Func <Stream, Stream> GetEncoder(
            HttpHeaderValueCollection <StringWithQualityHeaderValue> list)
        {
            if (list != null && list.Count > 0)
            {
                var headerValue = list.OrderByDescending(e => e.Quality ?? 1.0D)
                                  .Where(e => !e.Quality.HasValue ||
                                         e.Quality.Value > 0.0D)
                                  .FirstOrDefault(e => supported.Keys
                                                  .Contains(e.Value, StringComparer.OrdinalIgnoreCase));

                // Case 1: We can support what client has asked for
                if (headerValue != null)
                {
                    return(GetStreamForSchema(headerValue.Value));
                }


                // Case 2: Client is okay to accept any thing we support except
                // the ones explicitly specified as not preferred by setting q=0
                if (list.Any(e => e.Value == "*" &&
                             (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    var encoding = supported.Keys.Where(se =>
                                                        !list.Any(e =>
                                                                  e.Value.Equals(se, StringComparison.OrdinalIgnoreCase) &&
                                                                  e.Quality.HasValue &&
                                                                  e.Quality.Value == 0.0D))
                                   .FirstOrDefault();
                    if (encoding != null)
                    {
                        return(GetStreamForSchema(encoding));
                    }
                }

                // Case 3: Client specifically refusing identity
                if (list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase) &&
                             e.Quality.HasValue && e.Quality.Value == 0.0D))
                {
                    throw new NegotiationFailedException();
                }

                // Case 4: Client is not willing to accept one of the encodings
                // we support and is not willing to accept identity
                if (list.Any(e => e.Value == "*" &&
                             (e.Quality.HasValue || e.Quality.Value == 0.0D)))
                {
                    if (!list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new NegotiationFailedException();
                    }
                }
            }

            // Settle for the default, which is no transformation whatsoever
            return(null);
        }
示例#22
0
        private Auth0ClientSettings GetSettingsFromResponseHeader(HttpHeaderValueCollection <AuthenticationHeaderValue> wwwAuthenticationHeaderValues)
        {
            var result = new Auth0ClientSettings();

            foreach (var authenticationHeaderValue in wwwAuthenticationHeaderValues)
            {
                if (authenticationHeaderValue.Scheme.ToLowerInvariant() == "bearer")
                {
                    // The header looks like this: WWW-Authenticate: Bearer realm="example.auth0.com", scope="client_id=xxxxxxxxxx service=https://myservice.example.com"
                    // First we have to split on white spaces that are not within '" "'.
                    var parameters = Regex.Matches(authenticationHeaderValue.Parameter, "\\w+\\=\\\".*?\\\"|\\w+[^\\s\\\"]+?");

                    foreach (var param in parameters)
                    {
                        var parameterstring = param.ToString();
                        var info            = parameterstring.Trim().Split('=');
                        if (info.Length < 2)
                        {
                            continue;
                        }

                        // Realm has only 1 value.
                        if ((info[0].ToLowerInvariant()) == "realm")
                        {
                            var domain = info[1].Replace("\"", "");
                            domain = domain.ToLowerInvariant().StartsWith("http") ? domain : $"https://{domain}";
                            result.Auth0ServerUrl = domain;
                            continue;
                        }

                        // Within the scope we can have multiple key/value pairs separated by white space.
                        if (info[0].ToLowerInvariant() == "scope")
                        {
                            var scopes = parameterstring.Substring(info[0].Length + 1).Replace("\"", "").Split(' ');
                            foreach (var scope in scopes)
                            {
                                var splittedScope = scope.Split('=');
                                if (splittedScope.Length < 2)
                                {
                                    continue;
                                }

                                // We are interested in the client id.
                                if ((splittedScope[0]?.ToLowerInvariant() ?? "") == "client_id")
                                {
                                    result.Auth0ClientId = splittedScope[1];
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        public void ParseAdd_CallWithNullValue_NothingAdded()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownHeader, headers);

            collection.ParseAdd(null);
            Assert.False(collection.IsSpecialValueSet);
            Assert.Equal(0, collection.Count);
            Assert.Equal(String.Empty, collection.ToString());
        }
示例#24
0
        public bool IsIn
        (
            HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> httpHeaderValueCollection,
            out MediaTypeWithQualityHeaderValue mediaType
        )
        {
            mediaType = httpHeaderValueCollection.FirstOrDefault(n => n.MediaType.Equals(MimeType, StringComparison.InvariantCultureIgnoreCase));

            return(mediaType != null);
        }
        public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues()
        {
            // Use different ctor overload than in previous test to make sure all ctor overloads work correctly.
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers,
                                                                                             specialValue, MockValidator);

            // When we remove 'invalidValue' our MockValidator will throw.
            Assert.Throws <MockException>(() => { collection.Remove(invalidValue); });
        }
        public static HttpHeaderValueCollection <THeader> Set <THeader>(this HttpHeaderValueCollection <THeader> collection, params string[] values)
            where THeader : class
        {
            foreach (var value in values)
            {
                collection.ParseAdd(value);
            }

            return(collection);
        }
        public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse()
        {
            // Create a new collection _without_ specifying a special value.
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers,
                                                                                             null, null);

            Assert.False(collection.IsSpecialValueSet,
                         "Special value is set even though collection doesn't define a special value.");
        }
        internal static HttpHeaderValueCollection <T> AddDistinct <T>(this HttpHeaderValueCollection <T> headers, Func <T, bool> predicate, string value)
            where T : class
        {
            if (!headers.Any(predicate))
            {
                headers.ParseAdd(value);
            }

            return(headers);
        }
示例#29
0
 private bool WillAcceptType(HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> mediaTypes, string contentType)
 {
     foreach (var mediaType in mediaTypes)
     {
         if (string.Equals(mediaType.MediaType, contentType, StringComparison.InvariantCultureIgnoreCase))
         {
             return(true);
         }
     }
     return(false);
 }
        public void CopyTo_AddSingleValue_ContainsSingleValue()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers);

            collection.Add(new Uri("http://www.example.org/"));

            Uri[] array = new Uri[1];
            collection.CopyTo(array, 0);
            Assert.Equal(new Uri("http://www.example.org/"), array[0]);
        }
        public void Add_AddValues_AllValuesAdded()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.Add(new Uri("http://www.example.org/3/"));

            Assert.Equal(3, collection.Count);
        }
        public void TryParseAdd_UseSpecialValue_Added()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection <Uri> collection = new HttpHeaderValueCollection <Uri>(knownUriHeader, headers,
                                                                                             specialValue);

            Assert.True(collection.TryParseAdd(specialValue.AbsoluteUri));

            Assert.True(collection.IsSpecialValueSet);
            Assert.Equal(specialValue.ToString(), collection.ToString());
        }
示例#33
0
        public bool RequestingAttachment()
        {
            HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> incomingMediaTypes = requestMessage.Headers.Accept;

            if (!incomingMediaTypes.Any() || incomingMediaTypes.Any(mt => RestUtils.IsJsonMediaType(mt.MediaType)))
            {
                return(false);
            }

            return(true);
        }
 public void SetAccept(HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> accept)
 {
     if (accept != null)
     {
         var acceptValues = accept.Select(v => v.MediaType);
         if (accept != null)
         {
             this.Client.DefaultRequestHeaders.Add("Accept", acceptValues);
         }
     }
 }
        protected override async Task<AuthenticationHeaderValue> CreateAuthorizationHeaderAsync(HttpRequestMessage request, HttpHeaderValueCollection<AuthenticationHeaderValue> challenges, CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue bearerChallenge = challenges.FirstOrDefault(IsOAuth2BearerChallenge);
            if (bearerChallenge != null)
            {
                string accessToken = await GetAccessTokenAsync(request);
                if (accessToken != null)
                {
                    return new AuthenticationHeaderValue(BearerScheme, accessToken);                 
                }
            }
 	        return null;
        }
        public static IParseDomainPosts CreateParser(HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> mediaTypeHeaderValues)
        {
            bool containsXml = false;

            foreach (var mediaType in mediaTypeHeaderValues)
                if (mediaType.MediaType.Contains("xml"))
                    containsXml = true;

            //if its xml try reading using xml
            if (containsXml)
            {
                return new XmlDomainPostParser();
            }
            // otherwise try to read it as json, treat as 'default' andlast resort
            return new JsonDomainPostParser();
        }
        public IActionConfiguration GetcontrollerActionConfiguration(Type controllerType, MethodInfo actionMethodInfo, HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> acceptHeaders)
        {
            if (!_controllerRules.ContainsKey(controllerType))
                return null;
            var controller = _controllerRules[controllerType];

            if (!controller.ContainsKey(actionMethodInfo))
                return null;

            var result = controller[actionMethodInfo];

            if ((acceptHeaders != null) && !acceptHeaders.Contains(new MediaTypeWithQualityHeaderValue(result.MetadataProvider.ContentType)))
                return null;

            return result;
        }
        public void Count_AddMultipleValuesThenQueryCount_ReturnsValueCountWithSpecialValues()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
            HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers,
                "special");

            Assert.Equal(0, collection.Count);

            collection.Add("value1");
            headers.Add(knownHeader, "special");
            Assert.Equal(2, collection.Count);

            headers.Add(knownHeader, "special");
            headers.Add(knownHeader, "value2");
            headers.Add(knownHeader, "special");
            Assert.Equal(5, collection.Count);
        }
示例#39
0
        public Func<Stream, Stream> GetEncoder(HttpHeaderValueCollection<StringWithQualityHeaderValue> list)
        {
            // The following steps will walk you through
            // completing the implementation of this method
            if (list != null && list.Count > 0)
            {
                // More code goes here
                var headerValue = list.OrderByDescending(e => e.Quality ?? 1.0D).Where(e => !e.Quality.HasValue || e.Quality.Value > 0.0D).FirstOrDefault(e => supported.Keys.Contains(e.Value, StringComparer.OrdinalIgnoreCase));
                // Case 1: We can support what client has asked for
                if (headerValue != null)
                    return GetStreamForSchema(headerValue.Value);
                // Case 2: Client will accept anything we support except
                // the ones explicitly specified as not preferred by setting q=0
                if (list.Any(e => e.Value == "*" &&
                (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    var encoding = supported.Keys.Where(se =>
                    !list.Any(e =>
                    e.Value.Equals(se, StringComparison.OrdinalIgnoreCase) &&
                    e.Quality.HasValue &&
                    e.Quality.Value == 0.0D))
                    .FirstOrDefault();
                    if (encoding != null)
                        return GetStreamForSchema(encoding);
                }

                // Case 3: Client specifically refusing identity
                if (list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase) &&
                e.Quality.HasValue && e.Quality.Value == 0.0D))
                {
                    throw new NegotiationFailedException();
                }
                // Case 4: Client is not willing to accept any of the encodings
                // we support and is not willing to accept identity
                if (list.Any(e => e.Value == "*" &&
                (e.Quality.HasValue || e.Quality.Value == 0.0D)))
                {
                    if (!list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase)))
                        throw new NegotiationFailedException();
                }
            }
            // Settle for the default, which is no transformation whatsoever
            return null;
        }
        public void Add_AddValues_AllValuesAdded()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.Add(new Uri("http://www.example.org/3/"));

            Assert.Equal(3, collection.Count);
        }
        public void RemoveSpecialValue_AddRemoveSpecialValue_SpecialValueGetsRemoved()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.SetSpecialValue();
            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
            Assert.Equal(1, headers.GetValues(knownHeader).Count());

            collection.RemoveSpecialValue();
            Assert.False(collection.IsSpecialValueSet, "Special value is set.");

            // Since the only header value was the "special value", removing it will remove the whole header
            // from the collection.
            Assert.False(headers.Contains(knownHeader));
        }
        public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.SetSpecialValue();
            collection.Add(new Uri("http://www.example.org/3/"));

            System.Collections.IEnumerable enumerable = collection;

            // The special value we added above, must be part of the collection returned by GetEnumerator().
            int i = 1;
            bool specialFound = false;
            foreach (var item in enumerable)
            {
                if (item.Equals(specialValue))
                {
                    specialFound = true;
                }
                else
                {
                    Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
                    i++;
                }
            }

            Assert.True(specialFound);
            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
        }
        public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse()
        {
            // Create a new collection _without_ specifying a special value.
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                null, null);

            Assert.False(collection.IsSpecialValueSet,
                "Special value is set even though collection doesn't define a special value.");
        }
        public void CopyTo_AddMultipleValues_ContainsAllValuesInTheRightOrder()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.Add(new Uri("http://www.example.org/3/"));

            Uri[] array = new Uri[5];
            collection.CopyTo(array, 1);

            Assert.Null(array[0]);
            Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
            Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
            Assert.Equal(new Uri("http://www.example.org/3/"), array[3]);
            Assert.Null(array[4]);
        }
        public void GetEnumerator_AddValuesAndGetEnumeratorFromInterface_AllValuesReturned()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.Add(new Uri("http://www.example.org/3/"));

            System.Collections.IEnumerable enumerable = collection;

            int i = 1;
            foreach (var item in enumerable)
            {
                Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
                i++;
            }
        }
        public void CopyTo_NoValues_DoesNotChangeArray()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            Uri[] array = new Uri[4];
            collection.CopyTo(array, 0);

            for (int i = 0; i < array.Length; i++)
            {
                Assert.Null(array[i]);
            }
        }
        public void Ctor_ProvideValidator_ValidatorIsUsedWhenAddingValues()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                MockValidator);

            // Adding an arbitrary Uri should not throw.
            collection.Add(new Uri("http://some/"));

            // When we add 'invalidValue' our MockValidator will throw.
            Assert.Throws<MockException>(() => { collection.Add(invalidValue); });
        }
        public void Remove_CallWithNullValue_Throw()
        {
            MockHeaders headers = new MockHeaders();
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            Assert.Throws<ArgumentNullException>(() => { collection.Remove(null); });
        }
        public void Remove_AddValuesThenCallRemove_ReturnsTrueWhenRemovingExistingValuesFalseOtherwise()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.Add(new Uri("http://www.example.org/3/"));

            Assert.True(collection.Remove(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
            Assert.False(collection.Remove(new Uri("http://www.example.org/4/")),
                "Expected false for non-existing item.");
        }
        public void CopyTo_ArrayTooSmall_Throw()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(string)));
            HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownHeader, headers,
                "special");

            string[] array = new string[1];
            array[0] = null;

            collection.CopyTo(array, 0); // no exception
            Assert.Null(array[0]);

            Assert.Throws<ArgumentNullException>(() => { collection.CopyTo(null, 0); });
            Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); });
            Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); });

            headers.Add(knownHeader, "special");
            array = new string[0];
            Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });

            headers.Add(knownHeader, "special");
            headers.Add(knownHeader, "special");
            array = new string[1];
            Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });

            headers.Add(knownHeader, "value1");
            array = new string[0];
            Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });

            headers.Add(knownHeader, "value2");
            array = new string[1];
            Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 0); });

            array = new string[2];
            Assert.Throws<ArgumentException>(() => { collection.CopyTo(array, 1); });
        }
        public void CopyTo_OnlySpecialValueEmptyDestination_Copied()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.SetSpecialValue();
            headers.Add(knownHeader, specialValue.ToString());

            Uri[] array = new Uri[2];
            collection.CopyTo(array, 0);

            Assert.Equal(specialValue, array[0]);
            Assert.Equal(specialValue, array[1]);

            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
        }
        public void CopyTo_AddValuesAndSpecialValue_AllValuesCopied()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.SetSpecialValue();
            collection.Add(new Uri("http://www.example.org/3/"));

            Uri[] array = new Uri[5];
            collection.CopyTo(array, 1);

            Assert.Null(array[0]);
            Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
            Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
            Assert.Equal(specialValue, array[3]);
            Assert.Equal(new Uri("http://www.example.org/3/"), array[4]);

            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
        }
        public void RemoveSpecialValue_AddValueAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/"));
            collection.SetSpecialValue();
            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
            Assert.Equal(2, headers.GetValues(knownHeader).Count());

            collection.RemoveSpecialValue();
            Assert.False(collection.IsSpecialValueSet, "Special value is set.");
            Assert.Equal(1, headers.GetValues(knownHeader).Count());
        }
        public void GetEnumerator_AddSingleValueAndGetEnumerator_AllValuesReturned()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            collection.Add(new Uri("http://www.example.org/"));

            bool started = false;
            foreach (var item in collection)
            {
                Assert.False(started, "We have more than one element returned by the enumerator.");
                Assert.Equal(new Uri("http://www.example.org/"), item);
            }
        }
        public void RemoveSpecialValue_AddTwoValuesAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/1/"));
            collection.Add(new Uri("http://www.example.org/2/"));
            collection.SetSpecialValue();
            Assert.True(collection.IsSpecialValueSet, "Special value not set.");
            Assert.Equal(3, headers.GetValues(knownHeader).Count());

            // The difference between this test and the previous one is that HttpHeaders in this case will use
            // a List<T> to store the two remaining values, whereas in the previous case it will just store
            // the remaining value (no list).
            collection.RemoveSpecialValue();
            Assert.False(collection.IsSpecialValueSet, "Special value is set.");
            Assert.Equal(2, headers.GetValues(knownHeader).Count());
        }
        public void GetEnumerator_NoValues_EmptyEnumerator()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            IEnumerator<Uri> enumerator = collection.GetEnumerator();

            Assert.False(enumerator.MoveNext(), "No items expected in enumerator.");
        }
        public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues()
        {
            // Use different ctor overload than in previous test to make sure all ctor overloads work correctly.
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue, MockValidator);

            // When we remove 'invalidValue' our MockValidator will throw.
            Assert.Throws<MockException>(() => { collection.Remove(invalidValue); });
        }
        public void CopyTo_AddSingleValue_ContainsSingleValue()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers,
                specialValue);

            collection.Add(new Uri("http://www.example.org/"));

            Uri[] array = new Uri[1];
            collection.CopyTo(array, 0);
            Assert.Equal(new Uri("http://www.example.org/"), array[0]);

            // Now only set the special value: nothing should be added to the array.
            headers.Clear();
            headers.Add(knownHeader, specialValue.ToString());
            array[0] = null;
            collection.CopyTo(array, 0);
            Assert.Equal(specialValue, array[0]);
        }
 private static void MockValidator(HttpHeaderValueCollection<Uri> collection, Uri value)
 {
     if (value == invalidValue)
     {
         throw new MockException();
     }
 }
        public void CopyTo_EmptyToEmpty_Success()
        {
            MockHeaders headers = new MockHeaders(knownHeader, new MockHeaderParser(typeof(Uri)));
            HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownHeader, headers);

            Uri[] array = new Uri[0];
            collection.CopyTo(array, 0);
        }