//--------------------------------------------------------------------------------
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(ImagesPath))
            ImagesPath = Page.MapPath("Images");

        cache = Helper.GetImageCache(ImagesPath);
        if (cache == null)
            return;

        PageCounterDown.OnClick += new PageCounter.OnClickDelegate(PageCounter_OnClick);
        PageCounterUp.OnClick += new PageCounter.OnClickDelegate(PageCounter_OnClick);

        int start = 0;
        int.TryParse(Start.Value, out start);
        int currentPage = (int)Math.Ceiling((float)start / (float)ImageCache.maxPerPage);
        PageCounterUp.Pages = PageCounterDown.Pages = cache.pages;
        PageCounterUp.CurrentPage = PageCounterDown.CurrentPage = currentPage;
        PageCounterUp.DrawPages();
        PageCounterDown.DrawPages();

        ImagesTitle.InnerText = Title;
        ImagesTable.Style[HtmlTextWriterStyle.MarginLeft] = "auto";
        ImagesTable.Style[HtmlTextWriterStyle.MarginRight] = "auto";
        ImagesTable.Width = Unit.Percentage(95);

        if (!Page.IsPostBack)
            DrawTable();
        Spot1.Visible = !HideAds;
    }
Exemple #2
0
        public StashGrid(PoEItemTable itemTable, ImageCache imageCache) {
            InitializeComponent();

            GridPen = Pens.Black;
            _itemTable = itemTable;
            _itemInfoPopup = new ItemInfoPopup(_itemTable);
            _imageCache = imageCache;
        }
 public DefaultRootFolderHandler(
     TheImport import,
     EnhancedDriveInfo drive_sInfo,
     string rootFolder,
     List<EnhancedFileInfo> foundFiles,
     ImageCache cachedImages)
     : base(import, drive_sInfo, rootFolder, foundFiles, cachedImages)
 {
 }
Exemple #4
0
        // this is a shallow cache for the images that are loaded via this item

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string url = value?.ToString();

            if (url != null)
            {
                return(ImageCache.GetImage(url));
            }
            return(null);
        }
Exemple #5
0
        public void CreateNewPage(float winWidth, float winHeight, MessureUnit unit, float resolution)
        {
            _page         = new Page(winWidth, winHeight, unit);
            Resolution    = resolution;
            ViewportWidth = (int)WinToView(winWidth);
            ViewportHeith = (int)WinToView(winHeight);
            SetViewSize(ViewportWidth, ViewportHeith);

            _imageCache = new ImageCache(_shapeDrawer, _page, ViewportWidth, ViewportHeith);
        }
        public StashImageSummarizer(ImageCache imgCache) {
            _imageCache = imgCache;

            _client = new HttpClient();

            BackgroundColor = Color.DimGray;
            GridColor = Color.Black;
            IncludeGrid = true;
            CellSize = 32;
        }
Exemple #7
0
        private void cacheImage()
        {
            HitObject   = new GameObject();
            ImageAssets = HitObject.AddComponent <ImageCache>();
            ImageAssets.imageFiles.Clear();
            string dataDirectory = "file://" + Interface.Oxide.DataDirectory + Path.DirectorySeparatorChar;

            ImageAssets.getImage("hitimage", dataDirectory + "hit.png");
            download();
        }
Exemple #8
0
        public void TestImageResize()
        {
            ImageCache cache = new ImageCache(tempPath);
            Guid       id    = Guid.NewGuid();
            Image      image = Image.FromFile(imagePath1);

            cache.CacheImage(id, image);

            Assert.IsTrue(File.Exists(cache.GetImagePath(id, 50, 50)));
        }
Exemple #9
0
 protected AbstractImageBuilder()
 {
     renderQueue         = new Queue <RenderParams>();
     completionCallbacks = new Dictionary <CallbackToken, List <RequestImageCallback> >();
     imageCache          = Service.Get <ImageCache>();
     if (imageCache == null)
     {
         Log.LogError(this, "ImageCache service not started!");
     }
 }
Exemple #10
0
        protected virtual void InitializeControls()
        {
            SetupName(_name);

            SetupCollectionView(_collectionView);

            _accessoryImageView.Image = ImageCache.GetImage("Images/Main/accessory_arrow.png");

            _bottomSeparator.BackgroundColor = Theme.ColorPalette.Separator.ToUIColor();
        }
Exemple #11
0
        public void TestCacheUpgrade()
        {
            Guid upgradeId = Guid.NewGuid();

            File.Copy(imagePath1, Path.Combine(tempPath, upgradeId.ToString() + ".png"));

            ImageCache cache = new ImageCache(tempPath);

            Assert.IsTrue(File.Exists(cache.GetImagePath(upgradeId)));
        }
 public ChainByTagsRootFolderHandler(
     TheImport import,
     EnhancedDriveInfo driveSInfo,
     string rootFolder,
     List<EnhancedFileInfo> foundFiles,
     ImageCache cachedImages)
     : base(import, driveSInfo, rootFolder, foundFiles, cachedImages)
 {
     this.item2File = new Item2File();
 }
Exemple #13
0
        private void cacheImage()
        {
            AdminPanelObject = new GameObject();
            ImageAssets      = AdminPanelObject.AddComponent <ImageCache>();
            ImageAssets.imageFiles.Clear();
            string dataDirectory = "file://" + Interface.Oxide.DataDirectory + Path.DirectorySeparatorChar + "AdminPanel" + Path.DirectorySeparatorChar + "img" + Path.DirectorySeparatorChar;

            ImageAssets.getImage("AdminPanalImage", dataDirectory + serverBanner);
            download();
        }
Exemple #14
0
 public SaveFile(Handler handler)
 {
     this.handler     = handler;
     this.ID          = ActionID;
     this.MenuText    = "&Save";
     this.ToolBarText = "Save";
     this.ToolTip     = "Saves the current file";
     this.Image       = ImageCache.IconFromResource("Pablo.Icons.save.ico");
     this.Shortcut    = PabloCommand.CommonModifier | Keys.S;
 }
        // This is only get called by ItemDetailsPage.Episodesitem_ContainerContentChanging
        public async void LoadImage(ListViewBase sender, ContainerContentChangingEventArgs args)
        {
            if (contentlist.State != Models.MediaList.MediaListState.OFFLINE)
            {
                var file = await ImageCache.GetFromCacheAsync(contentlist.Thumbnail.AbsoluteUri);

                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var img = new BitmapImage
                    {
                        DecodePixelWidth = 180,
                        CreateOptions    = BitmapCreateOptions.IgnoreImageCache
                    };
                    await img.SetSourceAsync(fileStream);

                    Thumbnail.Source = img;
                }
            }
            else
            {
                var file = await StorageFile.GetFileFromPathAsync(contentlist.Thumbnail.LocalPath);

                var thumbnail = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.VideosView);

                var img = new BitmapImage
                {
                    DecodePixelWidth = 180,
                    CreateOptions    = BitmapCreateOptions.IgnoreImageCache
                };
                await img.SetSourceAsync(thumbnail);

                Thumbnail.Source = img;
            }



            DoubleAnimation animation = new DoubleAnimation
            {
                From           = 0,
                To             = 1,
                Duration       = new Duration(TimeSpan.FromMilliseconds(700)),
                EasingFunction = new ExponentialEase
                {
                    Exponent   = 7,
                    EasingMode = EasingMode.EaseOut
                }
            };
            Storyboard ImageOpenedOpacity = new Storyboard();

            ImageOpenedOpacity.Children.Add(animation);

            Storyboard.SetTarget(ImageOpenedOpacity, Thumbnail);
            Storyboard.SetTargetProperty(ImageOpenedOpacity, "Opacity");
            ImageOpenedOpacity.Begin();
        }
