protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, bool clearCacheOnOutOfMemory, bool verboseLoadingCancelledLogging) { _verboseLoadingCancelledLogging = verboseLoadingCancelledLogging; _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory; CancellationToken = new CancellationTokenSource(); Parameters = parameters; NumberOfRetryNeeded = parameters.RetryCount; MainThreadDispatcher = mainThreadDispatcher; Logger = miniLogger; ConfigureParameters(); _hasCustomCacheKey = !string.IsNullOrWhiteSpace(Parameters.CustomCacheKey); _keys = new ConcurrentDictionary<string, string>(); _transformationsKey = new Lazy<string>(() => { if (Parameters.Transformations == null || Parameters.Transformations.Count == 0) return string.Empty; return ";" + string.Join(";", Parameters.Transformations.Select(t => t.Key)); }); _downsamplingKey = new Lazy<string>(() => { if (Parameters.DownSampleSize == null) return string.Empty; return string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2); }); _rawKey = new Lazy<string>(() => GetKeyInternal(null, true)); _streamKey = new Lazy<string>(() => "Stream" + GetNextStreamIndex()); }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func<Image> getNativeControl, Action<WriteableBitmap, bool> doWithImage) : base(mainThreadDispatcher, miniLogger, parameters) { _getNativeControl = getNativeControl; _doWithImage = doWithImage; DownloadCache = downloadCache; }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func<UIView> getNativeControl, Action<UIImage, bool> doWithImage, nfloat imageScale) : base(mainThreadDispatcher, miniLogger, parameters) { _getNativeControl = getNativeControl; _doWithImage = doWithImage; _imageScale = imageScale; DownloadCache = downloadCache; }
protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters) { CancellationToken = new CancellationTokenSource(); Parameters = parameters; NumberOfRetryNeeded = parameters.RetryCount; MainThreadDispatcher = mainThreadDispatcher; Logger = miniLogger; ConfigureParameters(); }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, nfloat imageScale, ITarget<UIImage, ImageLoaderTask> target, bool clearCacheOnOutOfMemory) : base(mainThreadDispatcher, miniLogger, parameters, true, clearCacheOnOutOfMemory) { if (target == null) throw new ArgumentNullException(nameof(target)); _target = target; DownloadCache = downloadCache; }
/// <summary> /// Initializes a new instance of the <see cref="T:FFImageLoading.Cache.ReuseBitmapDrawableCache`1"/> class. /// </summary> /// <param name="logger">Logger.</param> /// <param name="memoryCacheSize">Memory cache size.</param> /// <param name="bitmapPoolSize">Bitmap pool size.</param> /// <param name="verboseLogging">If set to <c>true</c> verbose logging.</param> public ReuseBitmapDrawableCache(IMiniLogger logger, int memoryCacheSize, int bitmapPoolSize, bool verboseLogging = false) { _gcThreshold = bitmapPoolSize; _verboseLogging = verboseLogging; _log = logger; _bitmapPoolSize = bitmapPoolSize; _displayed_cache = new ByteBoundStrongLruCache <TValue>(memoryCacheSize); _reuse_pool = new ByteBoundStrongLruCache <TValue>(bitmapPoolSize); _reuse_pool.EntryRemoved += OnEntryRemovedFromReusePool; }
/// <summary> /// Initializes a new instance of the <see cref="T:FFImageLoading.Cache.ReuseBitmapDrawableCache`1"/> class. /// </summary> /// <param name="logger">Logger.</param> /// <param name="memoryCacheSize">Memory cache size.</param> /// <param name="bitmapPoolSize">Bitmap pool size.</param> /// <param name="verboseLogging">If set to <c>true</c> verbose logging.</param> public ReuseBitmapDrawableCache(IMiniLogger logger, int memoryCacheSize, int bitmapPoolSize, bool verboseLogging = false) { _verboseLogging = verboseLogging; log = logger; low_watermark = bitmapPoolSize / 2; high_watermark = bitmapPoolSize; displayed_cache = new ByteBoundStrongLruCache <TValue>(memoryCacheSize); reuse_pool = new ByteBoundStrongLruCache <TValue>(bitmapPoolSize); reuse_pool.EntryRemoved += OnEntryRemovedFromReusePool; }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView) : base(mainThreadDispatcher, miniLogger, parameters, true) { DownloadCache = downloadCache; if (imageView != null) { _imageWeakReference = new WeakReference<ImageView>(imageView); } }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView) : base(mainThreadDispatcher, miniLogger, parameters) { CancellationToken = new CancellationTokenSource(); Context = Android.App.Application.Context.ApplicationContext; DownloadCache = downloadCache; _imageWeakReference = new WeakReference<ImageView>(imageView); UseFadeInBitmap = true; }
private ImageCache(int maxCacheSize, IMiniLogger logger, bool verboseLogging) { _logger = logger; int safeMaxCacheSize = GetMaxCacheSize(maxCacheSize); // consider low treshold as a third of maxCacheSize int lowTreshold = safeMaxCacheSize / 3; _cache = new ReuseBitmapDrawableCache(logger, safeMaxCacheSize, lowTreshold, safeMaxCacheSize, verboseLogging); _imageInformations = new ConcurrentDictionary<string, ImageInformation>(); }
EvasImageCache(int maxCacheSize, IMiniLogger logger) { _maxCacheSize = maxCacheSize; _logger = logger; _currentCacheSize = 0; if (_maxCacheSize <= 0) { _maxCacheSize = 1920 * 1080 * 10 * 4; // 10 FHD Images } }
public ImageController(IImageProviderService imageProviderService, AppConfiguration configuration, IDateTimeProvider dateTimeProvider, IMiniLogger logger) : base(configuration, dateTimeProvider, logger) { _imageProviderService = imageProviderService; _snapshotImagePath = AppConfiguration.SnapShotImagePath; RegisterConnectedUser(); }
private ImageCache(int maxCacheSize, IMiniLogger logger, bool verboseLogging) { _logger = logger; int safeMaxCacheSize = GetMaxCacheSize(maxCacheSize); // consider low treshold as a third of maxCacheSize int lowTreshold = safeMaxCacheSize / 3; _cache = new ReuseBitmapDrawableCache(logger, safeMaxCacheSize, lowTreshold, safeMaxCacheSize, verboseLogging); _imageInformations = new ConcurrentDictionary <string, ImageInformation>(); }
/// <summary> /// Initialize ImageService default values. This can only be done once: during app start. /// </summary> /// <param name="maxCacheSize">Max cache size. If zero then 20% of the memory will be used.</param> /// <param name="httpClient">.NET HttpClient to use. If null then a ModernHttpClient is instanciated.</param> /// <param name="scheduler">Work scheduler used to organize/schedule loading tasks.</param> /// <param name="logger">Basic logger. If null a very simple implementation that prints to console is used.</param> /// <param name="diskCache">Disk cache. If null a default disk cache is instanciated that uses a journal mechanism.</param> /// <param name="downloadCache">Download cache. If null a default download cache is instanciated, which relies on the DiskCache</param> public static void Initialize(int maxCacheSize = 0, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null, IDiskCache diskCache = null, IDownloadCache downloadCache = null) { lock (_initializeLock) { if (_initialized) throw new Exception("FFImageLoading.ImageService is already initialized"); } InitializeIfNeeded(maxCacheSize, httpClient, scheduler, logger, diskCache, downloadCache); }
private ImageCache(int maxCacheSize, IMiniLogger logger) { _logger = logger; if (maxCacheSize == 0) { maxCacheSize = 1000000 * 256; //256MB _logger?.Debug($"Memory cache size: {maxCacheSize} bytes"); } _reusableBitmaps = new WriteableBitmapLRUCache(maxCacheSize); }
public WorkScheduler(IMiniLogger logger, bool verbosePerformanceLogging, IPlatformPerformance performance) { _verbosePerformanceLogging = verbosePerformanceLogging; _logger = logger; _performance = performance; int _processorCount = Environment.ProcessorCount; if (_processorCount <= 2) _maxParallelTasks = 1; else _maxParallelTasks = (int)Math.Truncate((double)_processorCount / 2d) + 1; }
public WorkScheduler(IMiniLogger logger) { _logger = logger; _pauseWorkLock = new object(); _pendingTasks = new List<PendingTask>(); int _processorCount = Environment.ProcessorCount; if (_processorCount == 1) _defaultParallelTasks = 1; else _defaultParallelTasks = (int)System.Math.Truncate((double)_processorCount / 2); }
private ImageCache(int maxCacheSize, IMiniLogger logger) { _cache = new NSCache(); _imageInformations = new ConcurrentDictionary <string, ImageInformation>(); _cache.TotalCostLimit = (nuint)(NSProcessInfo.ProcessInfo.PhysicalMemory * 0.2); // 20% of physical memory decimal sizeInMB = System.Math.Round((decimal)_cache.TotalCostLimit / (1024 * 1024), 2); logger.Debug(string.Format("LruCache size: {0}MB", sizeInMB)); // if we get a memory warning notification we should clear the cache NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIApplicationDidReceiveMemoryWarningNotification"), notif => Clear()); }
private ImageCache(int maxCacheSize, IMiniLogger logger) { _logger = logger; _cache = new NSCache(); _imageInformations = new ConcurrentDictionary<string, ImageInformation>(); _cache.TotalCostLimit = (nuint)(NSProcessInfo.ProcessInfo.PhysicalMemory * 0.2); // 20% of physical memory decimal sizeInMB = System.Math.Round((decimal)_cache.TotalCostLimit/(1024*1024), 2); logger.Debug(string.Format("LruCache size: {0}MB", sizeInMB)); // if we get a memory warning notification we should clear the cache NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIApplicationDidReceiveMemoryWarningNotification"), notif => Clear()); }
public static void SaveImageSnapshot(byte[] imageAsBytes, IDateTimeProvider dateTimeProvider, string snapshotImagePath, IMiniLogger logger, int userId, string userIp) { if (!IsTimeToWriteAPicture(dateTimeProvider)) { return; } Image image = ImageHelper.ConvertByteArrayToImage(imageAsBytes); WriteImageToFile(image, dateTimeProvider.DateTimeNow, snapshotImagePath, logger, userId, userIp); }
private ImageCache(int maxCacheSize, IMiniLogger logger, bool verboseLogging) { _logger = logger; int safeMaxCacheSize = GetMaxCacheSize(maxCacheSize); double sizeInMB = Math.Round(safeMaxCacheSize / 1024d / 1024d, 2); logger.Debug(string.Format("Image memory cache size: {0} MB", sizeInMB)); // consider low treshold as a third of maxCacheSize int lowTreshold = safeMaxCacheSize / 3; _cache = new ReuseBitmapDrawableCache(logger, safeMaxCacheSize, lowTreshold, safeMaxCacheSize, verboseLogging); _imageInformations = new ConcurrentDictionary<string, ImageInformation>(); }
private ImageCache(int maxCacheSize, IMiniLogger logger, bool verboseLogging) { _logger = logger; int safeMaxCacheSize = GetMaxCacheSize(maxCacheSize); double sizeInMB = Math.Round(safeMaxCacheSize / 1024d / 1024d, 2); logger.Debug(string.Format("Image memory cache size: {0} MB", sizeInMB)); // consider low treshold as a third of maxCacheSize int lowTreshold = safeMaxCacheSize / 3; _cache = new ReuseBitmapDrawableCache(logger, safeMaxCacheSize, lowTreshold, safeMaxCacheSize, verboseLogging); _imageInformations = new ConcurrentDictionary <string, ImageInformation>(); }
public Configuration(int maxCacheSize, HttpClient httpClient, IWorkScheduler scheduler, IMiniLogger logger, IDiskCache diskCache, IDownloadCache downloadCache, bool loadWithTransparencyChannel, bool fadeAnimationEnabled, int httpHeadersTimeout, int httpReadTimeout ) { MaxCacheSize = maxCacheSize; HttpClient = httpClient; Scheduler = scheduler; Logger = logger; DiskCache = diskCache; DownloadCache = downloadCache; LoadWithTransparencyChannel = loadWithTransparencyChannel; FadeAnimationEnabled = fadeAnimationEnabled; HttpHeadersTimeout = httpHeadersTimeout; HttpReadTimeout = httpReadTimeout; }
private static void TrySaveImageAgain(Image image, IMiniLogger logger, string imagePath, int userId, string userIp) { try { if (File.Exists(imagePath)) { File.Delete(imagePath); } System.Threading.Thread.Sleep(1000); SaveImage(image, imagePath); } catch (Exception e) { logger?.LogError($"{nameof(WriteImageToFile)}->{nameof(TrySaveImageAgain)}(): " + $"{e.Message} filepath: {imagePath}", userId, userIp); } }
public WorkScheduler(IMiniLogger logger) { _logger = logger; _pauseWorkLock = new object(); _pendingTasks = new List <PendingTask>(); int _processorCount = Environment.ProcessorCount; if (_processorCount == 1) { _defaultParallelTasks = 1; } else { _defaultParallelTasks = (int)System.Math.Truncate((double)_processorCount / 2); } }
/// <summary> /// Initializes a new instance of the <see cref="AndroidBitmapDrawableCache"/> class. /// </summary> /// <param name="logger">Logger for debug messages</param> /// <param name="highWatermark">Maximum number of bytes the reuse pool will hold before starting evictions. /// <param name="lowWatermark">Number of bytes the reuse pool will be drained down to after the high watermark is exceeded.</param> /// On Honeycomb and higher this value is used for the reuse pool size.</param> /// <param name="gcThreshold">Threshold in bytes that triggers a System.GC.Collect (Honeycomb+ only).</param> /// <param name="debugDump">If set to <c>true</c> dump stats to log every 10 seconds.</param> public ReuseBitmapDrawableCache(IMiniLogger logger, long highWatermark, long lowWatermark, long gcThreshold = 2 * 1024 * 1024, bool verboseLogging = false) { _verboseLogging = verboseLogging; log = logger; low_watermark = lowWatermark; high_watermark = highWatermark; gc_threshold = gcThreshold; displayed_cache = new Dictionary <string, ISelfDisposingBitmapDrawable>(); reuse_pool = new ByteBoundStrongLruCache <string, ISelfDisposingBitmapDrawable>(highWatermark, lowWatermark); reuse_pool.EntryRemoved += OnEntryRemovedFromReusePool; // if (_verboseLogging) { // main_thread_handler = new Handler(); // DebugDumpStats(); //} }
public WorkScheduler(IMiniLogger logger, bool verbosePerformanceLogging, IPlatformPerformance performance) { _verbosePerformanceLogging = verbosePerformanceLogging; _logger = logger; _performance = performance; int _processorCount = Environment.ProcessorCount; if (_processorCount <= 2) { _maxParallelTasks = 1; } else { _maxParallelTasks = (int)Math.Truncate((double)_processorCount / 2d) + 1; } }
public Configuration(int maxCacheSize, HttpClient httpClient, IWorkScheduler scheduler, IMiniLogger logger, IDiskCache diskCache, IDownloadCache downloadCache, bool loadWithTransparencyChannel, bool fadeAnimationEnabled, bool transformPlaceholders, InterpolationMode downsampleInterpolationMode, int httpHeadersTimeout, int httpReadTimeout ) { MaxCacheSize = maxCacheSize; HttpClient = httpClient; Scheduler = scheduler; Logger = logger; DiskCache = diskCache; DownloadCache = downloadCache; LoadWithTransparencyChannel = loadWithTransparencyChannel; FadeAnimationEnabled = fadeAnimationEnabled; TransformPlaceholders = transformPlaceholders; DownsampleInterpolationMode = downsampleInterpolationMode; HttpHeadersTimeout = httpHeadersTimeout; HttpReadTimeout = httpReadTimeout; }
public BaseApiController(AppConfiguration appConfiguration, IDateTimeProvider dateTimeProvider, IMiniLogger logger) { AppConfiguration = appConfiguration; DateTimeProviderInstance = dateTimeProvider; Logger = logger; UserIp = HttpContextHelper.GetIpFromHttpContext(HttpContext.Current); UserId = HttpContextHelper.GetUniqueUserIdFromBrowser(HttpContext.Current, UserIp); if (!AppConfiguration.IsValid) { LogInvalidConfiguration(); AppConfiguration.Reset(); } }
private static void InitializeIfNeeded(int maxCacheSize = 0, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null, IDiskCache diskCache = null, IDownloadCache downloadCache = null, bool loadWithTransparencyChannel = false, bool fadeAnimationEnabled = true, int httpHeadersTimeout = HttpHeadersTimeout, int httpReadTimeout = HttpReadTimeout ) { if (_initialized) return; lock (_initializeLock) { if (_initialized) return; var userDefinedConfig = new Configuration(maxCacheSize, httpClient, scheduler, logger, diskCache, downloadCache, loadWithTransparencyChannel, fadeAnimationEnabled, httpHeadersTimeout, httpReadTimeout); Config = GetDefaultConfiguration(userDefinedConfig); _initialized = true; } }
private int _currentPosition; // useful? public WorkScheduler(IMiniLogger logger) { _logger = logger; _pendingTasks = new ConcurrentDictionary <string, PendingTask>(); _pendingTasksByRawKey = new ConcurrentDictionary <string, PendingTask>(); _currentlyRunning = new ConcurrentDictionary <PendingTask, byte>(); _dispatch = Task.FromResult <byte>(1); int _processorCount = Environment.ProcessorCount; if (_processorCount <= 2) { _defaultParallelTasks = 1; } else { _defaultParallelTasks = (int)Math.Truncate((double)_processorCount / 2d) + 1; } }
public static void WriteImageToFile(Image image, DateTime dateTime, string imageDirectory, IMiniLogger logger, int userId, string userIp, bool roundSecondsToZero = true) { if (image == null) { return; } if (string.IsNullOrWhiteSpace(imageDirectory)) { return; } dateTime = RoundSecondsToZero(dateTime, roundSecondsToZero); string dateTimeCompact = DateTimeFormatter.ConvertTimeToCompactString(dateTime: dateTime, withMilliSeconds: false); WriteImageToFile(image, imageDirectory, dateTimeCompact, logger, userId, userIp); }
/// <summary> /// Initialize ImageService default values. This can only be done once: during app start. /// </summary> /// <param name="maxCacheSize">Max cache size. If zero then 20% of the memory will be used.</param> /// <param name="httpClient">.NET HttpClient to use. If null then a.NET HttpClient is instanciated.</param> /// <param name="scheduler">Work scheduler used to organize/schedule loading tasks.</param> /// <param name="logger">Basic logger. If null a very simple implementation that prints to console is used.</param> /// <param name="diskCache">Disk cache. If null a default disk cache is instanciated that uses a journal mechanism.</param> /// <param name="downloadCache">Download cache. If null a default download cache is instanciated, which relies on the DiskCache</param> /// <param name="loadWithTransparencyChannel">Gets a value indicating whether images should be loaded with transparency channel. On Android we save 50% of the memory without transparency since we use 2 bytes per pixel instead of 4.</param> /// <param name="fadeAnimationEnabled">Defines if fading should be performed while loading images.</param> /// <param name="transformPlaceholders">Defines if transforms should be applied to placeholders.</param> /// <param name="downsampleInterpolationMode">Defines default downsample interpolation mode.</param> /// <param name="httpHeadersTimeout">Maximum time in seconds to wait to receive HTTP headers before the HTTP request is cancelled.</param> /// <param name="httpReadTimeout">Maximum time in seconds to wait before the HTTP request is cancelled.</param> public static void Initialize(int? maxCacheSize = null, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null, IDiskCache diskCache = null, IDownloadCache downloadCache = null, bool? loadWithTransparencyChannel = null, bool? fadeAnimationEnabled = null, bool? transformPlaceholders = null, InterpolationMode? downsampleInterpolationMode = null, int httpHeadersTimeout = HttpHeadersTimeout, int httpReadTimeout = HttpReadTimeout ) { lock (_initializeLock) { _initialized = false; if (Config != null) { // If DownloadCache is not updated but HttpClient is then we inform DownloadCache if (httpClient != null && downloadCache == null) { downloadCache = Config.DownloadCache; downloadCache.DownloadHttpClient = httpClient; } logger.Debug("Skip configuration for maxCacheSize and diskCache. They cannot be redefined."); maxCacheSize = Config.MaxCacheSize; diskCache = Config.DiskCache; // Redefine these if they were provided only httpClient = httpClient ?? Config.HttpClient; scheduler = scheduler ?? Config.Scheduler; logger = logger ?? Config.Logger; downloadCache = downloadCache ?? Config.DownloadCache; loadWithTransparencyChannel = loadWithTransparencyChannel ?? Config.LoadWithTransparencyChannel; fadeAnimationEnabled = fadeAnimationEnabled ?? Config.FadeAnimationEnabled; transformPlaceholders = transformPlaceholders ?? Config.TransformPlaceholders; downsampleInterpolationMode = downsampleInterpolationMode ?? Config.DownsampleInterpolationMode; } InitializeIfNeeded(maxCacheSize ?? 0, httpClient, scheduler, logger, diskCache, downloadCache, loadWithTransparencyChannel ?? false, fadeAnimationEnabled ?? true, transformPlaceholders ?? true, downsampleInterpolationMode ?? InterpolationMode.Default, httpHeadersTimeout, httpReadTimeout ); } }
private ImageCache(int maxCacheSize, IMiniLogger logger) { _logger = logger; if (maxCacheSize == 0) { //TODO Does anyone know how we could get available app ram from WinRT API? EasClientDeviceInformation deviceInfo = new EasClientDeviceInformation(); if (deviceInfo.OperatingSystem.ToLowerInvariant().Contains("phone")) { maxCacheSize = 1000000 * 64; //64MB } else { maxCacheSize = 1000000 * 256; //256MB } _logger?.Debug($"Memory cache size: {maxCacheSize} bytes"); } _reusableBitmaps = new WriteableBitmapLRUCache(maxCacheSize); }
protected ImageLoaderTaskBase(IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, IDownloadCache downloadCache, bool clearCacheOnOutOfMemory, bool verboseLoadingCancelledLogging) { _verboseLoadingCancelledLogging = verboseLoadingCancelledLogging; _clearCacheOnOutOfMemory = clearCacheOnOutOfMemory; CancellationToken = new CancellationTokenSource(); DownloadCache = downloadCache; Parameters = parameters; NumberOfRetryNeeded = parameters.RetryCount; MainThreadDispatcher = mainThreadDispatcher; Logger = miniLogger; ConfigureParameters(); _hasCustomCacheKey = !string.IsNullOrWhiteSpace(Parameters.CustomCacheKey); _keys = new ConcurrentDictionary <string, string>(); _transformationsKey = new Lazy <string>(() => { if (Parameters.Transformations == null || Parameters.Transformations.Count == 0) { return(string.Empty); } return(";" + string.Join(";", Parameters.Transformations.Select(t => t.Key))); }); _downsamplingKey = new Lazy <string>(() => { if (Parameters.DownSampleSize == null) { return(string.Empty); } return(string.Concat(";", Parameters.DownSampleSize.Item1, "x", Parameters.DownSampleSize.Item2)); }); _rawKey = new Lazy <string>(() => GetKeyInternal(null, true)); _streamKey = new Lazy <string>(() => "Stream" + GetNextStreamIndex()); }
ImageCache(int maxCacheSize, IMiniLogger logger) { _logger = logger; _cache = new NSCache(); _imageInformations = new ConcurrentDictionary <string, ImageInformation>(); if (maxCacheSize <= 0) { _cache.TotalCostLimit = (nuint)(NSProcessInfo.ProcessInfo.PhysicalMemory * 0.2d); // 20% of physical memory } else { _cache.TotalCostLimit = (nuint)Math.Min((NSProcessInfo.ProcessInfo.PhysicalMemory * 0.05d), maxCacheSize); } double sizeInMB = Math.Round(_cache.TotalCostLimit / 1024d / 1024d, 2); logger.Debug(string.Format("Image memory cache size: {0} MB", sizeInMB)); // if we get a memory warning notification we should clear the cache NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIApplicationDidReceiveMemoryWarningNotification"), notif => Clear()); }
private static void TryCreateDir(string snapshotImagePath, IMiniLogger logger, int userId, string userIp) { string directoryName = Path.GetDirectoryName(snapshotImagePath); try { if (string.IsNullOrWhiteSpace(directoryName)) { return; } if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } } catch (Exception ex) { logger?.LogError($"{nameof(WriteImageToFile)}( ): {ex.Message} directoryName: {directoryName}", userId, userIp); throw; } }
public App( Routes routes, int port = Constants.Port, string mode = Constants.ServerMode, IServerStatus serverStatus = null, ISocketMachine socketMachine = null, IProtocolConnectionHandler protocolConnectionHandler = null, IMiniLogger logger = null ) { Config = new ServerConfig(Constants.HostName, port, mode); Logger = logger ?? new MiniLogger(new LogConfig(Config.Mode)); Status = serverStatus ?? new ServerStatus(); SocketMachine = socketMachine ?? new DotNetSocketMachine(); ProtocolConnectionHandler = protocolConnectionHandler ?? new HttpConnectionHandler { SocketReader = new InternalSocketReader(), DataParser = new RequestParser(), RequestProcessor = new RouteHandler(routes) }; SocketMachine.Configure(Config.Port, Config.HostName); }
public static void Initialize(int? maxCacheSize = null, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null, IDiskCache diskCache = null, IDownloadCache downloadCache = null, bool? loadWithTransparencyChannel = null, bool? fadeAnimationEnabled = null, bool? transformPlaceholders = null, InterpolationMode? downsampleInterpolationMode = null, int httpHeadersTimeout = 15, int httpReadTimeout = 30 ) { var cfg = new Configuration(); if (httpClient != null) cfg.HttpClient = httpClient; if (scheduler != null) cfg.Scheduler = scheduler; if (logger != null) cfg.Logger = logger; if (diskCache != null) cfg.DiskCache = diskCache; if (downloadCache != null) cfg.DownloadCache = downloadCache; if (loadWithTransparencyChannel.HasValue) cfg.LoadWithTransparencyChannel = loadWithTransparencyChannel.Value; if (fadeAnimationEnabled.HasValue) cfg.FadeAnimationEnabled = fadeAnimationEnabled.Value; if (transformPlaceholders.HasValue) cfg.TransformPlaceholders = transformPlaceholders.Value; if (downsampleInterpolationMode.HasValue) cfg.DownsampleInterpolationMode = downsampleInterpolationMode.Value; cfg.HttpHeadersTimeout = httpHeadersTimeout; cfg.HttpReadTimeout = httpReadTimeout; if (maxCacheSize.HasValue) cfg.MaxCacheSize = maxCacheSize.Value; Initialize(cfg); }
public ImageProviderService(IImageFromCacheService imageFromCacheService, IImageFromWebCamService imageFromWebCamService, IDateTimeProvider dateTimeProvider, IMiniLogger logger, int cacheUpdaterExpirationMilliSec, CacheUpdaterInfo cacheUpdaterInfo, string imageErrorLogoUrl) { if (cacheUpdaterExpirationMilliSec < MinValueCacheUpdaterLifeTimeMilliSec) { throw new ArgumentException( nameof(cacheUpdaterExpirationMilliSec) + $" = {cacheUpdaterExpirationMilliSec} < {MinValueCacheUpdaterLifeTimeMilliSec}"); } _imageFromCacheService = imageFromCacheService ?? throw new ArgumentNullException(nameof(imageFromCacheService)); _imageFromWebCamService = imageFromWebCamService ?? throw new ArgumentNullException(nameof(imageFromWebCamService)); _dateTimeProvider = dateTimeProvider ?? throw new ArgumentNullException(nameof(dateTimeProvider)); _logger = logger; _cacheUpdaterExpirationMilliSec = cacheUpdaterExpirationMilliSec; _cacheUpdaterInfo = cacheUpdaterInfo ?? new CacheUpdaterInfo(); _imageErrorLogoUrl = imageErrorLogoUrl; }
private static void InitializeIfNeeded(int maxCacheSize = 0, HttpClient httpClient = null, IWorkScheduler scheduler = null, IMiniLogger logger = null, IDiskCache diskCache = null, IDownloadCache downloadCache = null) { if (_initialized) return; lock (_initializeLock) { if (_initialized) return; var userDefinedConfig = new Configuration(maxCacheSize, httpClient, scheduler, logger, diskCache, downloadCache); Config = GetDefaultConfiguration(userDefinedConfig); _initialized = true; } }
public ImageCache(int maxCacheSize, IMiniLogger logger, bool verboseLogging) : base(maxCacheSize, logger, verboseLogging) { }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, Func <UIView> getNativeControl, Action <UIImage, bool, bool> doWithImage, nfloat imageScale) : base(mainThreadDispatcher, miniLogger, parameters, true) { _getNativeControl = getNativeControl; _doWithImage = doWithImage; _imageScale = imageScale; DownloadCache = downloadCache; }
/// <summary> /// This constructor is useful for child classes only. It can help when having a totally different loading logic. /// </summary> /// <param name="miniLogger">Logger</param> /// <param name="key">Key.</param> /// <param name="imageView">Image view.</param> protected ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, string key, ImageView imageView) : this(downloadCache, mainThreadDispatcher, miniLogger, TaskParameter.FromFile(key), imageView) { }
public MiniLoggerWrapper(IMiniLogger logger, bool verboseLogging) { _logger = logger; _verboseLogging = verboseLogging; }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ImageView imageView) : base(mainThreadDispatcher, miniLogger, parameters) { CancellationToken = new CancellationTokenSource(); Context = Android.App.Application.Context.ApplicationContext; DownloadCache = downloadCache; _imageWeakReference = new WeakReference <ImageView>(imageView); UseFadeInBitmap = true; }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, nfloat imageScale, ITarget <UIImage, ImageLoaderTask> target, bool clearCacheOnOutOfMemory) : base(mainThreadDispatcher, miniLogger, parameters, downloadCache, true, clearCacheOnOutOfMemory) { if (target == null) { throw new ArgumentNullException(nameof(target)); } _target = target; }
private ImageCache(int maxCacheSize, IMiniLogger logger) { _logger = logger; _reusableBitmaps = new ConcurrentDictionary<string, Tuple<WeakReference<WriteableBitmap>, ImageInformation>>(); }
public ImageLoaderTask(IDownloadCache downloadCache, IMainThreadDispatcher mainThreadDispatcher, IMiniLogger miniLogger, TaskParameter parameters, ITarget <WriteableBitmap, ImageLoaderTask> target, bool clearCacheOnOutOfMemory) : base(mainThreadDispatcher, miniLogger, parameters, false, clearCacheOnOutOfMemory) { if (target == null) { throw new ArgumentNullException(nameof(target)); } _target = target; DownloadCache = downloadCache; }