public JsonFormatterExtensionsFixtures()
 {
     this.formatter = A.Fake<IResponseFormatter>();
     this.model = new Person { FirstName = "Andy", LastName = "Pike" };
     DefaultSerializersStartup.JsonSerializer = new DefaultJsonSerializer();
     this.response = this.formatter.AsJson(model);
 }
 public JsonFormatterExtensionsFixtures()
 {
     this.formatter = A.Fake<IResponseFormatter>();
     A.CallTo(() => this.formatter.Serializers).Returns(new[] { new DefaultJsonSerializer() });
     this.model = new Person { FirstName = "Andy", LastName = "Pike" };
     this.response = this.formatter.AsJson(model);
 }
Ejemplo n.º 3
0
		public static Response CreateResponse(this Exception e, ResponseFormat format, IResponseFormatter formatter)
		{
			// dumb ugliness b/c MSFT's xml serializer can't handle anonymous objects
			var exception = new FormattedException
			                	{
			                		name = e.GetType().Name,
			                		message = e.Message,
			                		callStack = e.StackTrace
			                	};

			Response r;
			switch (format)
			{
				case ResponseFormat.Json:
					r = formatter.AsJson(exception, HttpStatusCode.InternalServerError);
					break;
				case ResponseFormat.Xml:
					r = formatter.AsXml(exception);
					break;
				default:
					r = null;
					break;
			}

			if (r != null)
			{
				r.StatusCode = HttpStatusCode.InternalServerError;
			}

			return r;
		}
Ejemplo n.º 4
0
        private static Response CreateResponse(IResponseFormatter formatter, string id)
        {
            var url = formatter.Context.Request.Url.ToString();
            var response = new Response {StatusCode = HttpStatusCode.Created, Headers = {{"Location", url + "/" + id}}};

            return response;
        }
Ejemplo n.º 5
0
		public void Setup()
		{

			_testCommand = A.Fake<ICommand>();
			_publisher = A.Fake<IPublisher>();
			_compositeApp = A.Fake<ICompositeApp>();
			_registry = A.Fake<ICommandRegistry>();
			_formatter = A.Fake<IResponseFormatter>();
			_publicationRecord = A.Fake<ICommandPublicationRecord>();
			_jsonSerializer = new DefaultJsonSerializer();
			_xmlSerializer = new DefaultXmlSerializer();

			A.CallTo(() => _testCommand.Created).Returns(DateTime.MaxValue);
			A.CallTo(() => _testCommand.CreatedBy).Returns(new Guid("ba5f18dc-e287-4d9e-ae71-c6989b10d778"));
			A.CallTo(() => _testCommand.Identifier).Returns(new Guid("ba5f18dc-e287-4d9e-ae71-c6989b10d778"));
			A.CallTo(() => _formatter.Serializers).Returns(new List<ISerializer> { _jsonSerializer, _xmlSerializer });
			A.CallTo(() => _publicationRecord.Dispatched).Returns(true);
			A.CallTo(() => _publicationRecord.Error).Returns(false);
			A.CallTo(() => _publicationRecord.Completed).Returns(true);
			A.CallTo(() => _publicationRecord.Created).Returns(DateTime.MinValue);
			A.CallTo(() => _publicationRecord.MessageLocation).Returns(new Uri("http://localhost/fake/message"));
			A.CallTo(() => _publicationRecord.MessageType).Returns(typeof(IPublicationRecord));
			A.CallTo(() => _publicationRecord.CreatedBy).Returns(Guid.Empty);
			A.CallTo(() => _compositeApp.GetCommandForInputModel(A.Dummy<IInputModel>())).Returns(_testCommand);
			A.CallTo(() => _publisher.PublishMessage(A.Fake<ICommand>())).Returns(_publicationId);
			A.CallTo(() => _registry.GetPublicationRecord(_publicationId)).Returns(_publicationRecord);

			_euclidApi = new ApiModule(_compositeApp, _registry, _publisher);
		}
Ejemplo n.º 6
0
 public RavenSessionModule(IViewFactory viewFactory, IResponseFormatter responseFormatter,
                                IModelBinderLocator modelBinderLocator,
                                IRavenSessionManager ravenSessionProvider)
 {
     this.viewFactory = viewFactory;
     this.responseFormatter = responseFormatter;
     this.modelBinderLocator = modelBinderLocator;
     _ravenSessionProvider = ravenSessionProvider;
 }