Exemple #16
0
        private void OnReLoadClick(object sender, EventArgs e)
        {
            if (pictureGrid.CurrentRow != null)
            {
                pictureGrid.CurrentRow.Cells["uploadStateCol"].Value = "正在上传";
                ImageCache    imageCache = new ImageCache();
                CnasRemotCall remoteCall = new CnasRemotCall();
                string        fileName   = pictureGrid.CurrentRow.Cells["filePathCol"].Value != null ?
                                           pictureGrid.CurrentRow.Cells["filePathCol"].Value.ToString() : string.Empty;
                string imageName = pictureGrid.CurrentRow.Cells["imageNameCol"].Value != null ?
                                   pictureGrid.CurrentRow.Cells["imageNameCol"].Value.ToString() : string.Empty;
                bool upLoadResult = false;
                if (!string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(imageName) &&
                    File.Exists(fileName))
                {
                    Bitmap image = new System.Drawing.Bitmap(fileName);
                    pictureGrid.CurrentRow.Cells["imageCol"].Value = image;
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        //update the file to remote machine.
                        image.Save(memStream, ImageFormat.Jpeg);
                        upLoadResult = imageCache.SaveImageCache(_uploadFolder, imageName, memStream);
                    }

                    //Save the data in db.
                    if (upLoadResult)
                    {
                        if (!string.IsNullOrEmpty(imageName))
                        {
                            SortedList sqlParameters = new SortedList();
                            SortedList imageItem     = new SortedList();
                            sqlParameters.Add(1, imageItem);
                            imageItem.Add(1, GetUploadType());
                            imageItem.Add(2, _objectId);
                            imageItem.Add(3, BarCode);
                            imageItem.Add(4, imageName);
                            imageItem.Add(5, "8");
                            string testSql      = remoteCall.RemotInterface.CheckUPDataList("HCS_image-data-add001", sqlParameters);
                            int    insertResult = remoteCall.RemotInterface.UPDataList("HCS_image-data-add001", sqlParameters);
                            upLoadResult = insertResult > 0 && upLoadResult;
                        }
                    }
                    pictureGrid.CurrentRow.Cells["uploadStateCol"].Value = upLoadResult ? "上传完成" : "上传失败";
                    pictureGrid.CurrentRow.Cells["statusCol"].Value      = upLoadResult ? 1 : 0;
                    pictureGrid.CurrentRow.Cells["imageStateCol"].Value  = 8;
                    if (pictureGrid.CurrentRow.Cells["imageCol"].Value != null && pictureGrid.CurrentRow.Cells["imageCol"].Value is Image)
                    {
                        picturePreview.Images = new List <Image>()
                        {
                            image
                        };
                    }
                }
            }
        }
Exemple #17
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string path = value as string;

            if (string.IsNullOrWhiteSpace(path))
            {
                return(null);
            }

            return(ImageCache.GetImage(path));
        }
Exemple #18
0
        private bool _AddLocationAttachment()
        {
            if (!string.IsNullOrEmpty(App.Current.EntityService.AttachedLatitude) &&
                !string.IsNullOrEmpty(App.Current.EntityService.AttachedLongitude))
            {
                try
                {
                    string uri = String.Format(AppResources.GeolocationMapUriFormatMessage,
                                               App.Current.EntityService.AttachedLatitude.Replace(",", "."),
                                               App.Current.EntityService.AttachedLongitude.Replace(",", "."));

                    var avm = new AttachmentViewModel(-1, -1, -1, AttachmentType.Location, uri, null, null, null, null);
                    _model.Add(avm);

                    string filename     = CommonHelper.DoDigest(uri);
                    var    photosToLoad = new List <AvatarLoadItem>();
                    photosToLoad.Add(new AvatarLoadItem(1, uri, filename));

                    var service = new AsyncAvatarsLoader();

                    if (photosToLoad.Any())
                    {
                        service.LoadAvatars(photosToLoad.ToList(), id =>
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                try
                                {
                                    ImageCache cache  = new ImageCache();
                                    BitmapImage image = cache.GetItem(filename);

                                    if (image != null && image.PixelHeight > 0 && image.PixelWidth > 0)
                                    {
                                        avm.AttachPhoto = image;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine("_AddLocationAttachment failed in AttachmentsPage: " + ex.Message);
                                }
                            });
                        }, null);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Load attached location photo failed " + ex.Message);
                }

                return(true);
            }

            return(false);
        }
Exemple #19
0
 public NewFile(Main main)
     : base(main)
 {
     this.main        = main;
     base.ID          = ActionID;
     this.MenuText    = "&New";
     this.ToolBarText = "New";
     this.ToolTip     = "Create a new file";
     this.Image       = ImageCache.IconFromResource("Pablo.Interface.Icons.new.ico");
     this.Shortcut    = PabloCommand.CommonModifier | Keys.N;
 }
Exemple #20
0
 public OpenFile(Main main)
 {
     this.main        = main;
     base.ID          = ActionID;
     this.MenuText    = "&Open";
     this.ToolBarText = "Open";
     this.ToolTip     = "Open a file";
     this.Image       = ImageCache.IconFromResource("Pablo.Interface.Icons.open.ico");
     this.Shortcut    = PabloCommand.CommonModifier | Keys.O;
     this.Enabled     = main.Client == null || main.Client.CurrentUser.Level >= Pablo.Network.UserLevel.Operator;
 }
Exemple #21
0
 private async void GetPic()
 {
     if (!string.IsNullOrEmpty(userSmallAvatarUrl))
     {
         userSmallAvatar = await ImageCache.GetImage(ImageType.SmallAvatar, userSmallAvatarUrl);
     }
     if (!string.IsNullOrEmpty(extraPicUrl))
     {
         extra_pic = await ImageCache.GetImage(ImageType.Icon, extraPicUrl);
     }
 }
Exemple #22
0
        public SearchActivity()
        {
            InitializeComponent();

            setUpApplicationBar();

            txtKeyWord.Focus();
            disableProgressBar();
            imgCache = new ImageCache();
            this.lstVideoSearching.Loaded += new RoutedEventHandler(lstVideoSearching_Loaded);
        }
Exemple #23
0
        public ItemsGroupBox()
        {
            CommandBindings.Add(new CommandBinding(SelectPrevious, ExecutedSelectedPrevious, CanExecuteSelectPrevious));
            CommandBindings.Add(new CommandBinding(SelectNext, ExecutedSelectedNext, CanExecuteSelectNext));
            CommandBindings.Add(new CommandBinding(Unlock, ExecutedUnlock, CanExecuteUnlock));
            CommandBindings.Add(new CommandBinding(AddNew, ExecutedAddNew, CanExecuteAddNew));

            LockIcon = ImageCache.GetImage("pack://application:,,,/BioLink.Client.Extensibility;component/images/Locked.png");

            _collectionChangedHandler = (s, e) => UpdateCurrentPosition();
        }
Exemple #24
0
    public ThumbnailService(StatusService statusService,
                            ImageProcessService imageService,
                            ImageCache imageCache, WorkService workService)
    {
        _statusService          = statusService;
        _imageProcessingService = imageService;
        _imageCache             = imageCache;
        _workService            = workService;

        _workService.AddJobSource(this);
    }
Exemple #25
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            imageCache       = new ImageCache(IL16);
            tsmiNew.Image    = imageCache["new"];
            tsmiOpen.Image   = imageCache["open"];
            tsmiSave.Image   = imageCache["save"];
            tsmiSaveAs.Image = imageCache["saveAs"];
            tsmiExit.Image   = imageCache["exit"];
            tsbNew.Image     = imageCache["new"];
            tsbOpen.Image    = imageCache["open"];
            tsbSave.Image    = imageCache["save"];
            tsbSaveAs.Image  = imageCache["saveAs"];
            tsbUndo.Image    = imageCache["undo"];
            tsbRedo.Image    = imageCache["redo"];
            tsbLogic.Image   = imageCache["logic"];

            Bootstrap();

            //SetTheme(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);

            AddonManager.Instance.PostInit();

            serializeContext = new DeserializeDockContent(GetContentFromPersistString);
            if (!LoadLayoutConfig())
            {
                ShowMapEntitiesForm();
                ShowEntityTypesForm();
                ShowPropertiesForm();
                ShowContentForm();
                ShowConsoleForm();
            }

            InitializeEntityTypesForm();
            InitializeContentForm();
            InitializeEntitiesForm();
            InitializePropertiesForm();

            #region Splash Screen

            LongOperationNotifier.LongOperationNotify -= LongOperationCallbackManager_LongOperationNotify;
            this.Show();
            SplashScreen.Hide();
            this.Activate();
            #endregion

            this.WindowState = FormWindowState.Maximized;

            #region File System Watcher
            this.fileSystemWatcher = new FileSystemWatcher();
            #endregion

            UpdateWindowTitle();
            Debug("准备就绪...");
        }
Exemple #26
0
        public TracksViewModel(Attendee attendee, ImageCache imageCache, SearchModel searchModel)
        {
            _attendee    = attendee;
            _imageCache  = imageCache;
            _searchModel = searchModel;

            _tracks = new DependentList <Track>(() =>
                                                from track in _attendee.Conference.Tracks
                                                orderby track.Name
                                                select track);
        }
Exemple #27
0
 public void SetIconURL(string url)
 {
     if (url.StartsWith("//"))
     {
         url = "http:" + url;
     }
     this.m_IconKeyimage      = new Image();
     this.m_IconKeyimage.mUrl = url;
     this.m_IconKeyimage.Name = "icon";
     ImageCache.DownloadImage(this.m_IconKeyimage, null);
 }
Exemple #28
0
        public static void Init(int appId)
        {
            var services = new ServiceCollection();

            services.AddAudioBypass();
            VkApi = new Va(services);

            ImageCache.Init();

            ApplicationId = (ulong)appId;
        }
 private UIButton CreateHideKeyboardButton()
 {
     return(new UIButton(UIButtonType.Custom)
            .WithFrame(0, 162.5f.If_iPhone6Plus(169.3f), 104.5f.If_iPhone6(122.5f).If_iPhone6Plus(135), 60)
            .WithBackground(UIColor.Clear)
            .WithButtonImage(ImageCache.GetImage("Images/Main/hide_key.png", UIColor.Black), UIControlState.Normal)
            .WithButtonImage(ImageCache.GetImage("Images/Main/hide_key_state.png", UIColor.Black), UIControlState.Highlighted)
            .WithTune(tune =>
     {
         tune.SetBackgroundImage(UIColor.White.ToUIImage(), UIControlState.Highlighted);
     }));
 }
        public List_Drama_Activity()
        {
            InitializeComponent();
            imgCache     = new ImageCache();
            tvodUltility = new Ultility();
            setUpApplicationBar();
            enableProgressBar();

            btnNewest.Background  = new SolidColorBrush(Colors.White);
            btnNewest.Foreground  = new SolidColorBrush(Colors.Black);
            this.lstDrama.Loaded += new RoutedEventHandler(lstDrama_Loaded);
        }
Exemple #31
0
        public SpeakerDayViewModel(Attendee attendee, Speaker speaker, Day day, ImageCache imageCache)
        {
            _attendee   = attendee;
            _speaker    = speaker;
            _day        = day;
            _imageCache = imageCache;

            _matchingSessionPlaces = new DependentList <SessionPlace>(() =>
                                                                      from sessionPlace in _speaker.AvailableSessions
                                                                      where sessionPlace.Place.PlaceTime.Day == _day
                                                                      select sessionPlace);
        }
