Exemple #1
0
 private string Nachricht_aus_Request_extrahieren(Request request)
 {
     using (var sr = new StreamReader(Request.Body))
     {
         return sr.ReadToEnd();
     }
 }
 public static void PublicEndpoint(this Response response, Request request)
 {
     response
         .WithHeader("Access-Control-Allow-Origin", "*")
         .WithHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE, GET")
         .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type, X-Requested-With");
 }
Exemple #3
0
        private Response CompressResponse(Request request, Response response)
        {
            if (!response.ContentType.Contains("image")
                && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))
                && (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip"))
            {
                var data = new MemoryStream();
                response.Contents.Invoke(data);
                data.Position = 0;
                if (data.Length < 1024)
                {
                    response.Contents = stream =>
                    {
                        data.CopyTo(stream);
                        stream.Flush();
                    };
                }
                else
                {
                    response.Headers["Content-Encoding"] = "gzip";
                    response.Contents = s =>
                    {
                        var gzip = new GZipStream(s, CompressionMode.Compress, true);
                        data.CopyTo(gzip);
                        gzip.Close();
                    };
                }
            }

            return response;
        }
        private static string ExtractTokenFromHeader(Request request)
        {
            var authorization =
                request.Headers.Authorization;

            if (string.IsNullOrEmpty(authorization))
            {
                return null;
            }

            if (!authorization.StartsWith(Scheme))
            {
                return null;
            }

            try
            {
                var encodedToken = authorization.Substring(Scheme.Length).Trim();
                return String.IsNullOrWhiteSpace(encodedToken) ? null : encodedToken;
            }
            catch (FormatException)
            {
                return null;
            }
        }
Exemple #5
0
        public static Format[] Formats(Request request)
        {
            var dictionary = request.Form as IDictionary<string, object>;
            string name = "{0}.Name";
            string legality = "{0}.Legality";

            string[] keys = dictionary.Select(x => x.Key)
                .Where(x => x.StartsWith("Format"))
                .ToArray();

            keys = keys.Select(x => x.Substring(0,x.IndexOf('.'))).Distinct().ToArray();

            List<Format> formats = new List<Format>();

            if(keys != null && keys.Length > 0)
            {
                keys = keys.OrderBy(x => x).ToArray();

                foreach(string key in keys)
                {
                    formats.Add(new Format(){
                        Name = dictionary[string.Format(name, key)].ToString(),
                        Legality = dictionary[string.Format(legality, key)].ToString()
                    });
                }
            }

            return formats.ToArray();
        }
Exemple #6
0
        public static Ruling[] Rulings(Request request)
        {
            var dictionary =    request.Form as IDictionary<string, object>;
            string releasedAt = "{0}.ReleasedAt";
            string rule =       "{0}.Rule";

            string[] keys = dictionary.Select(x => x.Key)
                .Where(x => x.StartsWith("Ruling"))
                .ToArray();

            keys = keys.Select(x => x.Substring(0,x.IndexOf('.'))).Distinct().ToArray();

            List<Ruling> rulings = new List<Ruling>();

            if(keys != null && keys.Length > 0)
            {
                keys = keys.OrderBy(x => x).ToArray();

                foreach(string key in keys)
                {
                    rulings.Add(new Ruling(){
                        ReleasedAt =  DateTime.Parse(dictionary[string.Format(releasedAt, key)].ToString()),
                        Rule = dictionary[string.Format(rule, key)].ToString()
                    });
                }
            }

            return rulings.ToArray();
        }
        public ProviderServiceRequest Convert(Request from)
        {
            if (from == null)
            {
                return null;
            }
                
            var httpVerb = _httpVerbMapper.Convert(from.Method.ToUpper());

            var to = new ProviderServiceRequest
            {
                Method = httpVerb,
                Path = from.Path,
                Query = !String.IsNullOrEmpty(from.Url.Query) ? from.Url.Query.TrimStart('?') : null
            };

            if (from.Headers != null && from.Headers.Any())
            {
                var fromHeaders = from.Headers.ToDictionary(x => x.Key, x => String.Join(", ", x.Value));
                to.Headers = fromHeaders;
            }

            if (from.Body != null && from.Body.Length > 0)
            {
                var content = ConvertStreamToString(from.Body);
                var httpBodyContent = _httpBodyContentMapper.Convert(content, to.Headers);

                to.Body = httpBodyContent.Body;
            }

            return to;
        }
        public void Should_have_a_file_with_the_correct_data_in_it()
        {
            // Given
            var expected = "wazaa";

            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
            {
                { "sample.txt", new Tuple<string, string, string>("content/type", expected, "name")}
            }));

            var headers = new Dictionary<string, IEnumerable<string>>
            {
                { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
            };

            // When
            var request = new Request("POST", "/", headers, CreateRequestStream(stream), "http");

            // Then
            var fileValue = request.Files.Single().Value;
            var actualBytes = new byte[fileValue.Length];
            fileValue.Read(actualBytes, 0, (int)fileValue.Length);

            var actual = Encoding.ASCII.GetString(actualBytes);

            actual.ShouldEqual(expected);
        }
        public void If_the_stream_ends_with_carriage_return_characters_it_should_not_affect_the_multipart()
        {
            // Given
            var expected = "#!/usr/bin/env rake\n# Add your own tasks in files placed in lib/tasks ending in .rake,\n# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.\n\nrequire File.expand_path('../config/application', __FILE__)\n\nOnlinebackupWebclient::Application.load_tasks";
            var data = string.Format("--69989\r\nContent-Disposition: form-data; name=\"Stream\"; filename=\"Rakefile\"\r\nContent-Type: text/plain\r\n\r\n{0}\r\n--69989--\r\n", expected);
            var stream = new MemoryStream(Encoding.ASCII.GetBytes(data));

            var headers = new Dictionary<string, IEnumerable<string>>
            {
                {"Content-Type", new [] { "multipart/form-data; boundary=69989"} },
                {"Content-Length", new [] {"403"} }
            };

            // When
            var request = new Request("POST", "/", headers, CreateRequestStream(stream), "http");

            // Then
            var fileValue = request.Files.Single().Value;
            var actualBytes = new byte[fileValue.Length];
            fileValue.Read(actualBytes, 0, (int)fileValue.Length);

            var actual = Encoding.ASCII.GetString(actualBytes);

            actual.ShouldEqual(expected);
        }
Exemple #10
0
        public void Should_preserve_the_content_of_the_file_even_though_there_is_data_at_the_end_of_the_multipart()
        {
            // Given
            var expected = "wazaa";

            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
            {
                { "sample.txt", new Tuple<string, string, string>("content/type", expected, "name")}
            }, null, "epilogue"));

            var headers = new Dictionary<string, IEnumerable<string>>
            {
                { "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
            };

            // When
            var request = new Request("POST", new Url { Path = "/" }, CreateRequestStream(stream), headers);
            
            // Then
            var fileValue = request.Files.Single().Value;
            var actualBytes = new byte[fileValue.Length];
            fileValue.Read(actualBytes, 0, (int)fileValue.Length);

            var actual = Encoding.ASCII.GetString(actualBytes);

            actual.ShouldEqual(expected);
        }
		private void configureResponse(ResponseFormat expectedFormat)
		{
			Request req;
			var url = new Url { Scheme = "http", Path = "/" };
			switch (expectedFormat)
			{
				case ResponseFormat.Html:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptHtmlHeaders } },
									  null);
					break;
				case ResponseFormat.Json:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptJsonHeaders } },
									  null);
					break;
				case ResponseFormat.Xml:
					req = new Request("GET", url, null, new Dictionary<string, IEnumerable<string>> { { "Accept", _acceptXmlHeaders } },
									  null);
					break;
				default:
					Assert.Fail("Invalid response format");
					return;
			}

			_euclidApi.Context = new NancyContext { Request = req };
			_euclidApi.Response = _formatter;
			A.CallTo(() => _formatter.Context).Returns(_euclidApi.Context);
		}
        public void Create_WithRequest_CallsMockContentServiceAndAssignsRequestResponsePairsOnNancyContextItem()
        {
            var request = new Request("GET", "/events", "HTTP");
            var requestResponsePairs = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction() { Request = new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/events" }, Response = new ProviderServiceResponse() },
                new ProviderServiceInteraction() { Request = new ProviderServiceRequest { Method = HttpVerb.Post, Path = "/events" }, Response = new ProviderServiceResponse() },
            };

            var mockMockContextService = Substitute.For<IMockContextService>();
            var mockCultureService = Substitute.For<ICultureService>();
            var mockRequestTraceFactory = Substitute.For<IRequestTraceFactory>();
            var mockTextResource = Substitute.For<ITextResource>();

            mockMockContextService.GetExpectedRequestResponsePairs().Returns(requestResponsePairs);

            INancyContextFactory nancyContextFactory = new PactAwareContextFactory(
                mockMockContextService,
                mockCultureService,
                mockRequestTraceFactory,
                mockTextResource);

            var context = nancyContextFactory.Create(request);

            Assert.Equal(requestResponsePairs, context.Items["PactMockInteractions"]);
            mockMockContextService.Received(1).GetExpectedRequestResponsePairs();
        }
        public void Base_uri_should_contain_request_base_path()
        {
            var request = new Request("method", new Url {HostName = "host", Path = "path", BasePath = "/basePath"});

              var baseUri = request.BaseUri();

              Assert.That(baseUri, Is.StringContaining("http://host/basePath"));
        }
 protected static void InitNerdBeers()
 {
     var bs = new Org.NerdBeers.Specs.Modules.SpecBootStrapper();
     bs.Initialise();
     Engine = bs.GetEngine();
     DB = bs.DB;
     Req = null;
 }
 /// <summary>
 /// Handles an incoming <see cref="Request"/> async.
 /// </summary>
 /// <param name="nancyEngine">The <see cref="INancyEngine"/> instance.</param>
 /// <param name="request">An <see cref="Request"/> instance, containing the information about the current request.</param>
 /// <param name="onComplete">Delegate to call when the request is complete</param>
 /// <param name="onError">Deletate to call when any errors occur</param>
 public static void HandleRequest(
     this INancyEngine nancyEngine,
     Request request,
     Action<NancyContext> onComplete,
     Action<Exception> onError)
 {
     HandleRequest(nancyEngine, request, null, onComplete, onError, CancellationToken.None);
 }
        public void Base_uri_should_contain_restbuckson_net_if_host_is_not_provided()
        {
            var request = new Request("method", new Url {HostName = "", Path = "path"});

              var baseUri = request.BaseUri();

              Assert.That(baseUri, Is.StringContaining("http://restbuckson.net"));
        }
        public bool IsSessionHijacked(Request request)
        {
            if (!_sessionDetector.IsInSession(request)) return false;
              // ToDo: use real cookie name
              var secureCookie = _cookieReader.Read(request, "_nsid");

              return (secureCookie == null || !secureCookie.IsSecured || secureCookie.Hash != _hashGenerator.GenerateHash(request));
        }
        public void Base_uri_should_contain_request_port_if_present()
        {
            var request = new Request("method", new Url {HostName = "host", Port = 8000, Path = "path"});

              var baseUri = request.BaseUri();

              Assert.That(baseUri, Is.StringContaining("http://host:8000"));
        }
 public string Get(Request request)
 {
     using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
     {
         var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(request.Url.ToString()));
         return Convert.ToBase64String(hash);
     }
 }
        public void Base_uri_should_contain_request_scheme()
        {
            var request = new Request("method", "path", "scheme");

              var baseUri = request.BaseUri();

              Assert.That(baseUri, Is.StringStarting("scheme://"));
        }
 public static string GetBodyAsString(Request response)
 {
     using (var contentsStream = new MemoryStream())
     {
         response.Body.Position = 0;
         using (var streamReader = new StreamReader(response.Body))
             return streamReader.ReadToEnd();
     }
 }
 /// <summary>
 /// Handles an incoming <see cref="Request"/>.
 /// </summary>
 /// <param name="nancyEngine">The <see cref="INancyEngine"/> instance.</param>
 /// <param name="request">An <see cref="Request"/> instance, containing the information about the current request.</param>
 /// <param name="preRequest">Delegate to call before the request is processed</param>
 /// <returns>A <see cref="NancyContext"/> instance containing the request/response context.</returns>
 public static NancyContext HandleRequest(this INancyEngine nancyEngine, Request request, Func<NancyContext, NancyContext> preRequest)
 {
     var task = nancyEngine.HandleRequest(request, preRequest, CancellationToken.None);
     task.Wait();
     if (task.IsFaulted)
     {
         throw task.Exception ?? new Exception("Request task faulted");
     }
     return task.Result;
 }
Exemple #23
0
 public static CandidateModel CreateCandidateDataFromRequest(Request request)
 {
     return new CandidateModel
     {
         FirstName = request.Form.ContainsKey("firstname") ? request.Form["firstname"] : string.Empty,
         LastName = request.Form.ContainsKey("lastname") ? request.Form["lastname"] : string.Empty,
         Address = request.Form.ContainsKey("address") ? request.Form["address"] : string.Empty,
         Skills = request.Form.ContainsKey("skills[]") ? SplitToSkills(request.Form["skills[]"]) : new List<string>()
     };
 }
        public static Negotiator WithModelAppendedRestfulUrls(this Negotiator negotiator, IEnumerable<Message> messages, Request request)
        {
            string baseUrl = request.Url.SiteBase + request.Url.BasePath;

            foreach (var message in messages)
            {
                message.Url = baseUrl + "/messages/" + message.Id;
            }

            return negotiator.WithModel(messages);
        }
        public static ILandingResponse LandOn(this ILandingProvider landingProvider,  Request rq)
        {
            var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (var pair in rq.Query as IDictionary<string, object>) parameters[pair.Key] = (pair.Value as dynamic).Value as string;
            if (rq.Method == "POST")
            {
                foreach (var pair in rq.Form as IDictionary<string, object>) parameters[pair.Key] = (pair.Value as dynamic).Value as string;
            }

            return landingProvider.LandOn(parameters);
        }
 private static string GetRequestPathAndQuery(Request request)
 {
     if (request.Url.Query.IsNotNullOrWhiteSpace())
     {
         return string.Concat(request.Url.Path, "?", request.Url.Query);
     }
     else
     {
         return request.Url.Path;
     }
 }
Exemple #27
0
        internal static Guid SessionIdFromRequest(Request request)
        {
            Guid sessionId;
            string input = request.Headers["SessionId"].FirstOrDefault();
            if (String.IsNullOrEmpty(input) || !Guid.TryParse(input, out sessionId))
            {
                sessionId = Guid.NewGuid();
            }

            return sessionId;
        }
        public void StripHashFromCookie(Request request)
        {
            if (!_sessionDetector.IsInSession(request)) return;

              // ToDo: use real cookie name
              var secureCookie = _secureSessionCookieReader.Read(request, "_nsid");
              if (secureCookie == null) return;

              // ToDo: use real cookie name
              request.Cookies["_nsid"] = secureCookie.SessionId;
        }
 private static void UpdateResponseHeaders(Request request, Response response, CorsConfiguration corsConfiguration)
 {
     if (!request.Headers.Keys.Contains("Origin")) return;
     response.WithHeader("Access-Control-Allow-Origin", corsConfiguration.AllowOrigin);
     if (request.Method.Equals("OPTIONS"))
     {
         response
             .WithHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
             .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
     }
 }
        /// <summary>
        /// Create a new NancyContext
        /// </summary>
        /// <returns>NancyContext instance</returns>
        public NancyContext Create(Request request)
        {
            var nancyContext = new NancyContext();

            nancyContext.Request = request;

            nancyContext.Culture = this.cultureService.DetermineCurrentCulture(nancyContext);

            nancyContext.Trace.TraceLog.WriteLog(s => s.AppendLine("New Request Started"));

            return nancyContext;
        }
Exemple #31
0
        static public string makeXML_FromRequestData(string root, Nancy.Request Request)
        {
            string retval = string.Empty;

            foreach (string key in Request.Form.Keys)
            {
                string val  = Request.Form[key];
                string pair = string.Format("<{0}>{1}</{0}>", key, Request.Form[key]);
                retval += pair;
                retval += "\n";
            }

            retval = string.Format("<{0}>\n{1}\n </{0}>\n", root, retval);

            return(retval);
        }
Exemple #32
0
        private string makeXML_InitalContract(string root, Nancy.Request request)
        {
            return(mynancy.MyNancy.makeXML_FromRequestData(root, Request));

            //string retval = string.Empty;

            //foreach (string key in Request.Form.Keys)
            //{
            //    string val = Request.Form[key];
            //    string pair = string.Format("<{0}>{1}</{0}>", key, Request.Form[key]);
            //    retval += pair;
            //    retval += "\n";
            //}

            //retval = string.Format("<{0}>\n{1}\n </{0}>\n", root, retval);

            //return retval;
        }
Exemple #33
0
 private static string GetPath(Nancy.Request request)
 {
     return(request.Url.ToString().Substring(request.Url.ToString().IndexOf(request.Path)));
 }
Exemple #34
0
 /// <summary>
 /// Handles an incoming <see cref="Request"/>.
 /// </summary>
 /// <param name="request">An <see cref="Request"/> instance, containing the information about the current request.</param>
 /// <returns>A <see cref="NancyContext"/> instance containing the request/response context.</returns>
 public NancyContext HandleRequest(Request request)
 {
     return this.HandleRequest(request, context => context);
 }
Exemple #35
0
 private Result DoLogin(Nancy.Request req)
 {
     return(Result.Success("{UserName:'******', passwd:'1111'}"));
 }
Exemple #36
0
 private Result DoLogout(Nancy.Request req)
 {
     return(Result.Success(""));
 }
 public CoapDotNetHttpRequest(Request request, string url)
 {
     _request = request;
     _url     = url;
 }
Exemple #38
0
        private Stream StreamFromIFile(InfoResult r, bool?autowatch)
        {
            Nancy.Request request = RestModule.CurrentModule.Request;

            FileSystemResult <Stream> fr = r.File.OpenRead();

            if (fr == null || !fr.IsOk)
            {
                return(new StreamWithResponse(HttpStatusCode.InternalServerError,
                                              "Unable to open file '" + r.File.FullName + "': " + fr?.Error));
            }
            Stream org       = fr.Result;
            long   totalsize = org.Length;
            long   start     = 0;
            long   end       = totalsize - 1;

            string rangevalue = request.Headers["Range"].FirstOrDefault() ?? request.Headers["range"].FirstOrDefault();

            rangevalue = rangevalue?.Replace("bytes=", string.Empty);
            bool range = !string.IsNullOrEmpty(rangevalue);

            if (range)
            {
                // range: bytes=split[0]-split[1]
                string[] split = rangevalue.Split('-');
                if (split.Length == 2)
                {
                    // bytes=-split[1] - tail of specified length
                    if (string.IsNullOrEmpty(split[0]) && !string.IsNullOrEmpty(split[1]))
                    {
                        long e = long.Parse(split[1]);
                        start = totalsize - e;
                        end   = totalsize - 1;
                    }
                    // bytes=split[0] - split[0] to end of file
                    else if (!string.IsNullOrEmpty(split[0]) && string.IsNullOrEmpty(split[1]))
                    {
                        start = long.Parse(split[0]);
                        end   = totalsize - 1;
                    }
                    // bytes=split[0]-split[1] - specified beginning and end
                    else if (!string.IsNullOrEmpty(split[0]) && !string.IsNullOrEmpty(split[1]))
                    {
                        start = long.Parse(split[0]);
                        end   = long.Parse(split[1]);
                        if (start > totalsize - 1)
                        {
                            start = totalsize - 1;
                        }
                        if (end > totalsize - 1)
                        {
                            end = totalsize - 1;
                        }
                    }
                }
            }
            var outstream = new SubStream(org, start, end - start + 1);
            var resp      = new StreamWithResponse {
                ContentType = r.Mime
            };

            resp.Headers.Add("Server", ServerVersion);
            resp.Headers.Add("Connection", "keep-alive");
            resp.Headers.Add("Accept-Ranges", "bytes");
            resp.Headers.Add("Content-Range", "bytes " + start + "-" + end + "/" + totalsize);
            resp.ContentLength = end - start + 1;

            resp.ResponseStatus = range ? HttpStatusCode.PartialContent : HttpStatusCode.OK;

            if (r.User != null && autowatch.HasValue && autowatch.Value && r.VideoLocal != null)
            {
                outstream.CrossPosition         = (long)(totalsize * WatchedThreshold);
                outstream.CrossPositionCrossed +=
                    (a) =>
                {
                    Task.Factory.StartNew(() => { r.VideoLocal.ToggleWatchedStatus(true, r.User.JMMUserID); },
                                          new CancellationToken(),
                                          TaskCreationOptions.LongRunning, TaskScheduler.Default);
                };
            }
            resp.Stream = outstream;
            return(resp);
        }
Exemple #39
0
 /// <summary>
 /// Handles an incoming <see cref="Request"/> async.
 /// </summary>
 /// <param name="request">An <see cref="Request"/> instance, containing the information about the current request.</param>
 /// <param name="onComplete">Delegate to call when the request is complete</param>
 /// <param name="onError">Deletate to call when any errors occur</param>
 public void HandleRequest(Request request, Action<NancyContext> onComplete, Action<Exception> onError)
 {
     this.HandleRequest(request, context => context, onComplete, onError);
 }