Example #1
0
        public void Wrapper_Ctor_Converts_Null_Wrapped_Dictionary_To_Case_Insensitive_Dictionary()
        {
            _Headers = new HeadersDictionary(null);
            _Headers.Add("one", new string[] { "value" });

            Assert.AreEqual("value", _Headers["ONE"]);
        }
 protected override void Reset_To_RawStringArray()
 {
     _Headers = new HeadersDictionary()
     {
         { _Key, _RawStringArray },
     };
 }
Example #3
0
        protected override void OnAssigned(string key, string[] value)
        {
            if (!_DoingInitialCopy)
            {
                switch ((key ?? "").ToLower())
                {
                case "content-length":
                    _Response.ContentLength64 = Parser.ParseInt64(HeadersDictionary.JoinCookedHeaderValues(value)) ?? 0L;
                    break;

                case "keep-alive":
                    _Response.KeepAlive = Parser.ParseBool(HeadersDictionary.JoinCookedHeaderValues(value)) ?? true;
                    break;

                case "transfer-encoding":
                    if (
                        (value ?? new string[0])
                        .Any(r => (r ?? "").Trim().ToLower() == "chunked")
                        )
                    {
                        _Response.SendChunked = true;
                    }
                    break;

                case "www-authenticate":
                    _Response.AddHeader("WWW-Authenticate", HeadersDictionary.JoinCookedHeaderValues(value));
                    break;

                default:
                    _Response.Headers[key] = HeadersDictionary.JoinCookedHeaderValues(value);
                    break;
                }
            }
        }
Example #4
0
        public void headers_dictionary_is_case_insensitive()
        {
            var dico = HeadersDictionary.Create(new Dictionary <string, string[]> {
                ["accept"] = new[] { "application/json" }
            });

            Assert.True(dico.ContainsKey("AccePT"));
        }
Example #5
0
 protected override void Reset_To_RawStringArray()
 {
     _WrappedDictionary = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase)
     {
         { _Key, _RawStringArray },
     };
     _Headers = new HeadersDictionary(_WrappedDictionary);
 }
        public void Initialising_Dictonary_To_Null_Array_Produces_Null_Results()
        {
            _Headers = new HeadersDictionary(null);

            Assert.IsNull(_Headers[_Key]);
            Assert.IsNull(_Headers.Get(_Key));
            Assert.IsNull(_Headers.GetValues(_Key));
            Assert.IsNull(_Headers.GetCommaSeparatedValues(_Key));
        }
Example #7
0
        public void when_get_headers_item_as_string_first_is_taken()
        {
            var dico = HeadersDictionary.Create(new Dictionary <string, string[]> {
                ["accept"] = new[] { "application/json", "text/html" }
            });
            var accept = dico["accept", HeadersValueType.FirstOnly];

            Assert.Equal("application/json", accept);
        }
Example #8
0
    //Only for case when user refuse token or error.
    // public void ReopenBrowser() { OpenBrowserForRedditAuth(headers); }

    public void OpenBrowserForRedditAuth(HeadersDictionary settings)
    {
        string base_url = "https://www.reddit.com/api/v1/authorize?";
        var    sb       = new System.Text.StringBuilder(base_url);
        var    header   = string.Join("&", settings.GetFormmatedHeadersList());
        var    uri      = sb.Append(header).ToString();

        Application.OpenURL(uri);
    }
Example #9
0
        when_get_headers_item_as_string_concatenation_is_done()
        {
            var dico = HeadersDictionary.Create(new Dictionary <string, string[]> {
                ["accept"] = new[] { "application/json", "text/html" }
            });
            var accept = dico["accept", HeadersValueType.Concatened];

            Assert.Equal("application/json;text/html", accept);
        }
Example #10
0
        public void Wrapper_Ctor_Keys_Use_Whatever_Comparison_The_Original_Dictionary_Has()
        {
            var existingDictionary = new Dictionary <string, string[]>(StringComparer.Ordinal);

            _Headers = new HeadersDictionary(existingDictionary);

            _Headers.Add("one", new string[] { "value" });

            Assert.IsNull(_Headers["ONE"]);
        }
Example #11
0
        public static HeadersDictionary Create(Dictionary <string, string[]> values)
        {
            var me = new HeadersDictionary();

            foreach (var item in values)
            {
                me.Add(item.Key, item.Value);
            }
            return(me);
        }
Example #12
0
        public void GetContext_Environment_ResponseHeaders_Writes_Are_Applied_In_Real_Time()
        {
            var actualHeaders = _HttpListener.MockContext.MockResponse.Object.Headers;

            _ProcessRequestAction = (env) => {
                var headers = new HeadersDictionary((IDictionary <string, string[]>)_PipelineEnvironment[EnvironmentKey.ResponseHeaders])
                {
                    ["aB"] = "cD"
                };
                Assert.AreEqual("cD", actualHeaders.Get("aB"));
            };

            InitialiseAndStart();
        }
Example #13
0
        public void GetContext_Environment_ResponseHeaders_Is_Case_Insensitive()
        {
            _ProcessRequestAction = (env) => {
                var headers = new HeadersDictionary((IDictionary <string, string[]>)_PipelineEnvironment[EnvironmentKey.ResponseHeaders])
                {
                    ["aB"] = "cD"
                };
            };

            InitialiseAndStart();

            var headers = new HeadersDictionary((IDictionary <string, string[]>)_PipelineEnvironment[EnvironmentKey.ResponseHeaders]);

            Assert.AreEqual("cD", headers["Ab"]);
        }
Example #14
0
        /// <summary>
        /// Creates a new object.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="collection"></param>
        public HeadersWrapper_Response(IHttpListenerResponse response) : base(StringComparer.OrdinalIgnoreCase)
        {
            _Response = response;

            _DoingInitialCopy = true;
            try {
                foreach (var key in response.Headers.AllKeys)
                {
                    var value = response.Headers[key];
                    base[key] = HeadersDictionary.SplitRawHeaderValue(value).ToArray();
                }
            } finally {
                _DoingInitialCopy = false;
            }
        }
Example #15
0
 /// <summary>
 /// See interface docs.
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public virtual string[] this[string key]
 {
     get {
         var headerValue = _Collection[key];
         return(headerValue == null
             ? null
             : HeadersDictionary.SplitRawHeaderValue(headerValue)?.ToArray());
     }
     set {
         if (key == null)
         {
             throw new ArgumentNullException(nameof(key));
         }
         _Collection[key] = HeadersDictionary.JoinCookedHeaderValues(value);
     }
 }
Example #16
0
        public static async Task <T> ApiAction <T>(Uri uri, Method method, object obj, Dictionary <string, string> sHeader)//method you need to use if you have to add body to request
        {
            var request = new RestRequest(uri, method);

            request.AddJsonBody(obj);//or you could use AddXMLBody or even AddBody

            foreach (var v in sHeader.ToList())
            {
                request.AddHeader(v.Key, v.Value);
            }
            foreach (var v in HeadersDictionary.ToList())
            {
                request.AddHeader(v.Key, v.Value);
            }

            return(await ApiAction <T>(request));
        }
Example #17
0
    /// <summary>
    /// Only for data look like this "data=data&info=info"
    /// </summary>
    /// <returns></returns>
    public static HeadersDictionary GetHeadersFromUriData(this string text)
    {
        if (!text.Contains("&"))
        {
            return(null);
        }
        try {
            HeadersDictionary headers = new HeadersDictionary();

            foreach (var s in text.Split('&'))
            {
                var index = s.Split('=');
                headers.Add(index[0], index[1]);
            }
            return(headers);
        }
        catch (Exception e) { Debug.LogError(e); }

        return(null);
    }
Example #18
0
        public static async Task <T> ApiAction <T>(Uri uri, Method method, Dictionary <string, string> parameters,
                                                   Dictionary <string, string> sHeader)
        {
            var request = new RestRequest(uri, method);

            foreach (var p in parameters)
            {
                request.AddParameter(p.Key, p.Value);
            }

            foreach (var v in sHeader.ToList())
            {
                request.AddHeader(v.Key, v.Value);
            }
            foreach (var v in HeadersDictionary.ToList())
            {
                request.AddHeader(v.Key, v.Value);
            }

            return(await ApiAction <T>(request));
        }
Example #19
0
        public void Dictionary_Wrapper_Properties_Expose_Wrappers_Correctly(string wrapperPropertyName, string headersPropertyName, string environmentKey, Type wrapperType)
        {
            var wrapperPropertyInfo = typeof(OwinContext).GetProperty(wrapperPropertyName);
            var headersPropertyInfo = typeof(OwinContext).GetProperty(headersPropertyName);

            // If the headers are null then the wrapper is null (cannot expose a stub, it would not reflect environment)
            Assert.IsNull(wrapperPropertyInfo.GetValue(_Context, null));

            // Can assign wrapper to underlying headers property and wrapper property will expose same object, it will
            // not create a new wrapper for it.
            var wrapper = Activator.CreateInstance(wrapperType);

            headersPropertyInfo.SetValue(_Context, wrapper);
            Assert.AreSame(wrapper, wrapperPropertyInfo.GetValue(_Context, null));
            Assert.AreSame(wrapper, wrapperPropertyInfo.GetValue(_Context, null));

            TestInitialise();

            // If the headers property is a simple dictionary then a wrapper will be created for it and subsequent
            // fetches return the same wrapper
            var d1 = new HeadersDictionary();

            _Environment[environmentKey] = d1;
            var w1 = wrapperPropertyInfo.GetValue(_Context, null);

            Assert.AreSame(wrapperType, w1.GetType());
            Assert.AreSame(w1, wrapperPropertyInfo.GetValue(_Context, null));

            // If the underlying headers are changed then a new wrapper is created
            var d2 = new HeadersDictionary();

            _Environment[environmentKey] = d2;
            var w2 = wrapperPropertyInfo.GetValue(_Context, null);

            Assert.AreSame(wrapperType, w2.GetType());
            Assert.AreSame(w2, wrapperPropertyInfo.GetValue(_Context, null));
        }
        public void Static_SplitRawHeaderValue_Round_Trips_With_JoinCookedHeaderValues(string [] splitValues, string headerValue)
        {
            var splitHeaderValues = HeadersDictionary.SplitRawHeaderValue(headerValue);

            if (splitValues == null)
            {
                Assert.IsNull(splitHeaderValues);
            }
            else
            {
                Assert.IsTrue(splitValues.SequenceEqual(splitHeaderValues));
            }

            var rejoinedHeader = HeadersDictionary.JoinCookedHeaderValues(splitHeaderValues);

            if (headerValue == null)
            {
                Assert.IsNull(rejoinedHeader);
            }
            else
            {
                Assert.AreEqual(headerValue, rejoinedHeader);
            }
        }
        public void Static_SplitRawHeaderValue_Returns_Correct_Array_For_Header_Value(string[] expected, string rawString)
        {
            var actual = HeadersDictionary.SplitRawHeaderValue(rawString);

            Assert.IsTrue(expected.SequenceEqual(actual));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WebDavResponse"/> class.
 /// </summary>
 /// <param name="dispatcher">The WebDAV HTTP method dispatcher</param>
 /// <param name="response">The ASP.NET Core HTTP response</param>
 public WebDavResponse(IWebDavDispatcher dispatcher, HttpResponse response)
 {
     _response  = response;
     Dispatcher = dispatcher;
     Headers    = new HeadersDictionary(_response.Headers);
 }
Example #23
0
        /// <summary>
        /// Downloads the tile image using the URL values passed across.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="urlValues"></param>
        /// <param name="clientEndpoint"></param>
        /// <param name="headers"></param>
        /// <param name="outcome"></param>
        /// <param name="displayOutcome"></param>
        /// <returns></returns>
        private void FetchTileServerImage(Options options, FakeUrlEncodedValues urlValues, IPAddress clientEndpoint, HeadersDictionary headers, WebRequestOutcome outcome, RequestOutcome displayOutcome)
        {
            var tileServerSettings = Plugin.TileServerSettingsManagerWrapper.GetRealTileServerSettings(
                urlValues.MapProvider,
                urlValues.Name
                );

            if (tileServerSettings != null)
            {
                var tileImageUrl = _TileServerUrlTranslator.ExpandUrlParameters(
                    tileServerSettings.Url,
                    urlValues,
                    tileServerSettings.Subdomains
                    );

                var request = (HttpWebRequest)HttpWebRequest.Create(tileImageUrl);
                request.Method = "GET";
                request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                foreach (var headerKey in headers.Keys)
                {
                    var value = headers[headerKey];
                    switch (headerKey.ToLower())
                    {
                    case "accept":              request.Accept = value; break;

                    case "accept-encoding":     break;

                    case "connection":          break;

                    case "content-length":      break;

                    case "content-type":        request.ContentType = value; break;

                    case "date":                break;

                    case "expect":              request.Expect = value; break;

                    case "host":                break;

                    case "if-modified-since":   break;

                    case "proxy-connection":    break;

                    case "range":               break;

                    case "referer":             request.Referer = value; break;

                    case "transfer-encoding":   request.TransferEncoding = value; break;

                    case "user-agent":          request.UserAgent = value; break;

                    default:
                        request.Headers[headerKey] = value;
                        break;
                    }
                }
                request.AuthenticationLevel   = AuthenticationLevel.None;
                request.Credentials           = null;
                request.UseDefaultCredentials = false;
                request.KeepAlive             = true;
                request.Timeout = 1000 * options.TileServerTimeoutSeconds;

                lock (_SyncLock) {
                    if (!_TileServerNameToCookieCollection.TryGetValue(urlValues.Name, out var cookies))
                    {
                        cookies = new CookieCollection();
                        _TileServerNameToCookieCollection.Add(urlValues.Name, cookies);
                    }
                    foreach (Cookie cookie in cookies)
                    {
                        request.CookieContainer.Add(cookie);
                    }
                }

                var forwarded = request.Headers["Forwarded"] ?? "";
                if (forwarded.Length > 0)
                {
                    forwarded = $"{forwarded}, ";
                }
                forwarded = $"{forwarded}for={clientEndpoint}";
                request.Headers["Forwarded"] = forwarded;

                try {
                    using (var response = (HttpWebResponse)request.GetResponse()) {
                        using (var memoryStream = new MemoryStream()) {
                            using (var responseStream = response.GetResponseStream()) {
                                var buffer    = new byte[1024];
                                var bytesRead = 0;
                                do
                                {
                                    bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                                    if (bytesRead > 0)
                                    {
                                        memoryStream.Write(buffer, 0, bytesRead);
                                    }
                                } while(bytesRead > 0);
                            }

                            outcome.ImageBytes = memoryStream.ToArray();
                            displayOutcome.FetchedFromTileServer        = true;
                            displayOutcome.TileServerResponseStatusCode = (int)response.StatusCode;
                        }

                        var cookies = new CookieCollection();
                        foreach (Cookie cookie in response.Cookies)
                        {
                            cookies.Add(cookie);
                        }
                        lock (_SyncLock) {
                            _TileServerNameToCookieCollection[urlValues.Name] = cookies;
                        }
                    }
                } catch (WebException ex) {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        displayOutcome.TimedOut = true;
                    }
                    else
                    {
                        displayOutcome.WebExceptionErrorMessage = ex.Message;

                        outcome.StatusCode = HttpStatusCode.InternalServerError;
                        if (ex.Response is HttpWebResponse httpResponse)
                        {
                            if (httpResponse.StatusCode != HttpStatusCode.OK)
                            {
                                outcome.StatusCode = httpResponse.StatusCode;
                                displayOutcome.TileServerResponseStatusCode = (int)httpResponse.StatusCode;
                            }
                        }
                    }
                }
            }
        }
 public void TestInitialise()
 {
     _Headers = new HeadersDictionary();
 }
        public void Static_JoinCookedHeaderValues_Ignores_Null_And_Empty_Values(string[] rawStringArray, string expected)
        {
            var actual = HeadersDictionary.JoinCookedHeaderValues(rawStringArray);

            Assert.AreEqual(expected, actual);
        }
Example #26
0
 public void Wrapper_Ctor_Accepts_Null_Wrapped_Dictionary()
 {
     _Headers = new HeadersDictionary(null);
     Assert.AreEqual(0, _Headers.Count);
 }
Example #27
0
 public void TestInitialise()
 {
     _WrappedDictionary = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
     _Headers           = new HeadersDictionary(_WrappedDictionary);
 }