Exemple #32
0
 private void SaveToImageCache(string document, IServerProcess process, IScalar LResult)
 {
     lock (ImageCache)
     {
         byte[] value = null;
         if ((LResult != null) && (!LResult.IsNil))
         {
             value = LResult.AsByteArray;
         }
         ImageCache.Add(document, value);
     }
 }
        static void AssertSameImage(BitmapSource expected, BitmapSource actual)
        {
            var expectedBytes = ImageCache.GetBytesFromBitmapImage(expected);
            var actualBytes   = ImageCache.GetBytesFromBitmapImage(actual);

            // Since we scale the image, we can't compare all the bytes, so we'll compare a few of them.
            // TODO: This is probably not correct, but we've manually verified the code we're testing.
            // We need a way to test similarity of images.
            const int bytesToCompare = 19;

            Assert.Equal(expectedBytes.Take(bytesToCompare), actualBytes.Take(bytesToCompare));
        }
Exemple #34
0
        public ViewModelLocator()
        {
            _synchronizationService = new SynchronizationService();
            if (!DesignerProperties.IsInDesignTool)
            {
                _synchronizationService.Initialize();
            }

            _conferenceSelection = new ConferenceSelection();
            _imageCache          = new ImageCache();
            _searchModel         = new SearchModel();
        }
        public void ImageCache_LoadsAnImage()
        {
            var mock = new Mock <IImageLoader>();

            mock
            .Setup(l => l.LoadImage(It.IsAny <string>()))
            .Returns(new ImageMeta());
            ImageCache cache = new ImageCache(mock.Object, 1);

            cache.GetOrLoadImage("test.png");
            mock.Verify(m => m.LoadImage(It.IsAny <string>()), Times.Exactly(1));
        }
 protected RootFolderHandlerBase(
     TheImport import,
     EnhancedDriveInfo infoOfDrive,
     string rootFolder,
     List<EnhancedFileInfo> foundFiles,
     ImageCache cachedImages)
 {
     _import = import;
     _infoOfDrive = infoOfDrive;
     _files = foundFiles;
     RootFolder = rootFolder;
     _images = cachedImages;
 }
        public async Task DownloadsImageWhenMissingAndCachesIt()
        {
            var singlePixel = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");

            var imageUri = new Uri("https://example.com/poop.gif");
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(new InMemoryBlobCache());
            var imageDownloader = Substitute.For<IImageDownloader>();
            imageDownloader.DownloadImageBytes(imageUri).Returns(Observable.Return(singlePixel));
            var imageCache = new ImageCache(cacheFactory, Substitute.For<Rothko.Environment>(), new Lazy<IImageDownloader>(() => imageDownloader));

            var retrieved = await imageCache.GetImage(imageUri).FirstAsync();

            Assert.NotNull(retrieved);
            Assert.Equal(32, retrieved.PixelWidth);
            Assert.Equal(32, retrieved.PixelHeight);
        }
        public async Task RetrievesImageFromCacheAndDoesNotFetchIt()
        {
            var singlePixel = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
            var cache = new InMemoryBlobCache();
            await cache.Insert("https://fake/", singlePixel);
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageDownloader = Substitute.For<IImageDownloader>();
            imageDownloader.DownloadImageBytes(Args.Uri).Returns(_ => { throw new InvalidOperationException(); });
            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => imageDownloader));

            var retrieved = await imageCache.GetImage(new Uri("https://fake/")).FirstAsync();

            Assert.NotNull(retrieved);
            Assert.Equal(32, retrieved.PixelWidth);
            Assert.Equal(32, retrieved.PixelHeight);
        }
        public async Task WhenLoadingFromCacheFailsInvalidatesCacheEntry()
        {
            var cache = new InMemoryBlobCache();
            await cache.Insert("https://fake/", new byte[] { 0, 0, 0 });
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageDownloader = Substitute.For<IImageDownloader>();
            imageDownloader.DownloadImageBytes(Args.Uri).Returns(_ => { throw new InvalidOperationException(); });
            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => imageDownloader));

            var retrieved = await imageCache
                .GetImage(new Uri("https://fake/"))
                .Catch(Observable.Return<BitmapSource>(null))
                .FirstAsync();

            Assert.Null(retrieved);
            await Assert.ThrowsAsync<KeyNotFoundException>(async () => await cache.Get("https://fake/"));
        }
 internal static RootFolderHandlerBase ProvideRootFolderHandlerInstance(
     TheImport import,
     EnhancedDriveInfo infoOfDrive,
     string rootFolder,
     List<EnhancedFileInfo> foundFiles,
     ImageCache cachedImages)
 {
     if (import.Importer.ChainingOption == ChainOption.ChainByTags)
     {
         return new ChainByTagsRootFolderHandler(import, infoOfDrive, rootFolder, foundFiles, cachedImages);
     }
     else if (import.Importer.ChainingOption == ChainOption.ChainByFolder)
     {
         return new ChainByFolderRootFolderHandler(import, infoOfDrive, rootFolder, foundFiles, cachedImages);
     }
     else
     {
         return new DefaultRootFolderHandler(import, infoOfDrive, rootFolder, foundFiles, cachedImages);
     }
 }
        public async Task RemovesImageFromCache()
        {
            var singlePixel = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
            var cache = new InMemoryBlobCache();
            await cache.Insert("https://fake/", singlePixel);
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => Substitute.For<IImageDownloader>()));

            await imageCache.Invalidate(new Uri("https://fake/"));

            await Assert.ThrowsAsync<KeyNotFoundException>(async () => await cache.Get("https://fake/"));
        }
        public void OnlyDownloadsAndDecodesOnceForConcurrentOperations()
        {
            var singlePixel = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
            var subj = new Subject<byte[]>();

            var cache = new InMemoryBlobCache(Scheduler.Immediate);
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageDownloader = Substitute.For<IImageDownloader>();
            imageDownloader.DownloadImageBytes(Args.Uri).Returns(subj, Observable.Throw<byte[]>(new InvalidOperationException()));
            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => imageDownloader));
            var uri = new Uri("https://github.com/foo.png");

            BitmapSource res1 = null;
            BitmapSource res2 = null;

            var sub1 = imageCache.GetImage(uri).Subscribe(x => res1 = x);
            var sub2 = imageCache.GetImage(uri).Subscribe(x => res2 = x);

            Assert.Null(res1);
            Assert.Null(res2);

            subj.OnNext(singlePixel);
            subj.OnCompleted();

            Assert.NotNull(res1);
            Assert.Equal(res1, res2);
        }
Exemple #43
0
 private void CacheInit()
 {
     imageCache = new ImageCache();
       textureCache = new TextureCache(imageCache, 0);
 }
Exemple #44
0
        /// <summary>
        /// Loads the image thumbnail to image cache in a background thread.
        /// When the loading is complete, invalidate the item rectangle to make it redraw.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="bounds">The bounds.</param>
        private void LoadImageToCache(int index, Entry entry, ImageCache cache, Rectangle bounds)
        {
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += delegate(object sender, DoWorkEventArgs args)
            {
                Image thumbnailImage = new Bitmap(bounds.Width, bounds.Height);

                using (Image image = Image.FromFile(entry.PhotoPath))
                {
                    this.DrawToFit(Graphics.FromImage(thumbnailImage), image, new Rectangle(0, 0, bounds.Width, bounds.Height));
                }

                cache.AddCachedImage(entry, thumbnailImage);
            };

            worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs args)
            {
                // Start the timer to do the fade in animation.
                Timer timer = new Timer();
                timer.Interval = 1;

                long initialTimestamp = DateTime.Now.Ticks;

                timer.Tick += delegate(object s, EventArgs e)
                {
                    long diff = (DateTime.Now.Ticks - initialTimestamp) / 10000;
                    int alpha = (int)(255 - (255 * diff / PhotoFadeInTime));

                    if (alpha <= 0)
                    {
                        if (this.PhotoAlphaValues.ContainsKey(entry))
                        {
                            this.PhotoAlphaValues.Remove(entry);
                        }

                        timer.Stop();
                    }
                    else
                    {
                        if (this.PhotoAlphaValues.ContainsKey(entry))
                        {
                            this.PhotoAlphaValues[entry] = alpha;
                        }
                        else
                        {
                            this.PhotoAlphaValues.Add(entry, alpha);
                        }
                    }

                    this.Invalidate(this.GetItemRectangle(index));
                };

                timer.Start();
            };

            worker.RunWorkerAsync();
        }
        public async Task AddsImageDirectlyToCache()
        {
            var singlePixel = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
            var cache = new InMemoryBlobCache();
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => Substitute.For<IImageDownloader>()));

            await imageCache.SeedImage(new Uri("https://fake/"), singlePixel, DateTimeOffset.MaxValue);

            var retrieved = await cache.Get("https://fake/");
            Assert.Equal(singlePixel, retrieved);
        }
        /// <exception cref="Exception"><c>Exception</c>.</exception>
        internal static void ScanDrive(TheImport theImport,
             KeyValuePair<EnhancedDriveInfo, 
                 List<string>> driveRootFolders, 
             ref FilesQueue filesQueue)
        {
            var allFoundFiles = new List<EnhancedFileInfo>();

            var foundFiles = new List<EnhancedFileInfo>();

            try
            {

                ImageCache cachedImages = new ImageCache();

                foreach (string rootFolder in driveRootFolders.Value)
                {

                    if (Directory.Exists(rootFolder))
                    {

                        foundFiles.Clear();

                        foundFiles.AddRange(FindFiles(theImport, rootFolder));

                        RootFolderHandlerBase rootFolderHandler =
                            RootFolderHandlerProvider.ProvideRootFolderHandlerInstance(
                                theImport, driveRootFolders.Key, rootFolder, foundFiles, cachedImages);

                        RootFolderHandlerExecuter.Execute(rootFolderHandler);

                        allFoundFiles.AddRange(foundFiles);

                    }
                    else
                    {
                        theImport.Importer.LogMessages.Enqueue(
                            new LogMessage("Warn", "RootFolder doesn't exist: " + rootFolder));
                    }

                }

                EnhancedFileInfo[] foundFilesArray
                    = allFoundFiles.ToArray();

                filesQueue
                    .Enqueue
                    (foundFilesArray);

            }
            catch (Exception ex)
            {
                theImport.Importer.LogMessages.Enqueue(new LogMessage("Error", ex.ToString()));
                throw;
            }
            finally
            {
                allFoundFiles.Clear();
                foundFiles.Clear();
            }

            theImport.Importer.LogMessages.Enqueue
                (new LogMessage("Debug",
                                "Return from ScanDrive"));
        }
        public async Task ThrowsKeyNotFoundExceptionWhenItemNotInCacheAndImageFetchReturnsEmpty()
        {
            var imageUri = new Uri("https://example.com/poop.gif");
            var cache = new InMemoryBlobCache();
            var cacheFactory = Substitute.For<IBlobCacheFactory>();
            cacheFactory.CreateBlobCache(Args.String).Returns(cache);
            var imageDownloader = Substitute.For<IImageDownloader>();
            imageDownloader.DownloadImageBytes(imageUri).Returns(Observable.Empty<byte[]>());

            var imageCache = new ImageCache(cacheFactory, Substitute.For<IEnvironment>(), new Lazy<IImageDownloader>(() => imageDownloader));

            await Assert.ThrowsAsync<KeyNotFoundException>(async () => await
                imageCache.GetImage(imageUri).FirstAsync());
        }