Ejemplo n.º 7
0
 public static Response GetThumbnailImage(Guid id, int page, IResponseFormatter response)
 {
     var bitmap = Image.FromStream(new MemoryStream(GetPageImageBytes(id, page)), false, false);
     double ratio = 200D / (double)bitmap.Height;
     int width = (int)(bitmap.Width * ratio);
     var callback = new Image.GetThumbnailImageAbort(() => true);
     var thumbnail = bitmap.GetThumbnailImage(width, 200, callback, IntPtr.Zero);
     MemoryStream stream = GetBytesFromImage(thumbnail);
     return response.FromStream(stream, MimeTypes.GetMimeType(".jpg"));
 }
Ejemplo n.º 8
0
 public Response Generate(IResponseFormatter response, ErrorCode code)
 {
     var error = Errors[code];
     return response.AsJson(new
     {
         ErrorCode = (int)code,
         ErrorMessage = error.Message
     })
     .WithStatusCode(error.StatusCode);
 }
Ejemplo n.º 9
0
 public EventStreamWriterResponse(IResponseFormatter formatter, string id, dynamic body)
 {
     _serializer = formatter.Serializers.FirstOrDefault(s => s.CanSerialize("application/json"));
     ContentType = "text/event-stream";
     Contents = s =>
     {
         _responseStream = s;
         Write(body);
     };
 }
        public JsonFormatterExtensionsFixtures()
        {
            var environment = GetTestingEnvironment();
            var serializerFactory =
               new DefaultSerializerFactory(new ISerializer[] { new DefaultJsonSerializer(environment) });

            this.formatter = A.Fake<IResponseFormatter>();
            A.CallTo(() => this.formatter.Environment).Returns(environment);
            A.CallTo(() => this.formatter.SerializerFactory).Returns(serializerFactory);
            this.model = new Person { FirstName = "Andy", LastName = "Pike" };
            this.response = this.formatter.AsJson(model);
        }
Ejemplo n.º 11
0
		public static Response WriteTo(this IMetadataFormatter formatter, IResponseFormatter response)
		{
			var format = response.Context.GetResponseFormat();

			if (format == ResponseFormat.Html)
			{
				return HttpStatusCode.NoContent;
			}

			var representation = format == ResponseFormat.Json ? "json" : "xml";
			var encodedString = formatter.GetRepresentation(representation);
			var stream = new MemoryStream(Encoding.UTF8.GetBytes(encodedString));
			return response.FromStream(stream, Euclid.Common.Extensions.MimeTypes.GetByExtension(representation));
		}
Ejemplo n.º 12
0
 public Response MissingParameters(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.MissingParameters);
 }
Ejemplo n.º 13
0
 public static Response GetIcon(string key, IResponseFormatter response)
 {
     var image = ComicBook.PublisherIcons.GetImage(key);
     if (image == null)
     {
         return response.AsRedirect("/original/Views/spacer.png");
     }
     return response.FromStream(GetBytesFromImage(image), MimeTypes.GetMimeType(".jpg"));
 }
Ejemplo n.º 14
0
 private static Response OnRequestFallback(NancyContext context, Request request, IResponseFormatter formatter, ICollection<JsonSchemaMessage> violations)
 {
     return HttpStatusCode.BadRequest;
 }
