Example #1
0
 public ImageProcessor(IHttpClientWrapperAsync httpClient, IFaceDetection faceDetection, IImageCache imageCache, IImageEffect imageEffect)
 {
     this.httpClient    = httpClient;
     this.faceDetection = faceDetection;
     this.imageCache    = imageCache;
     this.imageEffect   = imageEffect;
 }
Example #2
0
 public Searches(IBotCredentials creds, IGoogleApiService google, IDataCache data, IHttpClientFactory factory)
 {
     _creds       = creds;
     _google      = google;
     _images      = data.LocalImages;
     _httpFactory = factory;
 }
Example #3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="shapes"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="properties"></param>
 /// <param name="ic"></param>
 public void SetClipboard(
     IEnumerable <BaseShape> shapes,
     double width,
     double height,
     ImmutableArray <ShapeProperty> properties,
     IImageCache ic)
 {
     try
     {
         using (var bitmap = new Bitmap((int)width, (int)height))
         {
             using (var ms = MakeMetafileStream(bitmap, shapes, properties, ic))
             {
                 var data = new WPF.DataObject();
                 data.SetData(WPF.DataFormats.EnhancedMetafile, ms);
                 WPF.Clipboard.SetDataObject(data, true);
             }
         }
     }
     catch (Exception ex)
     {
         Debug.Print(ex.Message);
         Debug.Print(ex.StackTrace);
     }
 }
 public static Image GetImageFromCache(string imageFileName, string email, int cacheDays,
                                       int imageSize, string imageCachePath, FallBackService fallBack)
 {
     try
     {
         if (cache == null)
         {
             cache = new DirectoryImageCache(imageCachePath); //or: new IsolatedStorageImageCache();
         }
         // If the user image is not cached yet, download it from gravatar and store it in the isolatedStorage
         if (!cache.FileIsCached(imageFileName) ||
             cache.FileIsExpired(imageFileName, cacheDays))
         {
             return(null);
         }
         if (cache.FileIsCached(imageFileName))
         {
             return(cache.LoadImageFromCache(imageFileName, null));
         }
     }
     catch (Exception ex)
     {
         //catch IO errors
         Trace.WriteLine(ex.Message);
     }
     return(null);
 }
Example #5
0
 public TwoStepImageCache(IImageLoader slowLoader, IImageLoader fastLoader, IReceiveImage receiver, int maxCacheSize)
 {
     _innerCache = new ImageCache(this, maxCacheSize);
     _slowLoader = slowLoader;
     _fastLoader = fastLoader;
     _receiver   = receiver;
 }
