상속: IDisposable
예제 #1
0
        Nancy.Response AddUser()
        {
            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            UserModel user = this.Bind <UserModel>();

            // Reject request with an ID param
            if (user.Id != null)
            {
                return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "POST", HttpStatusCode.Conflict, String.Format("Use PUT to update an existing user with Id = {0}", user.Id)));
            }

            // Save the item to the DB
            try {
                UserMapper usr_mpr = new UserMapper();
                user.CreateId();
                usr_mpr.Add(user);

                //Get new user data from DB
                UserModel      new_user = usr_mpr.GetById(user.Id);
                Nancy.Response response = Response.AsJson(new_user);
                response.StatusCode = HttpStatusCode.Created;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + user.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                Console.WriteLine(rawBody);
                String operation = String.Format("UserModule.AddItem({0})", (user == null) ? "No Model Data" : user.Username);
                return(HandleException(e, operation));
            }
        }
예제 #2
0
 /// <summary>
 /// Return image with given path
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 private object GetImageUsingPath(string path)
 {
     System.IO.Stream image = _rest.GetImageUsingPath(path);
     response = new Nancy.Response();
     response = Response.FromStream(image, "image/png");
     return(response);
 }
        Nancy.Response UpdateNotification(string id)
        {
            NotificationModel notification = null;

            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            try {
                notification = this.Bind <NotificationModel>();

                NotificationMapper not_mpr = new NotificationMapper();
                notification.Id = id;

                NotificationModel res = not_mpr.GetById(id);

                if (res == null)
                {
                    return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "GET", HttpStatusCode.NotFound, String.Format("A notification with Id = {0} does not exist", id)));
                }
                not_mpr.update(notification);

                Nancy.Response response = Response.AsJson(notification);
                response.StatusCode = HttpStatusCode.OK;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + notification.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                String operation = String.Format("NotificationModule.UpdateBadge({0})", (notification == null) ? "No Model Data" : notification.Message);
                return(HandleException(e, operation));
            }
        }
예제 #4
0
        //Common

        /// <summary>
        ///  Return image that is used as support image, images are build-in
        /// </summary>
        /// <param name="name">name of image inside resource</param>
        /// <returns></returns>
        private object GetSupportImageRest(string name)
        {
            System.IO.Stream image = _impl.GetSupportImage(name);
            response = new Nancy.Response();
            response = Response.FromStream(image, "image/png");
            return(response);
        }
예제 #5
0
        private static async Task <Nancy.Response> ProcessReadMethod(NancyModule module, string outUri, IRequestProvider requestProvider)
        {
            var result = new Nancy.Response();
            HttpResponseMessage response = null;
            var responseContent          = string.Empty;

            try
            {
                var hc = new HttpClient()
                {
                    BaseAddress = new Uri(outUri)
                };

                hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var initialPath = InputModule.GetPath(module.Context.Request);
                response = await hc.GetAsync(
                    initialPath +
                    (initialPath.Contains('?') && initialPath.Contains('=') ? "&" : "?") +
                    "userid=" +
                    await InputModule.GetUserId(module, requestProvider)
                    );

                responseContent = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();

                return(new TextResponse(HttpStatusCode.OK, responseContent));
            }
            catch (Exception ex)
            {
                result = new TextResponse(HttpStatusCode.BadRequest, (response != null) ? responseContent : ex.ToString());
            }
            return(result);
        }
        Nancy.Response AddNotification()
        {
            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            NotificationModel notification = this.Bind <NotificationModel>();

            // Reject request with an ID param
            if (notification.Id != null)
            {
                return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "POST", HttpStatusCode.Conflict, String.Format("Use PUT to update an existing notification with Id = {0}", notification.Id)));
            }

            // Save the item to the DB
            try {
                NotificationMapper not_mpr = new NotificationMapper();
                notification.CreateId();
                not_mpr.Add(notification);
                Nancy.Response response = Response.AsJson(notification);
                response.StatusCode = HttpStatusCode.Created;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + notification.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                Console.WriteLine(rawBody);
                String operation = String.Format("NotificationModule.AddItem({0})", (notification == null) ? "No Model Data" : notification.Message);
                return(HandleException(e, operation));
            }
        }
예제 #7
0
 /// <summary>
 /// Return image with given path
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 private object GetImageUsingPathRest(string path)
 {
     System.IO.Stream image = _rest.GetImageUsingPath(path);
     response = new Nancy.Response();
     response = Response.FromStream(image, MimeTypes.GetMimeType(path));
     return(response);
 }
예제 #8
0
        private Response AddObject(string bucket, string key, Stream stream)
        {
            if (Request.Url.Query == "?acl")
              {
            return new Response { StatusCode = HttpStatusCode.OK };
              }

              var content = stream.Copy(configuration.MaxBytesPerSecond);

              var s3Object = new S3Object
              {
            Bucket = bucket,
            Key = key,
            ContentType = Request.Headers.ContentType,
            CreationDate = DateTime.UtcNow,
            Content = () => content,
            ContentMD5 = content.GenerateMD5CheckSum(),
            Size = content.Length
              };

              storage.AddObject(s3Object);

              var response = new Response { StatusCode = HttpStatusCode.OK };
              response.WithHeader("ETag", string.Format("\"{0}\"", s3Object.ContentMD5));
              return response;
        }
		//	Kept seperate, as I guess more CSVs will be needed
		private static Response _initResponse()
		{
			Response response = new Response();
			response.Headers.Add("Content-Disposition", "attachment; filename=ExportedDate" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".csv");
			response.ContentType = "application/octet-stream";
			return response;
		}
        /// <summary>
        /// Generate the json documentation file.
        /// </summary>
        /// <returns></returns>
        public virtual Response GetDocumentation()
        {
            var    moduleType    = this.GetType();
            string specification = null;

            if (!cachedSpecifications.TryGetValue(moduleType, out specification))
            {
                GenerateSpecification();
                var serializerSettings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting        = Formatting.Indented,
                };

                specification = JsonConvert.SerializeObject(openApiSpecification, Formatting.None, serializerSettings);
                specification = specification.Replace("#/definitions/", "#/components/schemas/");

                cachedSpecifications[moduleType] = specification;
            }


            return(Response
                   .AsText(specification)
                   .WithContentType(CONTENT_TYPE));
        }
예제 #11
0
 public void Should_set_a_cookie_with_name_and_value()
 {
     var response = new Response();
     response.AddCookie("itsover", "9000");
     response.Cookies.Count.ShouldEqual(1);
     response.Cookies[0].ShouldEqual("itsover", "9000", null, null, null);
 }
예제 #12
0
        public AuthModule()
            : base("/api")
        {
            Post["/authenticate"] = x => {
                var bind = this.Bind<LoginRequest>();

                UserManager<User> manager = new UserManager<User>(new UserStore());

                var user = manager.Find(bind.Username, bind.Password);

                if (user == null)
                {
                    return new Response
                    {
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                }
                else
                {
                    var response = new Response
                    {
                        StatusCode = HttpStatusCode.OK
                    };
                    return response.WithCookie("sq-valid", user.UserName, DateTime.Now.AddMinutes(5));
                }
            };

            Get["/logout"] = x => {
                var response = new Response
                {
                    StatusCode = HttpStatusCode.OK
                };
                return response.WithCookie("sq-valid", null, DateTime.Now.AddYears(-5));
            };
        }
        private Response CreateDinner()
        {
            var dinner = this.Bind<Dinner>();
            nerdDinners.Dinners.Add(dinner);
            try
            {
                nerdDinners.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var message = ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage;
                var response = new Response
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Contents = stream =>
                                   {
                                       using (var writer = new StreamWriter(stream) { AutoFlush = true })
                                       {
                                           writer.WriteLine(message);
                                       }
                                   }
                };
                return response;
            }

            return new Response();
        }
예제 #14
0
 /// <summary>
 /// Return thumbnail with given ratio
 /// </summary>
 /// <param name="type"></param>
 /// <param name="id"></param>
 /// <param name="ratio"></param>
 /// <returns></returns>
 private object GetThumb(string type, string id, string ratio)
 {
     System.IO.Stream image = _rest.GetThumb(type, id, ratio);
     response = new Nancy.Response();
     response = Response.FromStream(image, "image/png");
     return(response);
 }
예제 #15
0
파일: Security.cs 프로젝트: ToJans/Nancy
        /// <summary>
        /// Gets a request hook for checking claims
        /// </summary>
        /// <param name="claims">Required claims</param>
        /// <returns>Before hook delegate</returns>
        public static Func<NancyContext, Response> RequiresClaims(IEnumerable<string> claims)
        {
            return (ctx) =>
                {
                    var failResponse = new Response() { StatusCode = HttpStatusCode.Forbidden };

                    object userClaimsObject;

                    if (!ctx.Items.TryGetValue(CLAIMS_KEY, out userClaimsObject))
                    {
                        return failResponse;
                    }

                    var userClaims = userClaimsObject as IEnumerable<string>;
                    if (userClaims == null)
                    {
                        return failResponse;
                    }

                    if (claims.Any(claim => !userClaims.Contains(claim)))
                    {
                        return failResponse;
                    }

                    return null;
                };
        }
예제 #16
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;
        }
예제 #17
0
        private Response DeleteBucket(string bucket)
        {
            storage.DeleteBucket(bucket);

              var response = new Response { StatusCode = HttpStatusCode.NoContent };
              return response;
        }