Ejemplo n.º 15
0
 public static Response InvalidToken(this IResponseFormatter response)
 {
     return(response.AsJsonError($"Missing or invalid {Config.AuthHeaderName} header.", HttpStatusCode.Unauthorized));
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultNancyModuleBuilder"/> class.
 /// </summary>
 /// <param name="viewFactory">The <see cref="IViewFactory"/> instance that should be assigned to the module.</param>
 /// <param name="responseFormatter">An <see cref="DefaultResponseFormatter"/> instance that should be assigned to the module.</param>
 /// <param name="modelBinderLocator">A <see cref="IModelBinderLocator"/> instance that should be assigned to the module.</param>
 public DefaultNancyModuleBuilder(IViewFactory viewFactory, IResponseFormatter responseFormatter, IModelBinderLocator modelBinderLocator)
 {
     this.viewFactory        = viewFactory;
     this.responseFormatter  = responseFormatter;
     this.modelBinderLocator = modelBinderLocator;
 }
Ejemplo n.º 17
0
 public Response OnBrokerResponse(NancyContext context, Request request, Response response, IResponseFormatter formatter, ICollection<JsonSchemaMessage> violations)
 {
     return HttpStatusCode.InternalServerError;
 }
Ejemplo n.º 18
0
        public static Response AsXml <TModel>(this IResponseFormatter formatter, TModel model)
        {
            var serializer = xmlSerializer ?? (xmlSerializer = formatter.Serializers.FirstOrDefault(s => s.CanSerialize("application/xml")));

            return(new XmlResponse <TModel>(model, "application/xml", serializer));
        }
        // Commented out to move the dependency on IResponseFormatter FROM the constructor TO the EndPoint method  - so a new service object will be received for every request
        //private IResponseFormatter formatter;

        //public WeatherEndpoint(IResponseFormatter responseFormatter)
        //{
        //    formatter = responseFormatter;
        //}

        public async Task Endpoint(HttpContext httpContext, IResponseFormatter formatter)
        {
            Console.WriteLine(formatter.GetType().CustomAttributes.ToString());
            await formatter.Format(httpContext, "WeatherEndpoint class no longer static. \nDependency on IResponseFormatter service through WeatherEndpoint.Endpoint() method \n(not via constructor injection): it's cloudy in Milan");
        }
        public static Response asJsonNet <T>(this IResponseFormatter formatter, T instance)
        {
            var responseData = JsonConvert.SerializeObject(instance);

            return(formatter.AsText(responseData, "application/json"));
        }
Ejemplo n.º 21
0
 public static Response AsJs(this IResponseFormatter formatter, string applicationRelativeFilePath)
 {
     return(AsFile(formatter, applicationRelativeFilePath));
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Configures the bootstrapper to use the provided instance of <see cref="IResponseFormatter"/>.
 /// </summary>
 /// <param name="responseFormatter">The <see cref="IResponseFormatter"/> instance that should be used by the bootstrapper.</param>
 /// <returns>An instance to the current <see cref="FakeNancyBootstrapperConfigurator"/>.</returns>
 public FakeNancyBootstrapperConfigurator ResponseFormatter(IResponseFormatter responseFormatter)
 {
     this.bootstrapper.configuredInstances[typeof(IResponseFormatter)] = responseFormatter;
     return(this);
 }
Ejemplo n.º 23
0
 public static Response AsStream(this IResponseFormatter formatter, Func <Stream> readStream, string contentType)
 {
     return(new StreamResponse(readStream, contentType));
 }
Ejemplo n.º 24
0
 public static Response ShopifyAuthenticationRequired(this IResponseFormatter response)
 {
     return(response.AsJsonError("Shopify OAuth integration required.", HttpStatusCode.PreconditionFailed));
 }
Ejemplo n.º 25
0
 public Response NoUserForEmail(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.NoUserForEmail);
 }
Ejemplo n.º 26
0
 public static Response AutomapJson <T>(this IResponseFormatter response, object model)
 {
     return(response.AsJson(Mapper.Map <T>(model)));
 }
Ejemplo n.º 27
0
 public Response PermissionDenied(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.PermissionDenied);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// AsError
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <param name="data"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static Response AsErrorJson <T>(this IResponseFormatter response, T data, string message) where T : class
        {
            var serverResponse = ResponseProvider.Error(data, message);

            return(response.AsJson(serverResponse));
        }
Ejemplo n.º 29
0
 public Response InvalidParameters(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.InvalidParameters);
 }
Ejemplo n.º 30
0
        /// <summary>
        /// AsSuccess
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static Response AsSuccessJson <T>(this IResponseFormatter response, T data) where T : class
        {
            var serverResponse = ResponseProvider.Success(data);

            return(response.AsJson(serverResponse));
        }
Ejemplo n.º 31
0
 public static Response ThenRedirectTo(this IResponseFormatter response, string viewName)
 {
     return(response.AsRedirect(viewName));
 }
 public CsvFormatterExtensionsFixtures()
 {
     this.formatter = A.Fake<IResponseFormatter>();
     this.model = new Person { FirstName = "Emmanuel", LastName = "Morales" };
     this.response = this.formatter.AsCsv(model);
 }
Ejemplo n.º 33
0
 public static Response FromByteArray(this IResponseFormatter formatter, byte[] body, string contentType = null)
 {
     return(new ByteArrayResponse(body, contentType));
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Takes a Nancy response + error message and turns it into a JSON error message.
 /// </summary>
 public static Response AsJsonError(this IResponseFormatter response, string message, HttpStatusCode statusCode, object details = null)
 {
     return(response.AsJson(new { message = message, details }, statusCode));
 }
Ejemplo n.º 35
0
 public FormatterExtensionsFixture()
 {
     this.context = new NancyContext();
     this.formatter = new DefaultResponseFormatter(A.Fake<IRootPathProvider>(), context, new DefaultSerializerFactory(null), A.Fake<INancyEnvironment>());
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Returns a redirect response to the agent.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="location">The location to redirect to.</param>
 /// <param name="type">The redirect type. See <see cref="RedirectResponse.RedirectType"/>.</param>
 public static Response AsRedirect(this IResponseFormatter formatter, string location, RedirectResponse.RedirectType type = RedirectResponse.RedirectType.SeeOther)
 {
     return(new RedirectResponse(formatter.Context.ToFullPath(location), type));
 }
Ejemplo n.º 37
0
 //private IResponseFormatter formatter;
 //public WeatherEndpoint(IResponseFormatter responseFormatter)
 //{
 //    formatter = responseFormatter;
 //}
 //public async Task Endpoint(HttpContext context)
 public async Task Endpoint(HttpContext context, IResponseFormatter formatter)
 {
     await formatter.Format(context, "Endpoint Class: It is cloudy in Milan");
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Serializes the <paramref name="model"/> to XML and returns it to the
        /// agent, optionally using the <paramref name="statusCode"/>.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <param name="formatter">The formatter.</param>
        /// <param name="model">The model to serialize.</param>
        /// <param name="statusCode">The HTTP status code. Defaults to <see cref="HttpStatusCode.OK"/>.</param>
        public static Response AsXml <TModel>(this IResponseFormatter formatter, TModel model, HttpStatusCode statusCode = HttpStatusCode.OK)
        {
            var serializer = xmlSerializer ?? (xmlSerializer = formatter.SerializerFactory.GetSerializer("application/xml"));

            return(new XmlResponse <TModel>(model, serializer, formatter.Environment));
        }
Ejemplo n.º 39
0
        public static Response GetPageImage(Guid id, int page, int width, int height, IResponseFormatter response)
        {
          // Restrict access to the FreeImage library to one thread at a time.
          lock(lockThis)
          {
            int max_width = 0;
            int max_height = 0;
            bool thumbnail = !(width == -1 && height == -1);
            bool processed = false;
            
            string filename = string.Format("{0}-p{1}-w{2}-h{3}.jpg", id, page, width, height);
            
            if (thumbnail)
            {
              MemoryStream cachestream = ImageCache.Instance.LoadFromCache(filename, true);
              // Cached thumbnails are assumed to be in the correct format and adhere to the size/format restrictions of the ipad.
              if (cachestream != null)
                return response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg"));
            }
            else
            {
              // Check if a processed (rescaled and/or progressive) image is cached.
              string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
              MemoryStream cachestream = ImageCache.Instance.LoadFromCache(processed_filename, false);
              if (cachestream != null)
                return response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg"));
            }

            MemoryStream stream = null;
            
            // Check if original image is in the cache.
            string org_filename = string.Format("{0}-p{1}.jpg", id, page);
            stream = ImageCache.Instance.LoadFromCache(org_filename, false);
              
            if (stream == null)
            {
              // Image is not in the cache, get it via ComicRack.
              var bytes = GetPageImageBytes(id, page);
              if (bytes == null)
              {
                return HttpStatusCode.NotFound;
              }
                
              stream = new MemoryStream(bytes);
                
              // Always save the original page to the cache
              ImageCache.Instance.SaveToCache(org_filename, stream, false);
            }
                        
            stream.Seek(0, SeekOrigin.Begin);

            #if USE_GDI
            
              Bitmap bitmap = new Bitmap(stream, false);
              int bitmap_width = (int)bitmap.Width;
              int bitmap_height = (int)bitmap.Height;
              
            #elif USE_DIB
            
              FIBITMAP dib = FreeImage.LoadFromStream(stream);
              if (dib == null)
              {
                Console.WriteLine("Loading bitmap failed. Aborting.");
                // Check whether there was an error message.
                return HttpStatusCode.InternalServerError;
              }
              int bitmap_width = (int)FreeImage.GetWidth(dib);
              int bitmap_height = (int)FreeImage.GetHeight(dib);
            
            #elif USE_FIB
            
              FreeImageBitmap fib = FreeImageBitmap.FromStream(stream, false);
              if (fib == null)
              {
                Console.WriteLine("Loading bitmap failed. Aborting.");
                // Check whether there was an error message.
                return HttpStatusCode.InternalServerError;
              }
                                      
              int bitmap_width = (int)fib.Width;
              int bitmap_height = (int)fib.Height;
            #endif
            
            if (ImageCache.Instance.use_max_dimension)
            {
              int mw, mh;
              
              if (bitmap_width >= bitmap_height)
              {
                mw = ImageCache.Instance.max_dimension_long;
                mh = ImageCache.Instance.max_dimension_short;
              }
              else
              {
                mw = ImageCache.Instance.max_dimension_short;
                mh = ImageCache.Instance.max_dimension_long;
              }
              
              if (bitmap_width > mw || bitmap_height > mh)
              {
                double scaleW = (double)mw / (double)bitmap_width;
                double scaleH = (double)mh / (double)bitmap_height;
                double scale = Math.Min(scaleW, scaleH);
                
                max_width = (int)Math.Floor(scale * bitmap_width);
                max_height = (int)Math.Floor(scale * bitmap_height);
              }
              else
              {
                max_width = bitmap_width;
                max_height = bitmap_height;
              }
            }
            else            
            // Check if the image dimensions exceeds the maximum image dimensions
            if ((bitmap_width * bitmap_height) > ImageCache.Instance.maximum_imagesize)
            {
              max_width = (int)Math.Floor(Math.Sqrt((double)bitmap_width / (double)bitmap_height * (double)ImageCache.Instance.maximum_imagesize));
              max_height = (int)Math.Floor((double)max_width * (double)bitmap_height / (double)bitmap_width);
            }
            else
            {
              max_width = bitmap_width;
              max_height = bitmap_height;
            }
                        
            // Calculate the dimensions of the returned image.
            int result_width = width;
            int result_height = height;
            
            if (result_width == -1 && result_height == -1)
            {
              result_width = max_width;
              result_height = max_height;
            }
            else
            {
              if (result_width == -1)
              {
                result_height = Math.Min(max_height, result_height);
                double ratio = (double)result_height / (double)max_height;
                result_width = (int)Math.Floor(((double)max_width * ratio));
              }
              else
              if (result_height == -1)
              {
                result_width = Math.Min(max_width, result_width);
                double ratio = (double)result_width / (double)max_width;
                result_height = (int)Math.Floor(((double)max_height * ratio));
              }
            }
            
            // TODO: do this per requesting target device instead of using one global setting.
            
            // Resize ?
            if (result_width != bitmap_width || result_height != bitmap_height)
            {
                processed = true;
                
              #if USE_DIB || USE_FIB
                //FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_BICUBIC;
                FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_LANCZOS3;
                
                #if USE_FIB
                  fib.Rescale(result_width, result_height, resizer);
                #else
                              
                  FIBITMAP newdib = FreeImage.Rescale(dib, result_width, result_height, resizer);
                  if (!newdib.IsNull)
                  {
                    FreeImage.Unload(dib);
                    dib.SetNull();
                    dib = newdib;
                  }
                #endif
              #elif USE_GDI
                Bitmap resizedBitmap = Resize(bitmap, result_width, result_height);
                bitmap.Dispose();
                bitmap = resizedBitmap;
                resizedBitmap = null;
              #endif
            }
            
            
            // Check if the image must be converted to progressive jpeg
            if (ImageCache.Instance.use_progressive_jpeg && (result_width * result_height) >= ImageCache.Instance.progressive_jpeg_size_threshold)
            {
              processed = true;
              
              // Convert image to progressive jpeg
              
              // FreeImage source code reveals that lower 7 bits of the FREE_IMAGE_SAVE_FLAGS enum are used for low-level quality control.
              FREE_IMAGE_SAVE_FLAGS quality = (FREE_IMAGE_SAVE_FLAGS)ImageCache.Instance.progressive_jpeg_quality;
              FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | quality;

              #if USE_DIB || USE_FIB
                
                stream.Dispose();
                stream = new MemoryStream();
                
                #if USE_FIB
                
                  fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                  fib.Dispose();
                  
                #else
                
                  FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                  FreeImage.Unload(dib);
                  dib.SetNull();
                 
                #endif
                
              #else
                FIBITMAP dib = FreeImage.CreateFromBitmap(bitmap);
                bitmap.Dispose();
                bitmap = null;
                stream.Dispose();
                stream = new MemoryStream();
                
                FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                FreeImage.Unload(dib);
                dib.SetNull();
                
              #endif              
            }
            else
            if (processed) 
            {
              // image was rescaled, make new stream with rescaled bitmap
              
              #if USE_DIB || USE_FIB
              
                FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_OPTIMIZE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                
                stream.Dispose();  
                stream = new MemoryStream();
                
                #if USE_FIB
                  fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                  fib.Dispose();
                #else
                  FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                  FreeImage.Unload(dib);
                  dib.SetNull();
                #endif
              #else
              
                stream = GetBytesFromImage(bitmap);
   
              #endif           
              // For now, images that were resized because they exceeded the maximum dimensions are not saved to the cache.
            }
            
            #if USE_DIB
              FreeImage.Unload(dib);
              dib.SetNull();
            #elif USE_FIB
              fib.Dispose();
            #elif USE_GDI

            if (bitmap != null)
            {
              bitmap.Dispose();
              bitmap = null;
            }

            #endif
            
            // Always save thumbnails to the cache
            if (thumbnail)
            {
              ImageCache.Instance.SaveToCache(filename, stream, true);
            }
            else
            if (processed)
            {
              // Store rescaled and/or progressive jpegs in the cache for now.
              string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
              ImageCache.Instance.SaveToCache(processed_filename, stream, false);
            }
            
            stream.Seek(0, SeekOrigin.Begin);
            return response.FromStream(stream, MimeTypes.GetMimeType(".jpg"));
          }
        }
Ejemplo n.º 40
0
 /// <summary>
 /// Writes the data from the given <paramref name="stream"/> to the
 /// agent, using <paramref name="contentType"/> for the <c>Content-Type</c> header.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="stream">The stream to copy from.</param>
 /// <param name="contentType">Value for the <c>Content-Type</c> header.</param>
 public static Response FromStream(this IResponseFormatter formatter, Stream stream, string contentType)
 {
     return(new StreamResponse(() => stream, contentType));
 }
Ejemplo n.º 41
0
 public TextFormatterFixture()
 {
     this.formatter = A.Fake<IResponseFormatter>();
     this.response = this.formatter.AsText("sample text");
 }
Ejemplo n.º 42
0
 /// <summary>
 /// Invokes the given <paramref name="streamDelegate"/> to write the stream data to the
 /// agent, using <paramref name="contentType"/> for the <c>Content-Type</c> header.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="streamDelegate">A delegate returning a stream to copy from.</param>
 /// <param name="contentType">Value for the <c>Content-Type</c> header.</param>
 public static Response FromStream(this IResponseFormatter formatter, Func <Stream> streamDelegate, string contentType)
 {
     return(new StreamResponse(streamDelegate, contentType));
 }
 public JsonFormatterExtensionsFixtures()
 {
     this.formatter = A.Fake<IResponseFormatter>();
     this.model = new Person { FirstName = "Andy", LastName = "Pike" };
     this.response = this.formatter.AsJson(model);
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Sends the file at <paramref name="applicationRelativeFilePath"/> to the
 /// agent, using the file extension and <see cref="MimeTypes.GetMimeType"/>
 /// to determine the <c>Content-Type</c> header.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="applicationRelativeFilePath">The application relative file path.</param>
 public static Response AsFile(this IResponseFormatter formatter, string applicationRelativeFilePath)
 {
     return(new GenericFileResponse(applicationRelativeFilePath));
 }
Ejemplo n.º 45
0
 public Response NoUserForCredentials(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.NoUserForCredentials);
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Returns the <paramref name="contents"/> string to the
 /// agent, using <c>text/plain</c> and <paramref name="encoding"/>
 /// for the <c>Content-Type</c> header.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="contents">The contents of the response.</param>
 /// <param name="encoding">The encoding to use.</param>
 public static Response AsText(this IResponseFormatter formatter, string contents, Encoding encoding)
 {
     return(new TextResponse(contents, encoding: encoding));
 }
Ejemplo n.º 47
0
 public Response NoUserForThumbkey(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.NoUserForThumbkey);
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Returns the <paramref name="contents"/> string as a <c>text/plain</c> response to the agent.
 /// </summary>
 /// <param name="formatter">The formatter.</param>
 /// <param name="contents">The contents of the response.</param>
 public static Response AsText(this IResponseFormatter formatter, string contents)
 {
     return(new TextResponse(contents));
 }
Ejemplo n.º 49
0
 public Response UserNameTaken(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.UserNameTaken);
 }
Ejemplo n.º 50
0
 public FormatterExtensionsFixture()
 {
     this.context = new NancyContext();
     this.formatter = new DefaultResponseFormatter(A.Fake<IRootPathProvider>(), context, new ISerializer[] { });
 }
Ejemplo n.º 51
0
 public Response InvalidForgotPasswordToken(IResponseFormatter response)
 {
     return Generate(response, ErrorCode.InvalidForgotPasswordToken);
 }
Ejemplo n.º 52
0
        // private IResponseFormatter formatter;

        // public WeatherEndpoint(IResponseFormatter responseFormatter)
        // {
        //     formatter = responseFormatter;
        // }

        public async Task Endpoint(HttpContext context, IResponseFormatter formatter)
        {
            // await context.Response.WriteAsync("Endpoint Class: It is cloudy in Milan");
            // change to DI - fetches the requisite service
            await formatter.Format(context, "Endpoint Class: It is cloudy in Milan");
        }
Ejemplo n.º 53
0
 public Response OnBrokenRequest(NancyContext context, Request request, IResponseFormatter formatter, ICollection<JsonSchemaMessage> violations)
 {
     return formatter.AsJson(new { }, HttpStatusCode.BadRequest);
 }
Ejemplo n.º 54
0
 public CharacterController(IResponseFormatter responseFormatter, DndRepository repository, CharacterLoginHandler characterLoginHandler, IRequestHandler requestHandler) : base(responseFormatter, repository)
 {
     _requestHandler        = requestHandler;
     _characterLoginHandler = characterLoginHandler;
 }
Ejemplo n.º 55
0
 public SubscriptionRunner(ISubscriptionRepository subscriptionRepository, IQueryPerformer queryPerformer, IResponseFormatter responseFormatter)
 {
     _subscriptionRepository = subscriptionRepository;
     _queryPerformer         = queryPerformer;
     _responseFormatter      = responseFormatter;
 }
Ejemplo n.º 56
0
        /// <summary>
        /// AsError
        /// </summary>
        /// <param name="response"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static Response AsErrorJson(this IResponseFormatter response, string message)
        {
            var serverResponse = ResponseProvider.Error(default(BaseResponseEmpty), message);

            return(response.AsJson(serverResponse));
        }
Ejemplo n.º 57
0
 public SearchArtistByNameFunction(IMediator mediator, IResponseFormatter <SearchArtistByNameResponseDto> artistResponseFormatter)
 {
     _mediator = mediator;
     _artistResponseFormatter = artistResponseFormatter;
 }
 public RequestHandler(ILogger <RequestHandler> logger, IResponseFormatter responseFormatter)
 {
     _logger            = logger;
     _responseFormatter = responseFormatter;
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultNancyModuleBuilder"/> class.
 /// </summary>
 /// <param name="viewFactory">The <see cref="IViewFactory"/> instance that should be assigned to the module.</param>
 /// <param name="responseFormatter">An <see cref="DefaultResponseFormatter"/> instance that should be assigned to the module.</param>
 /// <param name="modelBinderLocator">A <see cref="IModelBinderLocator"/> instance that should be assigned to the module.</param>
 public DefaultNancyModuleBuilder(IViewFactory viewFactory, IResponseFormatter responseFormatter, IModelBinderLocator modelBinderLocator)
 {
     this.viewFactory = viewFactory;
     this.responseFormatter = responseFormatter;
     this.modelBinderLocator = modelBinderLocator;
 }
Ejemplo n.º 60
0
        public static Response Created(this IResponseFormatter formatter, string location)
        {
            Response response = HttpStatusCode.Created;

            return(response.WithHeader("Location", location));
        }