Example #6
0
        public GirlRating(IImageCache images, double crazy, double hot, int roll, string advice)
        {
            _images = images;
            Crazy   = crazy;
            Hot     = hot;
            Roll    = roll;
            Advice  = advice; // convenient to have it here, even though atm there are only few different ones.

            Url = new AsyncLazy <string>(async() =>
            {
                try
                {
                    using (var ms = new MemoryStream(_images.WifeMatrix.ToArray(), false))
                        using (var img = Image.Load(ms))
                        {
                            const int minx   = 35;
                            const int miny   = 385;
                            const int length = 345;

                            var pointx = (int)(minx + length * (Hot / 10));
                            var pointy = (int)(miny - length * ((Crazy - 4) / 6));

                            using (var pointMs = new MemoryStream(_images.RategirlDot.ToArray(), false))
                                using (var pointImg = Image.Load(pointMs))
                                {
                                    img.DrawImage(pointImg, 100, default, new Point(pointx - 10, pointy - 10));
Example #7
0
 public MediaService(
     SmartDbContext db,
     IFolderService folderService,
     IMediaSearcher searcher,
     IMediaTypeResolver typeResolver,
     IMediaUrlGenerator urlGenerator,
     IEventPublisher eventPublisher,
     ILanguageService languageService,
     ILocalizedEntityService localizedEntityService,
     MediaSettings mediaSettings,
     IImageProcessor imageProcessor,
     IImageCache imageCache,
     MediaExceptionFactory exceptionFactory,
     Func <IMediaStorageProvider> storageProvider,
     MediaHelper helper)
 {
     _db                     = db;
     _folderService          = folderService;
     _searcher               = searcher;
     _typeResolver           = typeResolver;
     _urlGenerator           = urlGenerator;
     _eventPublisher         = eventPublisher;
     _languageService        = languageService;
     _localizedEntityService = localizedEntityService;
     _mediaSettings          = mediaSettings;
     _imageProcessor         = imageProcessor;
     _imageCache             = imageCache;
     _exceptionFactory       = exceptionFactory;
     _storageProvider        = storageProvider();
     _helper                 = helper;
 }
Example #8
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="pictureRepository">Picture repository</param>
 /// <param name="productPictureRepository">Product picture repository</param>
 /// <param name="settingService">Setting service</param>
 /// <param name="webHelper">Web helper</param>
 /// <param name="logger">Logger</param>
 /// <param name="eventPublisher">Event publisher</param>
 /// <param name="mediaSettings">Media settings</param>
 public PictureService(
     IRepository <Picture> pictureRepository,
     //IRepository<ProductPicture> productPictureRepository,
     ISettingService settingService,
     IWebHelper webHelper,
     ILogger logger,
     IEventPublisher eventPublisher,
     MediaSettings mediaSettings,
     IImageResizerService imageResizerService,
     ICacheManager cacheManager,
     CommonSettings commonSettings,
     IImageCache imageCache)
 {
     this._pictureRepository = pictureRepository;
     //this._productPictureRepository = productPictureRepository;
     this._settingService      = settingService;
     this._webHelper           = webHelper;
     this._logger              = logger;
     this._eventPublisher      = eventPublisher;
     this._mediaSettings       = mediaSettings;
     this._imageResizerService = imageResizerService;
     this._imageCache          = imageCache;
     this._cacheManager        = cacheManager;
     this._commonSettings      = commonSettings;
 }
Example #9
0
        public GamesService(CommandHandler cmd, IBotConfigProvider bc, NadekoBot bot,
                            NadekoStrings strings, IDataCache data, CommandHandler cmdHandler,
                            ICurrencyService cs, FontProvider fonts)
        {
            _bc         = bc;
            _cmd        = cmd;
            _strings    = strings;
            _images     = data.LocalImages;
            _cmdHandler = cmdHandler;
            _log        = LogManager.GetCurrentClassLogger();
            _rng        = new NadekoRandom();
            _cs         = cs;
            _fonts      = fonts;

            //8ball
            EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

            //girl ratings
            _t = new Timer((_) =>
            {
                GirlRatings.Clear();
            }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

            try
            {
                TypingArticles = JsonConvert.DeserializeObject <List <TypingArticle> >(File.ReadAllText(TypingArticlesPath));
            }
            catch (Exception ex)
            {
                _log.Warn("Error while loading typing articles {0}", ex.ToString());
                TypingArticles = new List <TypingArticle>();
            }
        }
Example #10
0
        /// <summary>
        /// Occurs when the ASP.NET event handler finishes execution.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task PostProcessImage(object sender, EventArgs e)
        {
            HttpContext context          = ((HttpApplication)sender).Context;
            object      cachedPathObject = context.Items[CachedPathKey];

            if (cachedPathObject != null)
            {
                // Trim the cache.
                await this.imageCache.TrimCacheAsync();

                string cachedPath = cachedPathObject.ToString();

                // Fire the post processing event.
                EventHandler <PostProcessingEventArgs> handler = OnPostProcessing;
                if (handler != null)
                {
                    context.Items[CachedPathKey] = null;
                    await Task.Run(() => handler(this, new PostProcessingEventArgs {
                        CachedImagePath = cachedPath
                    }));
                }
            }

            // Reset the cache.
            this.imageCache = null;
        }
Example #11
0
 public FlipCoinCommands(IDataCache data, ICurrencyService cs, DbService db,
                         GamblingConfigService gss) : base(gss)
 {
     _images = data.LocalImages;
     _cs     = cs;
     _db     = db;
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="container"></param>
        /// <param name="ic"></param>
        public void SetClipboard(IPageContainer container, IImageCache ic)
        {
            try
            {
                if (container == null || container.Template == null)
                {
                    return;
                }

                using (var bitmap = new Bitmap((int)container.Template.Width, (int)container.Template.Height))
                {
                    using (var ms = MakeMetafileStream(bitmap, container, ic))
                    {
                        var data = new WPF.DataObject();
                        data.SetData(WPF.DataFormats.EnhancedMetafile, ms);
                        WPF.Clipboard.SetDataObject(data, true);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }
Example #13
0
 public UserPunishCommands(IDataCache data, MuteService mute, GuildTimezoneService tz, DbService db)
 {
     _images = data.LocalImages;
     _mute   = mute;
     _tz     = tz;
     _db     = db;
 }
Example #14
0
        public PictureService(
            IRepository <MediaFile> pictureRepository,
            IRepository <ProductMediaFile> productPictureRepository,
            IAlbumRegistry albumRegistry,
            IMediaTypeResolver mediaTypeResolver,
            IMediaUrlGenerator mediaUrlGenerator,
            ISettingService settingService,
            IEventPublisher eventPublisher,
            MediaSettings mediaSettings,
            IImageProcessor imageProcessor,
            IImageCache imageCache,
            IProviderManager providerManager,
            IStoreContext storeContext,
            HttpContextBase httpContext,
            ICacheManager cacheManager)
        {
            _pictureRepository        = pictureRepository;
            _productPictureRepository = productPictureRepository;
            _albumRegistry            = albumRegistry;
            _mediaTypeResolver        = mediaTypeResolver;
            _mediaUrlGenerator        = mediaUrlGenerator;
            _settingService           = settingService;
            _eventPublisher           = eventPublisher;
            _mediaSettings            = mediaSettings;
            _imageProcessor           = imageProcessor;
            _imageCache   = imageCache;
            _httpContext  = httpContext;
            _cacheManager = cacheManager;

            var systemName = settingService.GetSettingByKey("Media.Storage.Provider", DatabaseMediaStorageProvider.SystemName);

            _storageProvider = providerManager.GetProvider <IMediaStorageProvider>(systemName);

            Logger = NullLogger.Instance;

            string appPath = "/";

            if (HostingEnvironment.IsHosted)
            {
                appPath = HostingEnvironment.ApplicationVirtualPath.EmptyNull();

                var cdn = storeContext.CurrentStore.ContentDeliveryNetwork;
                if (cdn.HasValue() && !_httpContext.IsDebuggingEnabled && !_httpContext.Request.IsLocal)
                {
                    _host = cdn;
                }
                else if (mediaSettings.AutoGenerateAbsoluteUrls)
                {
                    var uri = httpContext.Request.Url;
                    _host = "//{0}{1}".FormatInvariant(uri.Authority, appPath);
                }
                else
                {
                    _host = appPath;
                }
            }

            _host    = _host.EmptyNull().EnsureEndsWith("/");
            _appPath = appPath.EnsureEndsWith("/");
        }
Example #15
0
        public CockpitForm(ControlManager manager, IImageCache imageCache, CockpitXML.CockpitLayout layout, int forceX, int forceY)
        {
            this.manager    = manager;
            this.imageCache = imageCache;
            manager.AddForm(this);

            InitializeComponent();

            // Now construct the list of controls that are actually used in the layout
            foreach (CockpitXML.CockpitLayoutPanel controlPanel in layout.Panel)
            {
                controlPanels.Add(new CockpitPanel(this, manager, imageCache, controlPanel));
            }

            this.Location        = new Point(forceX >= 0 ? forceX : layout.X, forceY >= 0 ? forceY : layout.Y);
            this.Size            = new Size(layout.Width, layout.Height);
            this.BackgroundImage = imageCache.getImage(layout.BackgroundImage);
            if (layout.TransparencyKey != null)
            {
                this.TransparencyKey = Color.FromArgb(layout.TransparencyKey.Red, layout.TransparencyKey.Green, layout.TransparencyKey.Blue);
            }

            this.MouseDown += new MouseEventHandler(CockpitForm_MouseDown);
            this.MouseUp   += new MouseEventHandler(CockpitForm_MouseUp);
            this.Paint     += new PaintEventHandler(this.CockpitForm_Paint);
        }
Example #16
0
        public static void LoadCachedImage(string imageFileName, string email, Bitmap defaultBitmap, int cacheDays,
                                           int imageSize, string imageCachePath, Action <Image> onChangedImage,
                                           FallBackService fallBack)
        {
            try
            {
                if (cache == null)
                {
                    cache = new DirectoryImageCache(imageCachePath); //or: new IsolatedStorageImageCache();
                }
                // If the user image is not cached yet, download it from gravatar and store it in the isolatedStorage
                if (!cache.FileIsCached(imageFileName) ||
                    cache.FileIsExpired(imageFileName, cacheDays))
                {
                    onChangedImage(defaultBitmap);

                    GetImageFromGravatar(imageFileName, email, imageSize, fallBack);
                }
                if (cache.FileIsCached(imageFileName))
                {
                    onChangedImage(cache.LoadImageFromCache(imageFileName,
                                                            defaultBitmap));
                }
                else
                {
                    onChangedImage(defaultBitmap);
                }
            }
            catch (Exception ex)
            {
                //catch IO errors
                Trace.WriteLine(ex.Message);
            }
        }
Example #17
0
        public CockpitPanel(CockpitForm form, ControlManager manager, IImageCache imageCache, CockpitXML.CockpitLayoutPanel layout)
        {
            this.name = layout.Name;
            this.form = form;

            if (layout.ControlLayout != null)
            {
                // Now construct the list of controls that are actually used in the layout
                foreach (CockpitXML.CockpitLayoutPanelControlLayout controlLayout in layout.ControlLayout)
                {
                    if (manager.HasControl(controlLayout.ControlName))
                    {
                        ICockpitControl        control  = manager.GetControl(controlLayout.ControlName);
                        CockpitControlInstance formItem = new CockpitControlInstance(this, control, new Point(controlLayout.X, controlLayout.Y));
                        controlInstances.Add(formItem);
                        control.AddInstance(formItem);
                    }
                }
            }

            this.Location        = new Point(layout.X, layout.Y);
            this.Size            = new Size(layout.Width, layout.Height);
            this.backgroundImage = imageCache.getImage(layout.BackgroundImage);
            if (layout.VisibleSpecified)
            {
                this.Visible = layout.Visible;
            }
            else
            {
                this.Visible = true;
            }
        }
Example #18
0
        public ButtonControlState(IImageCache imageCache, CockpitXML.CockpitControlsButtonState state)
        {
            if (state.StateValue == null)
            {
                stateValues = new string[0];
            }
            else
            {
                stateValues = state.StateValue;
            }

            this.stateImage       = imageCache.getImage(state.Image);
            this.pushedStateImage = imageCache.getImage(state.PushedImage);

            if (state.PushedAction != null)
            {
                foreach (string action in state.PushedAction)
                {
                    pushedActions.Add(ActionFactory.CreateAction(action));
                }
            }

            if (state.ReleaseAction != null)
            {
                foreach (string action in state.ReleaseAction)
                {
                    releaseActions.Add(ActionFactory.CreateAction(action));
                }
            }
        }
Example #19
0
        public PlantPickService(DbService db, CommandHandler cmd, IBotStrings strings,
                                IDataCache cache, FontProvider fonts, ICurrencyService cs,
                                CommandHandler cmdHandler, DiscordSocketClient client, GamblingConfigService gss)
        {
            _db         = db;
            _strings    = strings;
            _images     = cache.LocalImages;
            _fonts      = fonts;
            _cs         = cs;
            _cmdHandler = cmdHandler;
            _rng        = new NadekoRandom();
            _client     = client;
            _gss        = gss;

            cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
            using (var uow = db.GetDbContext())
            {
                var guildIds = client.Guilds.Select(x => x.Id).ToList();
                var configs  = uow._context.Set <GuildConfig>()
                               .AsQueryable()
                               .Include(x => x.GenerateCurrencyChannelIds)
                               .Where(x => guildIds.Contains(x.GuildId))
                               .ToList();

                _generationChannels = new ConcurrentHashSet <ulong>(configs
                                                                    .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
            }
        }
Example #20
0
        public static void LoadCachedImage(string imageFileName, string email, Bitmap defaultBitmap, int cacheDays,
                                             int imageSize, string imageCachePath, Action<Image> onChangedImage,
                                             FallBackService fallBack)
        {
            try
            {
                if (cache == null)
                    cache = new DirectoryImageCache(imageCachePath); //or: new IsolatedStorageImageCache();

                // If the user image is not cached yet, download it from gravatar and store it in the isolatedStorage
                if (!cache.FileIsCached(imageFileName) ||
                    cache.FileIsExpired(imageFileName, cacheDays))
                {
                    onChangedImage(defaultBitmap);

                    GetImageFromGravatar(imageFileName, email, imageSize, fallBack);
                }
                if (cache.FileIsCached(imageFileName))
                {
                    onChangedImage(cache.LoadImageFromCache(imageFileName,
                                                                 defaultBitmap));
                }
                else
                {
                    onChangedImage(defaultBitmap);
                }
            }
            catch (Exception ex)
            {
                //catch IO errors
                Trace.WriteLine(ex.Message);
            }
        }
Example #21
0
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">
        /// The HTTP MIME type to send.
        /// </param>
        /// <param name="dependencyPaths">
        /// The dependency path for the cache dependency.
        /// </param>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable <string> dependencyPaths)
        {
            if (this.imageCache != null)
            {
                HttpResponse response = context.Response;

                if (response.Headers["ImageProcessedBy"] == null)
                {
                    response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion);
                }

                HttpCachePolicy cache = response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByHeaders["Accept-Encoding"] = true;

                if (!string.IsNullOrWhiteSpace(responseType))
                {
                    response.ContentType = responseType;
                }

                if (dependencyPaths != null)
                {
                    context.Response.AddFileDependencies(dependencyPaths.ToArray());
                    cache.SetLastModifiedFromFileDependencies();
                }

                int maxDays = this.imageCache.MaxDays;

                cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
                cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

                this.imageCache = null;
            }
        }
Example #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageSharpMiddleware"/> class.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline</param>
        /// <param name="options">The middleware configuration options</param>
        /// <param name="loggerFactory">An <see cref="ILoggerFactory"/> instance used to create loggers</param>
        /// <param name="uriParser">An <see cref="IUriParser"/> instance used to parse URI's for commands</param>
        /// <param name="resolvers">A collection of <see cref="IImageResolver"/> instances used to resolve images</param>
        /// <param name="processors">A collection of <see cref="IImageWebProcessor"/> instances used to process images</param>
        /// <param name="cache">An <see cref="IImageCache"/> instance used for caching images</param>
        public ImageSharpMiddleware(
            RequestDelegate next,
            IOptions <ImageSharpMiddlewareOptions> options,
            ILoggerFactory loggerFactory,
            IUriParser uriParser,
            IEnumerable <IImageResolver> resolvers,
            IEnumerable <IImageWebProcessor> processors,
            IImageCache cache)
        {
            Guard.NotNull(next, nameof(next));
            Guard.NotNull(options, nameof(options));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(uriParser, nameof(uriParser));
            Guard.NotNull(resolvers, nameof(resolvers));
            Guard.NotNull(processors, nameof(processors));
            Guard.NotNull(cache, nameof(cache));

            this.next       = next;
            this.options    = options.Value;
            this.uriParser  = uriParser;
            this.resolvers  = resolvers;
            this.processors = processors;
            this.cache      = cache;

            var commands = new List <string>();

            foreach (IImageWebProcessor processor in this.processors)
            {
                commands.AddRange(processor.Commands);
            }

            this.knownCommands = commands;

            this.logger = loggerFactory.CreateLogger <ImageSharpMiddleware>();
        }
Example #23
0
 public RedisCache(IBotCredentials creds)
 {
     Redis = ConnectionMultiplexer.Connect("127.0.0.1");
     Redis.PreserveAsyncOrder = false;
     LocalImages = new RedisImagesCache(Redis, creds);
     _db         = Redis.GetDatabase();
     _redisKey   = creds.RedisKey();
 }
Example #24
0
 public FlipCoinCommands(IDataCache data, CurrencyService cs,
                         IBotConfigProvider bc, DbService db)
 {
     _images = data.LocalImages;
     _bc     = bc;
     _cs     = cs;
     _db     = db;
 }
Example #25
0
        public AvatarProvider(ISharedCache sharedCache, IImageCache imageCache)
        {
            cache = sharedCache.LocalMachine;
            this.imageCache = imageCache;

            DefaultUserBitmapImage = CreateBitmapImage("pack://application:,,,/GitHub.App;component/Images/default_user_avatar.png");
            DefaultOrgBitmapImage = CreateBitmapImage("pack://application:,,,/GitHub.App;component/Images/default_org_avatar.png");
        }
Example #26
0
    public ImageProvider(IImageCache cache)
    {
        _image_cache = cache;

        // set default max permissible size to 4k resolution
        MaxResolutionWidth  = 3840;
        MaxResolutionHeight = 2160;
    }
Example #27
0
        public Device(ITransport transport, IImageCache imageCache, ILogger logger)
        {
            _imageCache = imageCache;
            _transport  = transport;
            _logger     = logger;

            _imageCache.FlushAsync(new TimeSpan(30, 0, 0, 0));
        }
        public void Setup()
        {
            _cache = Substitute.For <IImageCache>();
            _avatarImageNameProvider = Substitute.For <IImageNameProvider>();
            _avatarImageNameProvider.Get(Email).Returns($"{Email}.png");

            _service = new GravatarService(_cache, _avatarImageNameProvider);
        }
        public AvatarProvider(ISharedCache sharedCache, IImageCache imageCache)
        {
            cache           = sharedCache.LocalMachine;
            this.imageCache = imageCache;

            DefaultUserBitmapImage = CreateBitmapImage("pack://application:,,,/GitHub.App;component/Images/default_user_avatar.png");
            DefaultOrgBitmapImage  = CreateBitmapImage("pack://application:,,,/GitHub.App;component/Images/default_org_avatar.png");
        }
        public TestImageCache()
        {
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(new InMemoryBlobCache());
            var environment = new Rothko.Environment();
            var imageDownloader = Substitute.For<IImageDownloader>();

            cacheDelegate = new ImageCache(cacheFactory, environment, new Lazy<IImageDownloader>(() => imageDownloader));
        }
Example #31
0
 public ImageDrawNode(ImageShapeViewModel image, ShapeStyleViewModel style, IImageCache imageCache, ICache <string, IDisposable> bitmapCache)
     : base()
 {
     Style       = style;
     Image       = image;
     ImageCache  = imageCache;
     BitmapCache = bitmapCache;
     UpdateGeometry();
 }
Example #32
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="shapes"></param>
        /// <param name="properties"></param>
        /// <param name="ic"></param>
        /// <returns></returns>
        public MemoryStream MakeMetafileStream(
            Bitmap bitmap,
            IEnumerable<BaseShape> shapes,
            ImmutableArray<ShapeProperty> properties,
            IImageCache ic)
        {
            var g = default(Graphics);
            var mf = default(Metafile);
            var ms = new MemoryStream();

            try
            {
                using (g = Graphics.FromImage(bitmap))
                {
                    var hdc = g.GetHdc();
                    mf = new Metafile(ms, hdc);
                    g.ReleaseHdc(hdc);
                }

                using (g = Graphics.FromImage(mf))
                {
                    var r = new EmfRenderer(72.0 / 96.0);
                    r.State.ImageCache = ic;

                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.PageUnit = GraphicsUnit.Display;

                    if (shapes != null)
                    {
                        foreach (var shape in shapes)
                        {
                            shape.Draw(g, r, 0, 0, properties, null);
                        }
                    }

                    r.ClearCache(isZooming: false);
                }
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }

                if (mf != null)
                {
                    mf.Dispose();
                }
            }
            return ms;
        }
Example #33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="container"></param>
 /// <param name="ic"></param>
 public void Save(Stream stream, IPageContainer container, IImageCache ic)
 {
     if (container != null && container.Template != null)
     {
         using var bitmap = new Bitmap((int)container.Template.Width, (int)container.Template.Height);
         using var ms     = MakeMetafileStream(bitmap, container, ic);
         ms.WriteTo(stream);
     }
 }
        public TerrainMapRenderer(ITerrainMap terrainMap, IImageFactory imageFactory, IImageCache imageCache, IPixelMapper pixelMapper)
        {
            _terrainMap   = terrainMap;
            _imageFactory = imageFactory;
            _imageCache   = imageCache;
            _pixelMapper  = pixelMapper;

            _terrainMap.CollectionChanged += (s, e) => _imageCache.SetDirty(this);
        }
        public ImageHandler(string baseRoute, IImageCache cache, IImageLoader[] loaders, Func<Type, string, object> convert = null, params Type[] declaredTypes)
        {
            if (loaders == null) throw new ArgumentNullException(nameof(loaders));

            baseRoute = baseRoute ?? "";
            if (baseRoute != "" && !baseRoute.EndsWith("/")) baseRoute += "/";

            this.baseRoute = "/" + baseRoute;
            this.cache = cache;
            this.loaders = loaders.ToArray();
            this.invoker = new ExtensionMethodInvoker(convert, new[] { typeof(ImageFiltering) }.Concat(declaredTypes).ToArray());

            Image.MaxWidth = Image.MaxHeight = 5000;
        }
		private readonly static object _lock = new object();	// codehint: sm-add

        #endregion

        #region Constructors

        public CommonController(IPaymentService paymentService,
			IShippingService shippingService,
            ICurrencyService currencyService,
			IMeasureService measureService,
            ICustomerService customerService,
			IUrlRecordService urlRecordService, 
			IWebHelper webHelper,
			CurrencySettings currencySettings,
            MeasureSettings measureSettings,
			IDateTimeHelper dateTimeHelper,
            ILanguageService languageService,
			IWorkContext workContext,
			IStoreContext storeContext,
            IPermissionService permissionService,
			ILocalizationService localizationService,
            IImageCache imageCache,
			SecuritySettings securitySettings,
			ITypeFinder typeFinder,
            IPluginFinder pluginFinder,
            IGenericAttributeService genericAttributeService,
			IDbContext dbContext)
        {
            this._paymentService = paymentService;
            this._shippingService = shippingService;
            this._currencyService = currencyService;
            this._measureService = measureService;
            this._customerService = customerService;
            this._urlRecordService = urlRecordService;
            this._webHelper = webHelper;
            this._currencySettings = currencySettings;
            this._measureSettings = measureSettings;
            this._dateTimeHelper = dateTimeHelper;
            this._languageService = languageService;
            this._workContext = workContext;
			this._storeContext = storeContext;
            this._permissionService = permissionService;
            this._localizationService = localizationService;
            this._imageCache = imageCache; // codehint: sm-add
            this._securitySettings = securitySettings; // codehint: sm-add
            this._typeFinder = typeFinder; // codehint: sm-add
			this._pluginFinder = pluginFinder;	// codehint: sm-add
            this._genericAttributeService = genericAttributeService; // codehint: sm-add
			this._dbContext = dbContext;	// codehint: sm-add
        }
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="pictureRepository">Picture repository</param>
 /// <param name="productPictureRepository">Product picture repository</param>
 /// <param name="settingService">Setting service</param>
 /// <param name="webHelper">Web helper</param>
 /// <param name="logger">Logger</param>
 /// <param name="eventPublisher">Event publisher</param>
 /// <param name="mediaSettings">Media settings</param>
 public PictureService(
     IRepository<Picture> pictureRepository,
     IRepository<ProductPicture> productPictureRepository,
     ISettingService settingService, 
     IWebHelper webHelper,
     ILogger logger, 
     IEventPublisher eventPublisher,
     MediaSettings mediaSettings,
     IImageResizerService imageResizerService,
     IImageCache imageCache)
 {
     this._pictureRepository = pictureRepository;
     this._productPictureRepository = productPictureRepository;
     this._settingService = settingService;
     this._webHelper = webHelper;
     this._logger = logger;
     this._eventPublisher = eventPublisher;
     this._mediaSettings = mediaSettings;
     this._imageResizerService = imageResizerService;
     this._imageCache = imageCache;
 }
        /// <summary>
        /// This will make the browser and server keep the output
        /// in its cache and thereby improve performance.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <param name="responseType">
        /// The HTTP MIME type to send.
        /// </param>
        /// <param name="dependencyPaths">
        /// The dependency path for the cache dependency.
        /// </param>
        private void SetHeaders(HttpContext context, string responseType, IEnumerable<string> dependencyPaths)
        {
            if (this.imageCache != null)
            {
                HttpResponse response = context.Response;

                if (response.Headers["ImageProcessedBy"] == null)
                {
                    response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion);
                }

                HttpCachePolicy cache = response.Cache;
                cache.SetCacheability(HttpCacheability.Public);
                cache.VaryByHeaders["Accept-Encoding"] = true;

                if (!string.IsNullOrWhiteSpace(responseType))
                {
                    response.ContentType = responseType;
                }

                if (dependencyPaths != null)
                {
                    context.Response.AddFileDependencies(dependencyPaths.ToArray());
                    cache.SetLastModifiedFromFileDependencies();
                }

                int maxDays = this.imageCache.MaxDays;

                cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
                cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

                this.imageCache = null;

                if (!string.IsNullOrEmpty(context.Request.Headers["Origin"]))
                {
                    string origin = context.Request.Headers["Origin"];

                    if (this.IsValidCorsRequest(origin))
                    {
                        response.AddHeader("Access-Control-Allow-Origin", origin);
                    }
                }
            }
        }
Example #39
0
 /// <summary>
 /// Initialises a new instance of the <see cref="Tweet"/> class.
 /// </summary>
 /// <param name="imageCache">
 /// The image cache.
 /// </param>
 public Tweet(IImageCache imageCache)
 {
     this.imageCache = imageCache;
 }
        /// <summary>
        /// Occurs when the ASP.NET event handler finishes execution.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task OnEndRequest(object sender, EventArgs e)
        {
            if (this.imageCache != null)
            {
                // Trim the cache.
                await this.imageCache.TrimCacheAsync();

                // Reset the cache.
                this.imageCache = null;
            }
        }
Example #41
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="container"></param>
 /// <param name="ic"></param>
 public void SetClipboard(Container container, IImageCache ic)
 {
     try
     {
         using (var bitmap = new Bitmap((int)container.Width, (int)container.Height))
         {
             using (var ms = MakeMetafileStream(bitmap, container, ic))
             {
                 var data = new WPF.DataObject();
                 data.SetData(WPF.DataFormats.EnhancedMetafile, ms);
                 WPF.Clipboard.SetDataObject(data, true);
             }
         }
     }
     catch (Exception ex)
     {
         Debug.Print(ex.Message);
         Debug.Print(ex.StackTrace);
     }
 }
Example #42
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="path"></param>
 /// <param name="container"></param>
 /// <param name="ic"></param>
 public void Save(string path, Container container, IImageCache ic)
 {
     using (var bitmap = new Bitmap((int)container.Width, (int)container.Height))
     {
         using (var ms = MakeMetafileStream(bitmap, container, ic))
         {
             using (var fs = File.Create(path))
             {
                 ms.WriteTo(fs);
             }
         }
     }
 }
 /// <summary>
 /// Initialises a new instance of the <see cref="L2TGrabber"/> class. 
 /// </summary>
 /// <param name="imageCache">
 /// The image cache.
 /// </param>
 /// <param name="context">
 /// The context.
 /// </param>
 public L2TGrabber(IImageCache imageCache, TwitterContext context)
 {
     this.imageCache = imageCache;
     this.context = context;
 }
 public ImageHandler(string baseRoute, IImageCache cache, params IImageLoader[] loaders) : this(baseRoute, cache, loaders, null) { }
        /// <summary>
        /// Initialises a new instance of the <see cref="ModerationForm"/> class.
        /// </summary>
        /// <param name="display">
        /// The display.
        /// </param>
        /// <param name="twitterGrabber">
        /// The twitter Grabber.
        /// </param>
        /// <param name="imageCache">
        /// The image Cache.
        /// </param>
        public ModerationForm(DisplayForm display, ITwitterGrabber twitterGrabber, IImageCache imageCache, TwitterContext context)
        {
            this.twitterGrabber = twitterGrabber;
            this.imageCache = imageCache;
            this.context = context;
            this.Display = display;

            this.InitializeComponent();
            this.tweetGrabberThread = new BackgroundWorker();
            this.tweetGrabberThread.DoWork += this.AddTweets;
            this.tweetGrabberThread.RunWorkerCompleted += this.TweetGrabberThreadRunWorkerCompleted;
        }
 public ImageCacheManager(IImageCache cache) {
     _cache = cache;
 }
Example #47
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="container"></param>
        /// <param name="ic"></param>
        /// <returns></returns>
        public MemoryStream MakeMetafileStream(
            Bitmap bitmap,
            Container container,
            IImageCache ic)
        {
            var g = default(Graphics);
            var mf = default(Metafile);
            var ms = new MemoryStream();

            try
            {
                using (g = Graphics.FromImage(bitmap))
                {
                    var hdc = g.GetHdc();
                    mf = new Metafile(ms, hdc);
                    g.ReleaseHdc(hdc);
                }

                using (g = Graphics.FromImage(mf))
                {
                    var r = new EmfRenderer(72.0 / 96.0);
                    r.State.ImageCache = ic;

                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.PageUnit = GraphicsUnit.Display;

                    if (container.Template != null)
                    {
                        r.Draw(g, container.Template, container.Properties, null);
                    }

                    r.Draw(g, container, container.Properties, null);
                    r.ClearCache(isZooming: false);
                }
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }

                if (mf != null)
                {
                    mf.Dispose();
                }
            }
            return ms;
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="TwitterGrabber"/> class.
 /// </summary>
 /// <param name="imageCache">
 /// The image cache.
 /// </param>
 public TwitterGrabber(IImageCache imageCache)
 {
     this.imageCache = imageCache;
 }
Example #49
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="shapes"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="properties"></param>
 /// <param name="ic"></param>
 public void SetClipboard(
     IEnumerable<BaseShape> shapes,
     double width,
     double height,
     ImmutableArray<ShapeProperty> properties,
     IImageCache ic)
 {
     try
     {
         using (var bitmap = new Bitmap((int)width, (int)height))
         {
             using (var ms = MakeMetafileStream(bitmap, shapes, properties, ic))
             {
                 var data = new WPF.DataObject();
                 data.SetData(WPF.DataFormats.EnhancedMetafile, ms);
                 WPF.Clipboard.SetDataObject(data, true);
             }
         }
     }
     catch (Exception ex)
     {
         Debug.Print(ex.Message);
         Debug.Print(ex.StackTrace);
     }
 }
        /// <summary>
        /// Occurs when the ASP.NET event handler finishes execution.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task PostProcessImage(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            object cachedPathObject = context.Items[CachedPathKey];

            if (cachedPathObject != null)
            {
                // Trim the cache.
                await this.imageCache.TrimCacheAsync();

                string cachedPath = cachedPathObject.ToString();

                // Fire the post processing event.
                EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
                if (handler != null)
                {
                    context.Items[CachedPathKey] = null;
                    await Task.Run(() => handler(this, new PostProcessingEventArgs { CachedImagePath = cachedPath }));
                }
            }

            // Reset the cache.
            this.imageCache = null;
        }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Should we ignore this request?
            if (request.Unvalidated.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
            {
                return;
            }

            IImageService currentService = this.GetImageServiceForRequest(request);

            if (currentService != null)
            {
                bool isFileLocal = currentService.IsFileLocalService;
                string url = request.Url.ToString();
                bool isLegacy = ProtocolRegex.Matches(url).Count > 1;
                bool hasMultiParams = url.Count(f => f == '?') > 1;
                string requestPath;
                string queryString = string.Empty;
                string urlParameters = string.Empty;

                // Legacy support. I'd like to remove this asap.
                if (isLegacy && hasMultiParams)
                {
                    // We need to split the querystring to get the actual values we want.
                    string[] paths = url.Split('?');
                    requestPath = paths[1];

                    // Handle extension-less urls.
                    if (paths.Length > 3)
                    {
                        queryString = paths[3];
                        urlParameters = paths[2];
                    }
                    else if (paths.Length > 1)
                    {
                        queryString = paths[2];
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(currentService.Prefix))
                    {
                        requestPath = currentService.IsFileLocalService
                            ? HostingEnvironment.MapPath(request.Path)
                            : request.Path;
                        queryString = request.QueryString.ToString();
                    }
                    else
                    {
                        // Parse any protocol values from settings.
                        string protocol = currentService.Settings.ContainsKey("Protocol")
                                              ? currentService.Settings["Protocol"] + "://"
                                              : string.Empty;

                        // Handle requests that require parameters.
                        if (hasMultiParams)
                        {
                            string[] paths = url.Split('?');
                            requestPath = protocol
                                          + request.Path.Replace(currentService.Prefix, string.Empty).TrimStart('/')
                                          + "?" + paths[1];
                            queryString = paths[2];
                        }
                        else
                        {
                            requestPath = protocol + request.Path.Replace(currentService.Prefix, string.Empty).TrimStart('/');
                            queryString = request.QueryString.ToString();
                        }
                    }
                }

                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                // Execute the handler which can change the querystring 
                queryString = this.CheckQuerystringHandler(queryString, request.Unvalidated.RawUrl);

                // If the current service doesn't require a prefix, don't fetch it.
                // Let the static file handler take over.
                if (string.IsNullOrWhiteSpace(currentService.Prefix) && string.IsNullOrWhiteSpace(queryString))
                {
                    return;
                }

                if (string.IsNullOrWhiteSpace(requestPath))
                {
                    return;
                }

                string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
                string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
                object resourcePath;

                // More legacy support code.
                if (hasMultiParams)
                {
                    resourcePath = string.IsNullOrWhiteSpace(urlParameters)
                        ? new Uri(requestPath, UriKind.RelativeOrAbsolute)
                        : new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    resourcePath = requestPath;
                }

                // Check whether the path is valid for other requests.
                if (!currentService.IsValidRequest(resourcePath.ToString()))
                {
                    return;
                }

                string combined = requestPath + fullPath + queryString;
                using (await Locker.LockAsync(combined))
                {
                    // Create a new cache to help process and cache the request.
                    this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
                        .ImageCache.GetInstance(requestPath, fullPath, queryString);

                    // Is the file new or updated?
                    bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
                    string cachedPath = this.imageCache.CachedPath;

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        // Process the image.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value))
                        {
                            byte[] imageBuffer = await currentService.GetImage(resourcePath);

                            using (MemoryStream inStream = new MemoryStream(imageBuffer))
                            {
                                // Process the Image
                                using (MemoryStream outStream = new MemoryStream())
                                {
                                    imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream);

                                    // Add to the cache.
                                    await this.imageCache.AddImageToCacheAsync(outStream, imageFactory.CurrentImageFormat.MimeType);
                                }
                            }

                            // Store the cached path, response type, and cache dependency in the context for later retrieval.
                            context.Items[CachedPathKey] = cachedPath;
                            context.Items[CachedResponseTypeKey] = imageFactory.CurrentImageFormat.MimeType;
                            bool isFileCached = new Uri(cachedPath).IsFile;

                            if (isFileLocal)
                            {
                                if (isFileCached)
                                {
                                    // Some services might only provide filename so we can't monitor for the browser.
                                    context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                        ? new List<string> { cachedPath }
                                        : new List<string> { requestPath, cachedPath };
                                }
                                else
                                {
                                    context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                        ? null
                                        : new List<string> { requestPath };
                                }
                            }
                            else if (isFileCached)
                            {
                                context.Items[CachedResponseFileDependency] = new List<string> { cachedPath };
                            }
                        }
                    }

                    // The cached file is valid so just rewrite the path.
                    this.imageCache.RewritePath(context);

                    // Redirect if not a locally store file.
                    if (!new Uri(cachedPath).IsFile)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }
Example #52
0
 private static void WriteImages(IImageCache cache, IEnumerable<string> keys, ZipArchive archive, IFileSystem fileIO)
 {
     foreach (var key in keys)
     {
         var imageEntry = archive.CreateEntry(key);
         using (var imageStream = imageEntry.Open())
         {
             fileIO.WriteBinary(imageStream, cache.GetImage(key));
         }
     }
 }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Should we ignore this request?
            if (request.Unvalidated.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
            {
                return;
            }

            IImageService currentService = this.GetImageServiceForRequest(request);

            if (currentService != null)
            {
                bool isFileLocal = currentService.IsFileLocalService;
                string url = request.Url.ToString();
                bool isLegacy = ProtocolRegex.Matches(url).Count > 1;
                bool hasMultiParams = url.Count(f => f == '?') > 1;
                string requestPath;
                string queryString = string.Empty;
                string urlParameters = string.Empty;

                // Legacy support. I'd like to remove this asap.
                if (isLegacy && hasMultiParams)
                {
                    // We need to split the querystring to get the actual values we want.
                    string[] paths = url.Split('?');
                    requestPath = paths[1];

                    // Handle extension-less urls.
                    if (paths.Length > 3)
                    {
                        queryString = paths[3];
                        urlParameters = paths[2];
                    }
                    else if (paths.Length > 1)
                    {
                        queryString = paths[2];
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(currentService.Prefix))
                    {
                        requestPath = currentService.IsFileLocalService
                            ? HostingEnvironment.MapPath(request.Path)
                            : request.Path;
                        queryString = request.QueryString.ToString();
                    }
                    else
                    {
                        // Parse any protocol values from settings.
                        string protocol = currentService.Settings.ContainsKey("Protocol")
                                              ? currentService.Settings["Protocol"] + "://"
                                              : currentService.GetType() == typeof(RemoteImageService) ? request.Url.Scheme + "://" : string.Empty;

                        // Handle requests that require parameters.
                        if (hasMultiParams)
                        {
                            string[] paths = url.Split('?');
                            requestPath = protocol
                                          + request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/')
                                          + "?" + paths[1];
                            queryString = paths[2];
                        }
                        else
                        {
                            requestPath = protocol + request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/');
                            queryString = request.QueryString.ToString();
                        }
                    }
                }

                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                HttpContextWrapper httpContextBase = new HttpContextWrapper(context);

                // Execute the handler which can change the querystring 
                //  LEGACY:
#pragma warning disable 618
                queryString = this.CheckQuerystringHandler(context, queryString, request.Unvalidated.RawUrl);
#pragma warning restore 618

                // NEW WAY:
                ValidatingRequestEventArgs validatingArgs = new ValidatingRequestEventArgs(httpContextBase, queryString);
                this.OnValidatingRequest(validatingArgs);

                // If the validation has failed based on events, return
                if (validatingArgs.Cancel)
                {
                    ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>("Image processing has been cancelled by an event");
                    return;
                }

                // Re-assign based on event handlers
                queryString = validatingArgs.QueryString;

                // Break out if we don't meet critera.
                bool interceptAll = interceptAllRequests != null && interceptAllRequests.Value;
                if (string.IsNullOrWhiteSpace(requestPath) || (!interceptAll && string.IsNullOrWhiteSpace(queryString)))
                {
                    return;
                }

                string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
                string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
                object resourcePath;

                // More legacy support code.
                if (hasMultiParams)
                {
                    resourcePath = string.IsNullOrWhiteSpace(urlParameters)
                        ? new Uri(requestPath, UriKind.RelativeOrAbsolute)
                        : new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    resourcePath = requestPath;
                }

                // Check whether the path is valid for other requests.
                // We've already checked the unprefixed requests in GetImageServiceForRequest().
                if (!string.IsNullOrWhiteSpace(currentService.Prefix) && !currentService.IsValidRequest(resourcePath.ToString()))
                {
                    return;
                }

                string combined = requestPath + fullPath;

                using (await Locker.LockAsync(combined))
                {
                    // Create a new cache to help process and cache the request.
                    this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
                        .ImageCache.GetInstance(requestPath, fullPath, queryString);

                    // Is the file new or updated?
                    bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
                    string cachedPath = this.imageCache.CachedPath;

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        byte[] imageBuffer = null;
                        string mimeType;

                        try
                        {
                            imageBuffer = await currentService.GetImage(resourcePath);
                        }
                        catch (HttpException ex)
                        {
                            // We want 404's to be handled by IIS so that other handlers/modules can still run.
                            if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
                            {
                                ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(ex.Message);
                                return;
                            }
                        }

                        if (imageBuffer == null)
                        {
                            return;
                        }

                        using (MemoryStream inStream = new MemoryStream(imageBuffer))
                        {
                            // Process the Image
                            MemoryStream outStream = new MemoryStream();

                            if (!string.IsNullOrWhiteSpace(queryString))
                            {
                                // Animation is not a processor but can be a specific request so we should allow it.
                                bool processAnimation;
                                AnimationProcessMode mode = this.ParseAnimationMode(queryString, out processAnimation);

                                // Attempt to match querystring and processors.
                                IWebGraphicsProcessor[] processors = ImageFactoryExtensions.GetMatchingProcessors(queryString);
                                if (processors.Any() || processAnimation)
                                {
                                    // Process the image.
                                    bool exif = preserveExifMetaData != null && preserveExifMetaData.Value;
                                    bool gamma = fixGamma != null && fixGamma.Value;
                                  
                                    using (ImageFactory imageFactory = new ImageFactory(exif, gamma) { AnimationProcessMode = mode })
                                    {
                                        imageFactory.Load(inStream).AutoProcess(processors).Save(outStream);
                                        mimeType = imageFactory.CurrentImageFormat.MimeType;
                                    }
                                }
                                else if (this.ParseCacheBuster(queryString))
                                {
                                    // We're cachebustng. Allow the value to be cached
                                    await inStream.CopyToAsync(outStream);
                                    mimeType = FormatUtilities.GetFormat(outStream).MimeType;
                                }
                                else
                                {
                                    // No match? Someone is either attacking the server or hasn't read the instructions. 
                                    // Either way throw an exception to prevent caching.
                                    string message = string.Format(
                                            "The request {0} could not be understood by the server due to malformed syntax.",
                                            request.Unvalidated.RawUrl);
                                    ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(message);
                                    throw new HttpException((int)HttpStatusCode.BadRequest, message);
                                }
                            }
                            else
                            {
                                // We're capturing all requests.
                                await inStream.CopyToAsync(outStream);
                                mimeType = FormatUtilities.GetFormat(outStream).MimeType;
                            }

                            // Fire the post processing event.
                            EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
                            if (handler != null)
                            {
                                string extension = Path.GetExtension(cachedPath);
                                PostProcessingEventArgs args = new PostProcessingEventArgs
                                {
                                    Context = context,
                                    ImageStream = outStream,
                                    ImageExtension = extension
                                };

                                handler(this, args);
                                outStream = args.ImageStream;
                            }

                            // Add to the cache.
                            await this.imageCache.AddImageToCacheAsync(outStream, mimeType);

                            // Cleanup
                            outStream.Dispose();
                        }

                        // Store the response type and cache dependency in the context for later retrieval.
                        context.Items[CachedResponseTypeKey] = mimeType;
                        bool isFileCached = new Uri(cachedPath).IsFile;

                        if (isFileLocal)
                        {
                            if (isFileCached)
                            {
                                // Some services might only provide filename so we can't monitor for the browser.
                                context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                    ? new[] { cachedPath }
                                    : new[] { requestPath, cachedPath };
                            }
                            else
                            {
                                context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                    ? null
                                    : new[] { requestPath };
                            }
                        }
                        else if (isFileCached)
                        {
                            context.Items[CachedResponseFileDependency] = new[] { cachedPath };
                        }
                    }

                    // The cached file is valid so just rewrite the path.
                    this.imageCache.RewritePath(context);

                    // Redirect if not a locally store file.
                    if (!new Uri(cachedPath).IsFile)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Should we ignore this request?
            if (request.Unvalidated.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
            {
                return;
            }

            IImageService currentService = this.GetImageServiceForRequest(request);

            if (currentService != null)
            {
                bool isFileLocal = currentService.IsFileLocalService;
                string url = request.Url.ToString();
                bool isLegacy = ProtocolRegex.Matches(url).Count > 1;
                bool hasMultiParams = url.Count(f => f == '?') > 1;
                string requestPath;
                string queryString = string.Empty;
                string urlParameters = string.Empty;

                // Legacy support. I'd like to remove this asap.
                if (isLegacy && hasMultiParams)
                {
                    // We need to split the querystring to get the actual values we want.
                    string[] paths = url.Split('?');
                    requestPath = paths[1];

                    // Handle extension-less urls.
                    if (paths.Length > 3)
                    {
                        queryString = paths[3];
                        urlParameters = paths[2];
                    }
                    else if (paths.Length > 1)
                    {
                        queryString = paths[2];
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(currentService.Prefix))
                    {
                        requestPath = currentService.IsFileLocalService
                            ? HostingEnvironment.MapPath(request.Path)
                            : request.Path;
                        queryString = request.QueryString.ToString();
                    }
                    else
                    {
                        // Parse any protocol values from settings.
                        string protocol = currentService.Settings.ContainsKey("Protocol")
                                              ? currentService.Settings["Protocol"] + "://"
                                              : currentService.GetType() == typeof(RemoteImageService) ? request.Url.Scheme + "://" : string.Empty;

                        // Handle requests that require parameters.
                        if (hasMultiParams)
                        {
                            string[] paths = url.Split('?');
                            requestPath = protocol
                                          + request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/')
                                          + "?" + paths[1];
                            queryString = paths[2];
                        }
                        else
                        {
                            requestPath = protocol + request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/');
                            queryString = request.QueryString.ToString();
                        }
                    }
                }

                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                // Execute the handler which can change the querystring 
                queryString = this.CheckQuerystringHandler(context, queryString, request.Unvalidated.RawUrl);

                // Break out if we don't meet critera.
                bool interceptAll = interceptAllRequests != null && interceptAllRequests.Value;
                if (string.IsNullOrWhiteSpace(requestPath) || (!interceptAll && string.IsNullOrWhiteSpace(queryString)))
                {
                    return;
                }

                string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
                string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
                object resourcePath;

                // More legacy support code.
                if (hasMultiParams)
                {
                    resourcePath = string.IsNullOrWhiteSpace(urlParameters)
                        ? new Uri(requestPath, UriKind.RelativeOrAbsolute)
                        : new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    resourcePath = requestPath;
                }

                // Check whether the path is valid for other requests.
                if (!currentService.IsValidRequest(resourcePath.ToString()))
                {
                    return;
                }

                string combined = requestPath + fullPath + queryString;
                using (await Locker.LockAsync(combined))
                {
                    // Create a new cache to help process and cache the request.
                    this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
                        .ImageCache.GetInstance(requestPath, fullPath, queryString);

                    // Is the file new or updated?
                    bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
                    string cachedPath = this.imageCache.CachedPath;

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        // Process the image.
                        bool exif = preserveExifMetaData != null && preserveExifMetaData.Value;
                        bool gamma = fixGamma != null && fixGamma.Value;
                        using (ImageFactory imageFactory = new ImageFactory(exif, gamma))
                        {
                            byte[] imageBuffer = null;
                            string mimeType;

                            try
                            {
                                imageBuffer = await currentService.GetImage(resourcePath);
                            }
                            catch (HttpException ex)
                            {
                                // We want 404's to be handled by IIS so that other handlers/modules can still run.
                                if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
                                {
                                    return;
                                }
                            }

                            if (imageBuffer == null)
                            {
                                return;
                            }

                            using (MemoryStream inStream = new MemoryStream(imageBuffer))
                            {
                                // Process the Image
                                MemoryStream outStream = new MemoryStream();

                                if (!string.IsNullOrWhiteSpace(queryString))
                                {
                                    imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream);
                                    mimeType = imageFactory.CurrentImageFormat.MimeType;
                                }
                                else
                                {
                                    await inStream.CopyToAsync(outStream);
                                    mimeType = FormatUtilities.GetFormat(outStream).MimeType;
                                }

                                // Fire the post processing event.
                                EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
                                if (handler != null)
                                {
                                    string extension = Path.GetExtension(cachedPath);
                                    PostProcessingEventArgs args = new PostProcessingEventArgs
                                    {
                                        Context = context,
                                        ImageStream = outStream,
                                        ImageExtension = extension
                                    };

                                    handler(this, args);
                                    outStream = args.ImageStream;
                                }

                                // Add to the cache.
                                await this.imageCache.AddImageToCacheAsync(outStream, mimeType);

                                // Cleanup
                                outStream.Dispose();
                            }

                            // Store the response type and cache dependency in the context for later retrieval.
                            context.Items[CachedResponseTypeKey] = mimeType;
                            bool isFileCached = new Uri(cachedPath).IsFile;

                            if (isFileLocal)
                            {
                                if (isFileCached)
                                {
                                    // Some services might only provide filename so we can't monitor for the browser.
                                    context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                        ? new List<string> { cachedPath }
                                        : new List<string> { requestPath, cachedPath };
                                }
                                else
                                {
                                    context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                        ? null
                                        : new List<string> { requestPath };
                                }
                            }
                            else if (isFileCached)
                            {
                                context.Items[CachedResponseFileDependency] = new List<string> { cachedPath };
                            }
                        }
                    }

                    // The cached file is valid so just rewrite the path.
                    this.imageCache.RewritePath(context);

                    // Redirect if not a locally store file.
                    if (!new Uri(cachedPath).IsFile)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }
        public static Image GetImageFromCache(string imageFileName, string email, int cacheDays,
                                             int imageSize, string imageCachePath, FallBackService fallBack)
        {
            try
            {
                if (cache == null)
                    cache = new DirectoryImageCache(imageCachePath); //or: new IsolatedStorageImageCache();

                // If the user image is not cached yet, download it from gravatar and store it in the isolatedStorage
                if (!cache.FileIsCached(imageFileName) ||
                    cache.FileIsExpired(imageFileName, cacheDays))
                {
                    return null;
                }
                if (cache.FileIsCached(imageFileName))
                {
                    return cache.LoadImageFromCache(imageFileName, null);
                }

            }
            catch (Exception ex)
            {
                //catch IO errors
                Trace.WriteLine(ex.Message);
            }
            return null;
        }
Example #56
0
 private static void ReadImages(IImageCache cache, ZipArchive archive, IFileSystem fileIO)
 {
     foreach (var entry in archive.Entries)
     {
         if (entry.FullName.StartsWith(ImageEntryNamePrefix))
         {
             using (var entryStream = entry.Open())
             {
                 var bytes = fileIO.ReadBinary(entryStream);
                 cache.AddImage(entry.FullName, bytes);
             }
         }
     }
 }
 public UserDetailsViewModel(ISlackClient slack, IImageCache imageCache)
 {
     _slack = slack;
     _imageCache = imageCache;
 }
Example #58
0
 public ImageService(IImageRepository repository, IImageCache cache)
 {
     Repository = repository;
     Cache = cache;
 }
 protected GenericImageController(IImageBlobManager blobManager, IImageCache imageCache)
 {
     _imageBlobManager = blobManager;
     _imageCache = imageCache;
 }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;
            string rawUrl = request.Unvalidated.RawUrl;

            // Should we ignore this request?
            if (string.IsNullOrWhiteSpace(rawUrl) || rawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
            {
                return;
            }

            // Sometimes the request is url encoded so we have to decode.
            // See https://github.com/JimBobSquarePants/ImageProcessor/issues/478
            // This causes a bit of a nightmare as the incoming request is corrupted and cannot be used for splitting 
            // out each url part. This becomes a manual job.
            string url = this.DecodeUrlString(rawUrl);
            string applicationPath = request.ApplicationPath;

            IImageService currentService = this.GetImageServiceForRequest(url, applicationPath);

            if (currentService != null)
            {
                // Remove any service identifier prefixes from the url.
                string prefix = currentService.Prefix;
                if (!string.IsNullOrWhiteSpace(prefix))
                {
                    url = url.Split(new[] { prefix }, StringSplitOptions.None)[1].TrimStart("?");
                }

                // Identify each part of the incoming request.
                int queryCount = url.Count(f => f == '?');
                bool hasParams = queryCount > 0;
                bool hasMultiParams = queryCount > 1;
                string[] splitPath = url.Split('?');

                // Ensure we include any relevent querystring parameters into our request path for third party requests.
                string requestPath = hasMultiParams ? string.Join("?", splitPath.Take(splitPath.Length - 1)) : splitPath[0];
                string queryString = hasParams ? splitPath[splitPath.Length - 1] : string.Empty;

                // Map the request path if file local.
                bool isFileLocal = currentService.IsFileLocalService;
                if (currentService.IsFileLocalService)
                {
                    requestPath = HostingEnvironment.MapPath(requestPath);
                }

                // Parse any protocol values from settings if no protocol is present.
                if (currentService.Settings.ContainsKey("Protocol") && (ProtocolRegex.Matches(url).Count == 0 || ProtocolRegex.Matches(url)[0].Index > 0))
                {
                    // ReSharper disable once PossibleNullReferenceException
                    requestPath = currentService.Settings["Protocol"] + "://" + requestPath.TrimStart('/');
                }

                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                HttpContextWrapper httpContextBase = new HttpContextWrapper(context);

                // Execute the handler which can change the querystring 
                //  LEGACY:
#pragma warning disable 618
                queryString = this.CheckQuerystringHandler(context, queryString, rawUrl);
#pragma warning restore 618

                // NEW WAY:
                ValidatingRequestEventArgs validatingArgs = new ValidatingRequestEventArgs(httpContextBase, queryString);
                this.OnValidatingRequest(validatingArgs);

                // If the validation has failed based on events, return
                if (validatingArgs.Cancel)
                {
                    ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>("Image processing has been cancelled by an event");
                    return;
                }

                // Re-assign based on event handlers
                queryString = validatingArgs.QueryString;

                // Break out if we don't meet critera.
                bool interceptAll = interceptAllRequests != null && interceptAllRequests.Value;
                if (string.IsNullOrWhiteSpace(requestPath) || (!interceptAll && string.IsNullOrWhiteSpace(queryString)))
                {
                    return;
                }

                // Check whether the path is valid for other requests.
                // We've already checked the unprefixed requests in GetImageServiceForRequest().
                if (!string.IsNullOrWhiteSpace(prefix) && !currentService.IsValidRequest(requestPath))
                {
                    return;
                }

                using (await Locker.LockAsync(rawUrl))
                {
                    // Create a new cache to help process and cache the request.
                    this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
                        .ImageCache.GetInstance(requestPath, url, queryString);

                    // Is the file new or updated?
                    bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
                    string cachedPath = this.imageCache.CachedPath;

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        byte[] imageBuffer = null;
                        string mimeType;

                        try
                        {
                            imageBuffer = await currentService.GetImage(requestPath);
                        }
                        catch (HttpException ex)
                        {
                            // We want 404's to be handled by IIS so that other handlers/modules can still run.
                            if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
                            {
                                ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(ex.Message);
                                return;
                            }
                        }

                        if (imageBuffer == null)
                        {
                            return;
                        }

                        using (MemoryStream inStream = new MemoryStream(imageBuffer))
                        {
                            // Process the Image
                            MemoryStream outStream = new MemoryStream();

                            if (!string.IsNullOrWhiteSpace(queryString))
                            {
                                // Animation is not a processor but can be a specific request so we should allow it.
                                bool processAnimation;
                                AnimationProcessMode mode = this.ParseAnimationMode(queryString, out processAnimation);

                                // Attempt to match querystring and processors.
                                IWebGraphicsProcessor[] processors = ImageFactoryExtensions.GetMatchingProcessors(queryString);
                                if (processors.Any() || processAnimation)
                                {
                                    // Process the image.
                                    bool exif = preserveExifMetaData != null && preserveExifMetaData.Value;
                                    bool gamma = fixGamma != null && fixGamma.Value;

                                    using (ImageFactory imageFactory = new ImageFactory(exif, gamma) { AnimationProcessMode = mode })
                                    {
                                        imageFactory.Load(inStream).AutoProcess(processors).Save(outStream);
                                        mimeType = imageFactory.CurrentImageFormat.MimeType;
                                    }
                                }
                                else if (this.ParseCacheBuster(queryString))
                                {
                                    // We're cachebustng. Allow the value to be cached
                                    await inStream.CopyToAsync(outStream);
                                    mimeType = FormatUtilities.GetFormat(outStream).MimeType;
                                }
                                else
                                {
                                    // No match? Someone is either attacking the server or hasn't read the instructions. 
                                    // Either way throw an exception to prevent caching.
                                    string message = $"The request {request.Unvalidated.RawUrl} could not be understood by the server due to malformed syntax.";
                                    ImageProcessorBootstrapper.Instance.Logger.Log<ImageProcessingModule>(message);
                                    throw new HttpException((int)HttpStatusCode.BadRequest, message);
                                }
                            }
                            else
                            {
                                // We're capturing all requests.
                                await inStream.CopyToAsync(outStream);
                                mimeType = FormatUtilities.GetFormat(outStream).MimeType;
                            }

                            // Fire the post processing event.
                            EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
                            if (handler != null)
                            {
                                string extension = Path.GetExtension(cachedPath);
                                PostProcessingEventArgs args = new PostProcessingEventArgs
                                {
                                    Context = context,
                                    ImageStream = outStream,
                                    ImageExtension = extension
                                };

                                handler(this, args);
                                outStream = args.ImageStream;
                            }

                            // Add to the cache.
                            await this.imageCache.AddImageToCacheAsync(outStream, mimeType);

                            // Cleanup
                            outStream.Dispose();
                        }

                        // Store the response type and cache dependency in the context for later retrieval.
                        context.Items[CachedResponseTypeKey] = mimeType;
                        bool isFileCached = new Uri(cachedPath).IsFile;

                        if (isFileLocal)
                        {
                            if (isFileCached)
                            {
                                // Some services might only provide filename so we can't monitor for the browser.
                                context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                    ? new[] { cachedPath }
                                    : new[] { requestPath, cachedPath };
                            }
                            else
                            {
                                context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                    ? null
                                    : new[] { requestPath };
                            }
                        }
                        else if (isFileCached)
                        {
                            context.Items[CachedResponseFileDependency] = new[] { cachedPath };
                        }
                    }

                    // The cached file is valid so just rewrite the path.
                    this.imageCache.RewritePath(context);

                    // Redirect if not a locally store file.
                    if (!new Uri(cachedPath).IsFile)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }