public void ProcessRequest(HttpContext context) {
            // get request parameters
            string tableName = context.Request.QueryString["table"];
            string column = context.Request.QueryString["column"];
            int width = Convert.ToInt32(context.Request.QueryString["width"]);
            int height = Convert.ToInt32(context.Request.QueryString["height"]);

            StringBuilder sb = new StringBuilder();
            List<string> primaryKeyValues = new List<string>();
            int i = 0;
            string primaryKeyValue = context.Request.QueryString["pk" + i.ToString()];
            while (primaryKeyValue != null) {
                if (sb.Length > 0) {
                    sb.Append(',');
                }
                sb.Append(primaryKeyValue);
                primaryKeyValues.Add(primaryKeyValue);
                i++;
                primaryKeyValue = context.Request["pk" + i.ToString()];
            }

            string cachekey = string.Format("{0}:{1}:{2}", tableName, column, sb.ToString());
            ImageCacheEntry images = (ImageCacheEntry)context.Cache[cachekey];
            if (images == null) {
                //get image bytes
                byte[] bytes;
                object picture = LoadImage(tableName, primaryKeyValues.ToArray(), column);
                if (picture is byte[]) {
                    bytes = (byte[])picture;
                } else if (picture is System.Data.Linq.Binary) {
                    bytes = ((System.Data.Linq.Binary)picture).ToArray();
                } else {
                    bytes = null;
                }

                if (bytes != null) {
                    if (bytes.Length > 78 && bytes[0] == 0x15 && bytes[1] == 0x1c && bytes[2] == 0x2f) {
                        //hack to strip off OLE header for Northwind categories table
                        byte[] newbytes = new byte[bytes.Length - 78];
                        Array.Copy(bytes, 78, newbytes, 0, bytes.Length - 78);
                        bytes = newbytes;
                    }

                    images = new ImageCacheEntry(bytes);

                    //cache image
                    context.Cache.Add(cachekey, images, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.Low, null);
                }
            }

            if (images != null) {
                context.Response.ContentType = images.ContentType;
                context.Response.BinaryWrite(images.GetImage(width, height));
                context.Response.Cache.SetNoStore();
            } else {
                context.Response.ContentType = "image/gif";
                context.Response.WriteFile(context.Server.MapPath("~/DynamicData/Content/Images/Blank.gif"));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Requests a new image and return it via the callback. If the image is in the cache, it is
        /// returned from there. Otherwise we queue up the request and spin up a thread to retrieve the
        /// image and invoke the callback from there.
        /// </summary>
        /// <param name="imageURL">The URL of the image</param>
        /// <param name="maxWidth">The maximum width of the requested image</param>
        /// <param name="maxHeight">The maximum height of the requested image</param>
        /// <param name="callback">The callback</param>
        /// <param name="callbackParameter">A user specified parameter for the callback</param>
        /// <returns>An Image object that represents the specified image or null if it is not yet available</returns>
        public Image NewRequest(string imageURL, int maxWidth, int maxHeight, ImageRetrieved callback, object callbackParameter)
        {
            if (_imageCache.ContainsKey(imageURL))
            {
                LogFile.WriteLine("Image {0} retrieved from cache", imageURL);

                return((_imageCache[imageURL].Image != null) ? ScaleImage(_imageCache[imageURL].Image, maxWidth, maxHeight) : null);
            }

            // Spin up a new thread to obtain any images
            Thread t = new Thread(() =>
            {
                try
                {
                    LogFile.WriteLine("Requesting image {0}", imageURL);

                    // Convert Dropbox share URLs into raw links
                    string realImageURL = imageURL;
                    if (realImageURL.StartsWith("https://www.dropbox.com", StringComparison.Ordinal))
                    {
                        realImageURL += "?raw=1";
                    }

                    HttpWebRequest webRequest            = (HttpWebRequest)WebRequest.Create(realImageURL);
                    webRequest.AllowWriteStreamBuffering = true;
                    webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

                    using (WebResponse _WebResponse = webRequest.GetResponse())
                    {
                        Stream stream = _WebResponse.GetResponseStream();
                        if (stream != null)
                        {
                            Image _tmpImage       = Image.FromStream(stream);
                            _imageCache[imageURL] = new ImageCacheEntry {
                                Image = _tmpImage, Timestamp = DateTime.Now
                            };

                            Image image = ScaleImage(_tmpImage, maxWidth, maxHeight);
                            callback(image, callbackParameter);

                            LogFile.WriteLine("Image {0} retrieved from server and cached", imageURL);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogFile.WriteLine("Failed to load {0}: {1}", imageURL, e.Message);

                    // Don't try and request this image again for a while.
                    _imageCache[imageURL] = new ImageCacheEntry {
                        Image = null, Timestamp = DateTime.Now
                    };
                }
            });

            t.Start();
            return(null);
        }
Esempio n. 3
0
        private void RemoveImageFromFolder(ImageCacheEntry imageCacheEntry)
        {
            var path = Path.Combine(imageCacheEntry.FullPath, imageCacheEntry.FileName);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
Esempio n. 4
0
        private ImageCacheEntry SetImageToCacheInternal(string key, ImageCacheEntry imageCacheEntry, byte[] imageAsBytes, ImageCacheOptions opts)
        {
            var entryOptions = new MemoryCacheEntryOptions();

            entryOptions.RegisterPostEvictionCallback(_callback);
            entryOptions.SetSlidingExpiration(TimeSpan.FromMilliseconds(opts.ExpirationTimeSpanInMilliseconds));

            imageCacheEntry.FullPath = opts.PathToCacheDirectory;

            var entered = _memoryCache.Set <ImageCacheEntry>(key, imageCacheEntry, entryOptions);

            return(this.SaveImageToFolder(entered, imageAsBytes) ? entered : null);
        }
Esempio n. 5
0
        public ImageCacheEntry SetImageToCache(string key, ImageCacheEntry imageCacheEntry, byte[] imageAsBytes, ImageCacheOptions opts)
        {
            if (imageCacheEntry is null)
            {
                throw new ArgumentNullException(nameof(imageCacheEntry));
            }

            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            return(((MemoryCache)_memoryCache).Count == opts.MaxCountOfCachedImages ? null : this.SetImageToCacheInternal(key, imageCacheEntry, imageAsBytes, opts));
        }
Esempio n. 6
0
        private FileStreamResult GenerateImageResult(ImageCacheEntry image, byte[] imageAsBytes)
        {
            var fileExtension = image.FileName.Substring(image.FileName.LastIndexOf('.'));
            var contentType   = FileExtensions.GetContentTypeByExtension(fileExtension);

            var stream = new MemoryStream(imageAsBytes);

            var result = new FileStreamResult(stream, contentType)
            {
                FileDownloadName = image.FileName
            };

            return(result);
        }
Esempio n. 7
0
        /// <summary>
        /// Loads image with given image ID and weather icon description
        /// </summary>
        /// <param name="imageId">image ID to load</param>
        /// <param name="iconDescription">icon description for image to load</param>
        /// <returns>task to wait on</returns>
        private async Task LoadImageAsync(string imageId, WeatherIconDescription iconDescription)
        {
            ImageCacheEntry entry = null;

            switch (iconDescription.Type)
            {
            case WeatherIconDescription.IconType.IconLink:
                if (iconDescription.WebLink.StartsWith("https://www.austrocontrol.at"))
                {
                    var    platform = DependencyService.Get <IPlatform>();
                    byte[] data     = platform.LoadAssetBinaryData("alptherm-favicon.png");
                    entry = new ImageCacheEntry(data);
                    break;
                }

                string faviconLink = await GetFaviconFromLinkAsync(iconDescription.WebLink);

                if (!string.IsNullOrEmpty(faviconLink))
                {
                    byte[] data = await this.client.GetByteArrayAsync(faviconLink);

                    entry = new ImageCacheEntry(data);
                }

                break;

            case WeatherIconDescription.IconType.IconApp:
                var appManager = DependencyService.Get <IAppManager>();
                entry = new ImageCacheEntry(appManager.GetAppIcon(iconDescription.WebLink));
                break;

            case WeatherIconDescription.IconType.IconPlaceholder:
                string imagePath = Converter.ImagePathConverter.GetDeviceDependentImage("border_none_variant");
                entry = new ImageCacheEntry(ImageSource.FromFile(imagePath));
                break;

            default:
                break;
            }

            if (entry != null)
            {
                lock (this.imageCacheLock)
                {
                    this.imageCache[imageId] = entry;
                }
            }
        }
Esempio n. 8
0
        private byte[] GetImageFromFolder(ImageCacheEntry imageCacheEntry)
        {
            var path = Path.Combine(imageCacheEntry.FullPath, imageCacheEntry.FileName);

            if (File.Exists(path))
            {
                using var stream = File.Open(path, FileMode.Open);

                var imageAsBytes = new byte[stream.Length];

                stream.Read(imageAsBytes, 0, imageAsBytes.Length);

                return(imageAsBytes);
            }

            return(null);
        }
Esempio n. 9
0
        private bool SaveImageToFolder(ImageCacheEntry imageCacheEntry, byte[] imageAsBytes)
        {
            try
            {
                var path = Path.Combine(imageCacheEntry.FullPath, imageCacheEntry.FileName);

                if (!File.Exists(path))
                {
                    using var stream = File.Open(path, FileMode.CreateNew);

                    stream.Write(imageAsBytes, 0, imageAsBytes.Length);
                }

                return(true);
            }
            catch (IOException ex)
            {
                return(false);
            }
        }
Esempio n. 10
0
        public void ProcessRequest(HttpContext context)
        {
            // get request parameters
            string tableName = context.Request.QueryString["table"];
            string column    = context.Request.QueryString["column"];
            int    width     = Convert.ToInt32(context.Request.QueryString["width"]);
            int    height    = Convert.ToInt32(context.Request.QueryString["height"]);

            StringBuilder sb = new StringBuilder();
            List <string> primaryKeyValues = new List <string>();
            int           i = 0;
            string        primaryKeyValue = context.Request.QueryString["pk" + i.ToString()];

            while (primaryKeyValue != null)
            {
                if (sb.Length > 0)
                {
                    sb.Append(',');
                }
                sb.Append(primaryKeyValue);
                primaryKeyValues.Add(primaryKeyValue);
                i++;
                primaryKeyValue = context.Request["pk" + i.ToString()];
            }

            string          cachekey = string.Format("{0}:{1}:{2}", tableName, column, sb.ToString());
            ImageCacheEntry images   = (ImageCacheEntry)context.Cache[cachekey];

            if (images == null)
            {
                //get image bytes
                byte[] bytes;
                object picture = LoadImage(tableName, primaryKeyValues.ToArray(), column);
                if (picture is byte[])
                {
                    bytes = (byte[])picture;
                }
                else if (picture is System.Data.Linq.Binary)
                {
                    bytes = ((System.Data.Linq.Binary)picture).ToArray();
                }
                else
                {
                    bytes = null;
                }

                if (bytes != null)
                {
                    if (bytes.Length > 78 && bytes[0] == 0x15 && bytes[1] == 0x1c && bytes[2] == 0x2f)
                    {
                        //hack to strip off OLE header for Northwind categories table
                        byte[] newbytes = new byte[bytes.Length - 78];
                        Array.Copy(bytes, 78, newbytes, 0, bytes.Length - 78);
                        bytes = newbytes;
                    }

                    images = new ImageCacheEntry(bytes);

                    //cache image
                    context.Cache.Add(cachekey, images, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.Low, null);
                }
            }

            if (images != null)
            {
                context.Response.ContentType = images.ContentType;
                context.Response.BinaryWrite(images.GetImage(width, height));
                context.Response.Cache.SetNoStore();
            }
            else
            {
                context.Response.ContentType = "image/gif";
                context.Response.WriteFile(context.Server.MapPath("~/DynamicData/Content/Images/Blank.gif"));
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Requests a new image and return it via the callback. If the image is in the cache, it is
        /// returned from there. Otherwise we queue up the request and spin up a thread to retrieve the
        /// image and invoke the callback from there.
        /// </summary>
        /// <param name="imageURL">The URL of the image</param>
        /// <param name="maxWidth">The maximum width of the requested image</param>
        /// <param name="maxHeight">The maximum height of the requested image</param>
        /// <param name="callback">The callback</param>
        /// <param name="callbackParameter">A user specified parameter for the callback</param>
        /// <returns>An Image object that represents the specified image or null if it is not yet available</returns>
        public Image NewRequest(string imageURL, int maxWidth, int maxHeight, ImageRetrieved callback, object callbackParameter)
        {
            if (_imageCache.ContainsKey(imageURL))
            {
                LogFile.WriteLine("Image {0} retrieved from cache", imageURL);

                return (_imageCache[imageURL].Image != null) ? ScaleImage(_imageCache[imageURL].Image, maxWidth, maxHeight) : null;
            }

            // Spin up a new thread to obtain any images
            Thread t = new Thread(() =>
            {
                try
                {
                    LogFile.WriteLine("Requesting image {0}", imageURL);

                    // Convert Dropbox share URLs into raw links
                    string realImageURL = imageURL;
                    if (realImageURL.StartsWith("https://www.dropbox.com", StringComparison.Ordinal))
                    {
                        realImageURL += "?raw=1";
                    }

                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(realImageURL);
                    webRequest.AllowWriteStreamBuffering = true;
                    webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

                    using (WebResponse _WebResponse = webRequest.GetResponse())
                    {
                        Stream stream = _WebResponse.GetResponseStream();
                        if (stream != null)
                        {
                            Image _tmpImage = Image.FromStream(stream);
                            _imageCache[imageURL] = new ImageCacheEntry { Image = _tmpImage, Timestamp = DateTime.Now };

                            Image image = ScaleImage(_tmpImage, maxWidth, maxHeight);
                            callback(image, callbackParameter);

                            LogFile.WriteLine("Image {0} retrieved from server and cached", imageURL);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogFile.WriteLine("Failed to load {0}: {1}", imageURL, e.Message);

                    // Don't try and request this image again for a while.
                    _imageCache[imageURL] = new ImageCacheEntry { Image = null, Timestamp = DateTime.Now };
                }
            });
            t.Start();
            return null;
        }
Esempio n. 12
0
        public async Task InvokeAsync(HttpContext httpContext, IImagesCachingService imagesCachingService)
        {
            var key = httpContext.Request.Path.ToUriComponent();

            var imageInfo = imagesCachingService.GetImageFromCacheByKey(key);

            var imageCacheEntry = imageInfo?.Item1;
            var imageAsBytes    = imageInfo?.Item2;

            if (imageCacheEntry != null)
            {
                var result = this.GenerateImageResult(imageCacheEntry, imageAsBytes);

                if (result != null)
                {
                    await httpContext.ExecuteResultAsync <FileStreamResult>(result);
                }
            }
            else
            {
                var originalBody = httpContext.Response.Body;

                try
                {
                    await using (var stream = new MemoryStream())
                    {
                        httpContext.Response.Body = stream;

                        await _next(httpContext);

                        var contentType = httpContext.Response.ContentType;

                        if (contentType != null)
                        {
                            var extension = FileExtensions.GetExtensionByContentType(contentType);

                            if (extension != null)
                            {
                                if (ImageExtensions.IsImageFormatOrExtension(extension))
                                {
                                    var contentDisposition =
                                        new ContentDisposition(
                                            httpContext.Response.Headers[HeaderNames.ContentDisposition][0]);

                                    var imageAsBytesToSave = stream.ToArray();

                                    var imageToSet = new ImageCacheEntry
                                    {
                                        FileName = contentDisposition.FileName,
                                    };

                                    imagesCachingService.SetImageToCache(key, imageToSet, imageAsBytesToSave, _opts);
                                }
                            }
                        }

                        stream.Position = 0;
                        await stream.CopyToAsync(originalBody);
                    }
                }
                finally
                {
                    httpContext.Response.Body = originalBody;
                }
            }
        }