예제 #18
0
        public static Response ExportToCSV()
        {
            var calls = SupportCall.ToList();

            var response = new Response();

            response.Headers.Add("Content-Disposition", "attachment; filename=ExportedData" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".csv");


            response.Contents = stream =>
            {
                StreamWriter sw = new StreamWriter(stream);


                sw.Write("Internal Reference, Customer, Customer Reference, Customer Site, Customer Site Location, Assigned To, Product, Status, Created By, CreatedTime, Note Type, Note Sub Type, Note Text, Time Spent, Created By, Created Date Time");
                sw.Write(sw.NewLine);
                foreach (var call in calls)
                {
                    var notes = Note.LoadFromCall(call.RecordID);
                    foreach (var note in notes.OrderByDescending(x => x.CreatedDateTime).ThenByDescending(x => x.NoteType))
                    {
                        sw.Write(call.InternalReference);
                        sw.Write(",");
                        sw.Write(call.CustomerName);
                        sw.Write(",");
                        sw.Write(call.CustomerReference);
                        sw.Write(",");
                        sw.Write(call.CustomerSiteName);
                        sw.Write(",");
                        sw.Write(call.CustomerSiteLocationName);
                        sw.Write(",");
                        sw.Write(call.AssignedTo);
                        sw.Write(",");
                        sw.Write(call.ProductName);
                        sw.Write(",");
                        sw.Write(call.Status);
                        sw.Write(",");
                        sw.Write(call.CreatedBy);
                        sw.Write(",");
                        sw.Write(call.CreatedDateTime);
                        sw.Write(",");
                        sw.Write(note.NoteType);
                        sw.Write(",");
                        sw.Write(note.NoteSubType);
                        sw.Write(",");
                        sw.Write(note.NoteText);
                        sw.Write(",");
                        sw.Write(note.TimeSpent);
                        sw.Write(",");
                        sw.Write(note.CreatedBy);
                        sw.Write(",");
                        sw.Write(note.CreatedDateTime);
                        sw.Write(sw.NewLine);
                    }

                }
                sw.Close();
            };
            return response;
        }
예제 #19
0
        /// <summary>
        /// Return thumb with given id, type
        /// </summary>
        /// <param name="id">image id</param>
        /// <param name="type">image type</param>
        /// <param name="ratio">new image ratio</param>
        /// <returns>resize image body inside stream</returns>
        private object GetThumb(int type, int id, string ratio)
        {
            Nancy.Response response    = new Nancy.Response();
            string         contentType = "";

            ratio = ratio.Replace(',', '.');
            float.TryParse(ratio, System.Globalization.NumberStyles.AllowDecimalPoint,
                           System.Globalization.CultureInfo.CreateSpecificCulture("en-EN"), out float newratio);

            string path = ReturnImagePath(id, type, false);

            if (path == "")
            {
                Stream image = MissingImage();
                contentType = "image/png";
                response    = Response.FromStream(image, contentType);
            }
            else
            {
                FileStream fs = Pri.LongPath.File.OpenRead(path);
                contentType = MimeTypes.GetMimeType(path);
                System.Drawing.Image im = System.Drawing.Image.FromStream(fs);
                response = Response.FromStream(ResizeToRatio(im, newratio), contentType);
            }

            return(response);
        }
예제 #20
0
 /// <summary>
 /// Return image that is used as support image, images are build-in with given ratio
 /// </summary>
 /// <param name="name"></param>
 /// <param name="ratio"></param>
 /// <returns></returns>
 private object GetSupportImage(string name, string ratio)
 {
     System.IO.Stream image = _rest.GetSupportImage(name, ratio);
     response = new Nancy.Response();
     response = Response.FromStream(image, "image/png");
     return(response);
 }
예제 #21
0
        /// <summary>
        /// Save the session into the response
        /// </summary>
        /// <param name="session">Session to save</param>
        /// <param name="response">Response to save into</param>
        public void Save(ISession session, Nancy.Response response)
        {
            this.ExpireOldSessions();

            if (session == null || !session.HasChanged)
            {
                return;
            }

            var id = session["_id"] as string;

            if (null == id)
            {
                // TODO: warn
                return;
            }

            // Persist the session
            session.Delete("_id");
            Await(RethinkDbSessionStore.UpdateSession(currentConfiguration, id, session));

            // Encrypt the session Id in the cookie
            var cryptographyConfiguration = this.currentConfiguration.CryptographyConfiguration;
            var encryptedData             = cryptographyConfiguration.EncryptionProvider.Encrypt(id);
            var hmacBytes  = cryptographyConfiguration.HmacProvider.GenerateHmac(encryptedData);
            var cookieData = HttpUtility.UrlEncode(String.Format("{0}{1}", Convert.ToBase64String(hmacBytes), encryptedData));

            var cookie = new NancyCookie(this.currentConfiguration.CookieName, cookieData, true)
            {
                Domain = this.currentConfiguration.Domain,
                Path   = this.currentConfiguration.Path
            };

            response.WithCookie(cookie);
        }
예제 #22
0
 /// <summary>
 /// Return image with given Id type and information if its should be thumb
 /// </summary>
 /// <param name="id"></param>
 /// <param name="type"></param>
 /// <param name="thumb"></param>
 /// <returns></returns>
 private object GetImage(string id, string type, bool thumb)
 {
     System.IO.Stream image = _rest.GetImage(type, id, thumb);
     response = new Nancy.Response();
     response = Response.FromStream(image, "image/png");
     return(response);
 }
        public AuthenticateModule()
            : base("/api")
        {
            Post["/AuthenticateUser"] = parameters =>
                {
                    var bind = this.Bind<LoginRequest>();

                    //do something with request.Username and request.Password.

                    var response = new Response
                        {
                            StatusCode = HttpStatusCode.OK
                        };

                    response.AddCookie("valid", bind.Username, DateTime.Now.AddMinutes(5));
                    return response;
                };
            Get["/LogOff"] = parameters =>
                {
                    var response = new Response
                        {
                            StatusCode = HttpStatusCode.OK
                        };

                    //clear the cookie
                    response.AddCookie("valid", null, DateTime.Now.AddYears(-5));
                    return response;
                };
        }
        public static Response AsNancyResponse(this OutgoingWebResponse openauthResponse)
        {
            var response = new Response();

            var statusCode = HttpStatusCode.InternalServerError;
            string statusCodeName = null;
            if (openauthResponse.Status == System.Net.HttpStatusCode.Redirect)
            {
                statusCodeName = HttpStatusCode.TemporaryRedirect.ToString();
            }
            else
            {
                statusCodeName = openauthResponse.Status.ToString();
            }

            if (!Enum.TryParse<HttpStatusCode>(statusCodeName, out statusCode))
            {
                throw new Exception("Unknown Status Code: " + openauthResponse.Status.ToString());
            }
            response.StatusCode = statusCode;

            var headers = new Dictionary<string, string>();
            foreach(var key in openauthResponse.Headers.AllKeys)
            {
                headers.Add(key, openauthResponse.Headers[key]);
            }
            response.Headers = headers;

            var body = Encoding.UTF8.GetBytes(openauthResponse.Body);
            response.Contents = stream => stream.Write(body, 0, body.Length);

            return response;
        }
        private static Response HandleExceptions(Exception err, NancyContext ctx)
        {
            logger.Error("Failed {0} with {1}", ctx.Request.Path, err);
            var result = new Response { ReasonPhrase = err.Message };

            if (err is NotImplementedException)
            {
                result.StatusCode = HttpStatusCode.NotImplemented;
            }
            else if (err is UnauthorizedAccessException)
            {
                result.StatusCode = HttpStatusCode.Unauthorized;
            }
            else if (err is ArgumentException)
            {
                result.StatusCode = HttpStatusCode.BadRequest;
            }
            else
            {
                // An unexpected exception occurred!
                result.StatusCode = HttpStatusCode.InternalServerError;
            }

            return result;
        }
예제 #26
0
        private object GetSupportImage(string name, string ratio)
        {
            Nancy.Response response = new Nancy.Response();
            if (string.IsNullOrEmpty(name))
            {
                return(APIStatus.notFound404());
            }

            ratio = ratio.Replace(',', '.');
            float.TryParse(ratio, System.Globalization.NumberStyles.AllowDecimalPoint,
                           System.Globalization.CultureInfo.CreateSpecificCulture("en-EN"), out float newratio);

            name = Path.GetFileNameWithoutExtension(name);
            System.Resources.ResourceManager man = Resources.ResourceManager;
            byte[] dta = (byte[])man.GetObject(name);
            if ((dta == null) || (dta.Length == 0))
            {
                return(APIStatus.notFound404());
            }
            MemoryStream ms = new MemoryStream(dta);

            ms.Seek(0, SeekOrigin.Begin);
            System.Drawing.Image im = System.Drawing.Image.FromStream(ms);

            response = Response.FromStream(ResizeToRatio(im, newratio), "image/png");
            return(response);
        }
예제 #27
0
 /// <summary>
 /// Return image that is used as support image, images are build-in with given ratio
 /// </summary>
 /// <param name="name"></param>
 /// <param name="ratio"></param>
 /// <returns></returns>
 private object GetSupportImageRest(string name, string ratio)
 {
     System.IO.Stream image = _rest.GetSupportImage(name, ratio);
     response = new Nancy.Response();
     // This will always be png, so we are ok
     response = Response.FromStream(image, "image/png");
     return(response);
 }
예제 #28
0
 public void Should_set_a_cookie_with_everything()
 {
     var response = new Response();
     var date = DateTime.Now;
     response.AddCookie("itsover", "9000", date, "life", "/andeverything");
     response.Cookies.Count.ShouldEqual(1);
     response.Cookies[0].ShouldEqual("itsover", "9000", date, "life", "/andeverything");
 }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HeadResponse"/> class.
 /// </summary>
 /// <param name="response">
 /// The full response to create the head response from.
 /// </param>
 public HeadResponse(Response response)
 {
     this.Contents = GetStringContents(string.Empty);
     this.ContentType = response.ContentType;
     this.Headers = response.Headers;
     this.StatusCode = response.StatusCode;
     this.CheckAndSetContentLength(response);
 }
예제 #30
0
        public void Should_not_make_headers_null_on_new_instance()
        {
            // Given, When
            var response = new Response();

            // Then
            response.Headers.ShouldNotBeNull();
        }
예제 #31
0
        public void Should_set_content_type_to_text_html_on_new_instance()
        {
            // Given, When
            var response = new Response();

            // Then
            response.ContentType.ShouldEqual("text/html");
        }
예제 #32
0
        public void Should_set_status_code_ok_on_new_instance()
        {
            // Given, When
            var response = new Response();

            // Then
            response.StatusCode.ShouldEqual(HttpStatusCode.OK);
        }
예제 #33
0
        private Response AddBucket(string bucketName)
        {
            var bucket = new Bucket { Id = bucketName, CreationDate = DateTime.UtcNow };
              storage.AddBucket(bucket);

              var response = new Response { StatusCode = HttpStatusCode.OK };
              return response;
        }
예제 #34
0
        private Response HealthResponse()
        {
            var result = new HealthResponse {
                Response = "I am alive!"
            };

            return(Response.AsJson(result));
        }
예제 #35
0
 public void Should_set_a_cookie_with_name_and_value_and_expiry()
 {
     var response = new Response();
     var date = DateTime.Now;
     response.AddCookie("itsover", "9000", date);
     response.Cookies.Count.ShouldEqual(1);
     response.Cookies[0].ShouldEqual("itsover", "9000", date, null, null);
 }
예제 #36
0
 private static bool AlreadyGzipEncoded(Response response)
 {
     var contentEncoding = response.Headers.GetValueOrDefault("Content-Encoding");
     if (contentEncoding == "gzip")
     {
         return true;
     }
     return false;
 }
예제 #37
0
        public virtual void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            object errorHandled;
            if (context.Items.TryGetValue("ERROR_HANDLED", out errorHandled) && (errorHandled as bool? ?? false))
                return;

            object exceptionObject;
            if (!context.Items.TryGetValue("ERROR_EXCEPTION", out exceptionObject))
                return;

            var exception = UnwrapException((Exception)exceptionObject);

            // We're not that interested in Nancys exception really
            if (exception is RequestExecutionException)
                exception = exception.InnerException;

            if (exception is ResourceNotFoundException)
            {
                context.Response = new NotFoundResponse();
                return;
            }

            if (exception is ResourcePreconditionFailedException)
            {
                context.Response = new Response
                {
                    StatusCode = HttpStatusCode.PreconditionFailed,
                    ContentType = "text/html"
                };
                return;
            }

            var resp = new Response();
            object errorTrace;
            context.Items.TryGetValue("ERROR_TRACE", out errorTrace);

            resp.Contents = stream =>
            {
                using (var streamWriter = new StreamWriter(stream))
                {
                    if (exception != null)
                    {
                        streamWriter.WriteLine("Exception:");
                        streamWriter.WriteLine(exception);
                    }
                    if (errorTrace != null)
                    {
                        streamWriter.WriteLine("Trace:");
                        streamWriter.WriteLine(errorTrace);
                    }
                    streamWriter.WriteLine("Ey.. Got an exception there matey!!");
                }
            };
            resp.ContentType = "text/plain";
            resp.StatusCode = HttpStatusCode.InternalServerError;
            context.Response = resp;
        }
예제 #38
0
 private static bool ContentLengthIsTooSmall(Response response)
 {
     var contentLength = response.Headers.GetValueOrDefault("Content-Length");
     if (contentLength != null && long.Parse(contentLength) < 1024)
     {
         return true;
     }
     return false;
 }
예제 #39
0
파일: WebApi.cs 프로젝트: jbtule/PclUnit
        public PclRunnerModule()
        {
            Get["/"] = _ => "PclUnit Aggregating Runner";
            Get["/api/connect/{id}"] = _ => {
                string id = _.id;
                Console.WriteLine("Connecting:{0,15}",id);
                return "OK";
            };
            Post["/api/send_tests"] = _ => {
                var runner = this.Bind<Runner>();

                foreach (var test in runner.Assemblies.SelectMany(it=>it.Fixtures).SelectMany(it=>it.Tests))
                {
                    PlatformResults.Instance.AddTest(test, runner.Platform);
                }
                Console.WriteLine("Receiving Test List:{0,15}", runner.Platform);
                PlatformResults.Instance.ReceivedTests(runner.Platform);
                return "OK";
            };
            Post["/api/send_result"] = _ => {
                var result = this.Bind<Result>();
                var dict = PlatformResults.Instance.AddResult(result);
                PrintResults.PrintResult(dict);
                return "OK";
            };
            Get["/api/check_tests"] = _ => {
                var results = PlatformResults.Instance;
                if(results.Go){
                    var build = new StringBuilder();
                    foreach(var inc in results.Includes){
                        build.AppendFormat("++INCLUDE++{0}", inc);
                    }
                    foreach(var inc in results.Includes){
                        build.AppendFormat("++EXCLUDE++{0}", inc);
                    }
                    build.AppendLine("++READY++");
                    return build.ToString();
                }else{
                    return "++NOTREADY++";
                }
            };
            Get ["/reshare/{file*}"] = _ => {
                string path = _.file;
                var fullPath = Path.GetFullPath(PlatformResults.Instance.ResharePath);
                var fullFilePath = Path.GetFullPath(Path.Combine(fullPath, path));

                if(!fullFilePath.StartsWith(fullPath)){
                    return String.Format("Can't find file {0}" ,path);
                }
                var response = new Response();
                response.ContentType = "application/octet-stream";
                response.Contents = s => {
                    File.OpenRead(fullFilePath).CopyTo(s);
                };
                return response;
            };
        }
예제 #40
0
        /// <summary>
        /// Return thumbnail with given ratio
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <param name="ratio"></param>
        /// <returns></returns>
        private object GetThumbRest(string type, string id, string ratio)
        {
            string contentType;

            System.IO.Stream image = _rest.GetThumb(type, id, ratio, out contentType);
            response = new Nancy.Response();
            response = Response.FromStream(image, contentType);
            return(response);
        }
        public CachedResponse(Response response)
        {
            this.response = response;

            this.ContentType = response.ContentType;
            this.Headers = response.Headers;
            this.StatusCode = response.StatusCode;
            this.Contents = this.GetContents();
        }
예제 #42
0
        /// <summary>
        /// Return image with given Id type and information if its should be thumb
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="thumb"></param>
        /// <returns></returns>
        private object GetImageRest(string id, string type, bool thumb)
        {
            string contentType;

            System.IO.Stream image = _rest.GetImage(type, id, thumb, out contentType);
            response = new Nancy.Response();
            // This is not always png
            response = Response.FromStream(image, contentType);
            return(response);
        }
예제 #43
0
        /// <summary>
        /// Return image
        /// </summary>
        /// <param name="type">image type</param>
        /// <param name="id">image id</param>
        /// <returns></returns>
        private object GetImageRest(string type, string id)
        {
            response = new Nancy.Response();
            string content;
            Stream image = _rest.GetImage(type, id, false, out content);

            response = new Nancy.Response();
            response = Response.FromStream(image, content);
            return(response);
        }
        private Response processRequest(DynamicDictionary parameters, RequestDetails requestDetails, 
            Func<DataModel, DataModel> dataStorageDelegate, Func<DataModel, RequestDetails, Response> responseDelegate)
        {
            var reqDataModel = new DataModel() { Path = Request.Url };
            var response = new Response();

            //If request have parameters - construct the Path and jsonQuery for the Model (i.e. "/movies/{id}")
            if (requestDetails.Parameters != null && requestDetails.Parameters.Any())
            {
                string lastParName = requestDetails.Parameters.Last();                                  //we are assuming that the last parameter in request path is an "id" 
                string lastParValue = parameters[lastParName].Value;                                    //and we can use this parameter name and value to compose json filter for our dataStorage        

                reqDataModel.Path = reqDataModel.Path.Remove(reqDataModel.Path.Length - lastParValue.Length);                     //remove last parameter value from the "/movies/101" => "/movies/", where 101 is some "id"
                reqDataModel.jsonQuery = $"{{\"{lastParName}\":\"{lastParValue}\"}}";                                             // {"lastParameterName":"lastParameterValue"}
            }

            
            JObject reqBobyJsonObj = null;
            string reqBodyJsonStr = Request.Body.AsString();

            //if request body contains Json - we need to validate (try to parse) this Json first
            if (!String.IsNullOrEmpty(reqBodyJsonStr))
            {
                try
                {
                    reqBobyJsonObj = JObject.Parse(reqBodyJsonStr);
                }
                catch (Exception ex)
                {
                    logger.Error($"Incorrect JSON in {requestDetails.Verb.ToUpper()} request!");
                    logger.Error(ex);

                    response = "Bad Request";
                    response.StatusCode = HttpStatusCode.BadRequest;
                    return response;                                        
                }            
            }

            //If request have an associated schema - we need to validate received Json (from request body) with this schema
            if (!String.IsNullOrEmpty(requestDetails.Schema)) { 
                JSchema jsonSchema = JSchema.Parse(requestDetails.Schema);
                if (!reqBobyJsonObj?.IsValid(jsonSchema) ?? true)
                {
                    logger.Error($"JSON in {requestDetails.Verb.ToUpper()} request does not match the RAML schema!!!");
                    response.StatusCode = HttpStatusCode.UnprocessableEntity;
                    return response;
                }
            }

            reqDataModel.jsonModel = reqBodyJsonStr;
            var resultingDataModel = dataStorageDelegate(reqDataModel);
            response = responseDelegate(resultingDataModel, requestDetails);
                
            return response;
        }
        public RequestHandlerModule(IMediator mediator, RequestTypeProvider requestTypeProvider)
            : base("/RequestHandler/request")
        {
            Post["/{requestType}", true] = async (parameters, ct) =>
            {
                Console.WriteLine("Call to AsyncRequestHandlerModule");
                var requestTypeString = (string)parameters.requestType;

                var requestType = requestTypeProvider.FindByFullName(requestTypeString);

                if (requestType == null)
                {
                    return (int)HttpStatusCode.NotAcceptable;
                }

                dynamic deserializedRequest = this.Bind(requestType);

                var isAsyncRequest = requestType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IAsyncRequest<>));

                if (requestType.BaseType != typeof(object) && requestType.BaseType == typeof(FileRequest))
                {
                    var response = new Response { StatusCode = HttpStatusCode.OK, ContentType = "application/octet-stream", Contents = async s => {
                        ((FileRequest)deserializedRequest).SetStream(s);
                        if (isAsyncRequest)
                        {
                            await mediator.SendAsync(deserializedRequest);
                        }
                        else
                        {
                            mediator.Send(deserializedRequest);
                        }
                    } };

                    return response;
                }

                try
                {
                    if (isAsyncRequest)
                    {
                        return await mediator.SendAsync(deserializedRequest);
                    }

                    return mediator.Send(deserializedRequest);
                }
                catch (Exception exc)
                {
                    //todo:log, etc.
                    var errorResponse = Response.AsText(exc.Message);
                    errorResponse.StatusCode = HttpStatusCode.InternalServerError;

                    return errorResponse;
                }
            };
        }
예제 #46
0
 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");
     }
 }
예제 #47
0
        /// <summary>
        /// Return image with given path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private object GetImageUsingPath(string path)
        {
            string contentType = MimeTypes.GetMimeType(path);

            byte[] image = _image.GetImageUsingPath(path);
            Stream ms    = new MemoryStream(image);

            response = Response.FromStream(ms, contentType);
            //response = Response.FromByteArray(image, contentType);
            return(response);
        }
예제 #48
0
        private Response Handle(NancyContext context)
        {
            if (_cacheableSpecification.IsCacheable(context) && context.Request.Headers.IfModifiedSince.HasValue)
            {
                var response = new Response { ContentType = MimeTypes.GetMimeType(context.Request.Path), StatusCode = HttpStatusCode.NotModified };
                response.Headers.EnableCache();
                return response;
            }

            return null;
        }
예제 #49
0
        public void Should_set_empty_content_on_new_instance()
        {
            // Given
            var response = new Response();

            // When 
            var content = response.GetStringContentsFromResponse();

            // Then
            content.ShouldBeEmpty();
        }
예제 #50
0
        private static async Task <Nancy.Response> ProcessWriteMethod(NancyModule module, HttpMethod method, string inUri, IRequestProvider requestProvider)
        {
            var result = new Nancy.Response();
            HttpResponseMessage response = null;
            var responseContent          = string.Empty;

            try
            {
                var hc = new HttpClient()
                {
                    BaseAddress = new Uri(inUri)
                };

                string  jsonString = RequestStream.FromStream(module.Request.Body).AsString();
                dynamic jsonObj    = string.IsNullOrEmpty(jsonString) ?
                                     new ExpandoObject() :
                                     JsonConvert.DeserializeObject <ExpandoObject>(jsonString);

                jsonObj.UserId = await InputModule.GetUserId(module, requestProvider);

                var content = new StringContent(JsonConvert.SerializeObject(jsonObj));
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                var message = new HttpRequestMessage(
                    method,
                    InputModule.GetPath(module.Context.Request)
                    )
                {
                    Content = content
                };
                foreach (var kvp in module.Context.Request.Headers.ToList())
                {
                    if (Array.IndexOf(new string[] { "Content-Length", "Content-Type" }, kvp.Key) < 0)
                    {
                        message.Headers.Add(kvp.Key, string.Join(',', kvp.Value));
                    }
                }
                response = await hc.SendAsync(message);

                responseContent = await response.Content.ReadAsStringAsync();

                response.EnsureSuccessStatusCode();

                result = new TextResponse(HttpStatusCode.OK, responseContent);
            }
            catch (Exception ex)
            {
                result = new TextResponse(HttpStatusCode.BadRequest, (response != null) ? responseContent : ex.ToString());
            }
            return(result);
        }
예제 #51
0
        public Response Post(NancyContext context)
        {
            var jsonString = context.Request.Body.AsString();
            var resp       = new Nancy.Response();

            bool multiple = false;
            Dictionary <string, string> returnModifiers = null;

            foreach (string name in context.Request.Query)
            {
                if (name.StartsWith("return.", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (returnModifiers == null)
                    {
                        returnModifiers = new Dictionary <string, string>();
                    }
                    string dataType = "Rhino.Geometry." + name.Substring("return.".Length);
                    string items    = context.Request.Query[name];
                    returnModifiers[dataType] = items;
                    continue;
                }
                if (name.Equals("multiple", StringComparison.InvariantCultureIgnoreCase))
                {
                    multiple = context.Request.Query[name];
                }
            }

            object data = string.IsNullOrWhiteSpace(jsonString) ? null : Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
            var    ja   = data as Newtonsoft.Json.Linq.JArray;

            if (multiple && ja.Count > 1)
            {
                var result = new System.Text.StringBuilder("[");
                for (int i = 0; i < ja.Count; i++)
                {
                    if (i > 0)
                    {
                        result.Append(",");
                    }
                    var item = ja[i] as Newtonsoft.Json.Linq.JArray;
                    result.Append(HandlePostHelper(item, returnModifiers));
                }
                result.Append("]");
                return(result.ToString());
            }
            else
            {
                return(HandlePostHelper(ja, returnModifiers));
            }
        }
예제 #52
0
        protected Nancy.Response InSession(Nancy.Response response = null)
        {
            if (response == null)
            {
                throw new Exception("null response object");
            }

            bool a = CurrentSession.Valid;             // Этот запуск свойства создает анонима в анонимной сессии.

            activeSessions[CurrentSession.GUID] = CurrentSession;

            return(response.WithCookie(IN_SESSION_COOKIE_NAME, CurrentSession.GUID, DateTime.Today.AddYears(1)));
            // Установить "исчезновение" куки на один год вперед.
        }
예제 #53
0
        private Response FetchDateTime(bool isLongFormat)
        {
            var dateTimeString = $"{DateTime.Now.ToShortDateString()}  {DateTime.Now.ToShortTimeString()}";

            if (isLongFormat)
            {
                dateTimeString = $"{DateTime.Now.ToLongDateString()}  {DateTime.Now.ToLongTimeString()}";
            }
            var result = new HealthResponse {
                Response = dateTimeString
            };

            return(Response.AsJson(result));
        }
예제 #54
0
        private void RegisterCorsOptions(string path)
        {
            Options(path, (req) =>
            {
                var response = this.Context.Response;

                var res = new Nancy.Response();

                res.WithHeader("Access-Control-Allow-Headers", "*");
                res.WithHeader("Access-Control-Allow-Origin", "http://localhost:8080");

                this.Context.Response = res;

                return(res);
            });
        }
예제 #55
0
        private object RehashVideoLocal(string vlid)
        {
            int videoLocalID = -1;

            int.TryParse(vlid, out videoLocalID);
            response = new Nancy.Response();
            if (videoLocalID == -1)
            {
                response.StatusCode = HttpStatusCode.BadRequest;
                return(response);
            }

            _binary.RehashFile(videoLocalID);

            response.StatusCode = HttpStatusCode.OK;
            return(response);
        }
예제 #56
0
        private object CreateJsonResponse <T>(BaseResponse <T> response)
        {
            HttpStatusCode statusCode = response.StatusCode.ConvertToEnum <HttpStatusCode>();

            Nancy.Response httpResponse = null;

            if (response.IsSuccess == true)
            {
                httpResponse = Response.AsJson(response.SuccessBody, statusCode);
            }
            else
            {
                httpResponse = Response.AsJson(response.ErrorBody, statusCode);
            }

            return(httpResponse);
        }
예제 #57
0
        protected Nancy.Response InSession(Nancy.Response response = null)
        {
            if (response == null)
            {
                throw new RenderException("null response object");
            }

            if (String.IsNullOrEmpty(CurrentSession.GUID))
            {
                CurrentSession.GUID     = ImportFromAtlcomru.GetGUID();
                CurrentSession["valid"] = "false";
            }

            activeSessions[CurrentSession.GUID] = CurrentSession;

            return(response.WithCookie(IN_SESSION_COOKIE_NAME, CurrentSession.GUID));
        }
예제 #58
0
        /// <summary>
        /// Return image with given Id type and information if its should be thumb
        /// </summary>
        /// <param name="id"></param>
        /// <param name="type"></param>
        /// <param name="thumb"></param>
        /// <returns></returns>
        private object GetImage(string id, string type, string thumb)
        {
            int    imgtype = int.Parse(type);
            string contentType;
            bool   isthumb = false;

            bool.TryParse(thumb, out isthumb);

            byte[] image = _image.GetImage(id, imgtype, isthumb, out contentType);
            if (image == null || contentType == "")
            {
                return(new APIMessage(500, "Image of type not found for ID"));
            }

            Stream ms = new MemoryStream(image);

            response = Response.FromStream(ms, contentType);
            //response = Response.FromByteArray(image, contentType);
            return(response);
        }
예제 #59
0
        /// <summary>
        /// Return image with given id, type
        /// </summary>
        /// <param name="id">image id</param>
        /// <param name="type">image type</param>
        /// <returns>image body inside stream</returns>
        private object GetImage(int type, int id)
        {
            Nancy.Response response    = new Nancy.Response();
            string         contentType = "";
            string         path        = ReturnImagePath(type, id, false);

            if (path == "")
            {
                Stream image = MissingImage();
                contentType = "image/png";
                response    = Response.FromStream(image, contentType);
            }
            else
            {
                FileStream fs = Pri.LongPath.File.OpenRead(path);
                contentType = MimeTypes.GetMimeType(path);
                response    = Response.FromStream(fs, contentType);
            }

            return(response);
        }
예제 #60
-1
        public Response Convert(ProviderServiceResponse from)
        {
            if (from == null)
            {
                return null;
            }

            var to = new Response
            {
                StatusCode = (HttpStatusCode) from.Status,
                Headers = from.Headers ?? new Dictionary<string, string>()
            };

            if (from.Body != null)
            {
                HttpBodyContent bodyContent = _httpBodyContentMapper.Convert(body: from.Body, headers: from.Headers);
                to.ContentType = bodyContent.ContentType;
                to.Contents = s =>
                {
                    byte[] bytes = bodyContent.ContentBytes;
                    s.Write(bytes, 0, bytes.Length);
                    s.Flush();
                };
            }

            return to;
        }