private async void LoadImage() { if (_currentTask != null) { _currentTask.Cancel(); } TaskParameter imageLoader = null; var ffSource = await FFImageSourceBinding.GetImageSourceBinding(Source); if (ffSource == null) { if (internalImage != null) { await MainThreadDispatcher.Instance.PostAsync(() => { internalImage.Source = null; }); } } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Url) { imageLoader = ImageService.Instance.LoadUrl(ffSource.Path, TimeSpan.FromDays(CacheDuration)); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.CompiledResource) { imageLoader = ImageService.Instance.LoadCompiledResource(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.ApplicationBundle) { imageLoader = ImageService.Instance.LoadFileFromApplicationBundle(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Filepath) { imageLoader = ImageService.Instance.LoadFile(ffSource.Path); } if (imageLoader != null) { // CustomKeyFactory if (CacheKeyFactory != null) { var dataContext = DataContext; imageLoader.CacheKey(CacheKeyFactory.GetKey(Source, dataContext)); } // LoadingPlaceholder if (LoadingPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(LoadingPlaceholder); if (placeholderSource != null) { imageLoader.LoadingPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // ErrorPlaceholder if (ErrorPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(ErrorPlaceholder); if (placeholderSource != null) { imageLoader.ErrorPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // Downsample if (DownsampleToViewSize && (Width > 0 || Height > 0)) { if (Height > Width) { imageLoader.DownSampleInDip(height: (int)Height); } else { imageLoader.DownSampleInDip(width: (int)Width); } } else if (DownsampleToViewSize && (MinWidth > 0 || MinHeight > 0)) { if (MinHeight > MinWidth) { imageLoader.DownSampleInDip(height: (int)MinHeight); } else { imageLoader.DownSampleInDip(width: (int)MinWidth); } } else if ((int)DownsampleHeight != 0 || (int)DownsampleWidth != 0) { if (DownsampleHeight > DownsampleWidth) { if (DownsampleUseDipUnits) { imageLoader.DownSampleInDip(height: (int)DownsampleHeight); } else { imageLoader.DownSample(height: (int)DownsampleHeight); } } else { if (DownsampleUseDipUnits) { imageLoader.DownSampleInDip(width: (int)DownsampleWidth); } else { imageLoader.DownSample(width: (int)DownsampleWidth); } } } // Downsample mode imageLoader.DownSampleMode(DownsampleMode); // RetryCount if (RetryCount > 0) { imageLoader.Retry(RetryCount, RetryDelay); } // FadeAnimation imageLoader.FadeAnimation(FadeAnimationEnabled); // TransformPlaceholders imageLoader.TransformPlaceholders(TransformPlaceholders); // Transformations if (Transformations != null && Transformations.Count != 0) { imageLoader.Transform(Transformations); } imageLoader.WithPriority(LoadingPriority); imageLoader.WithCache(CacheType); imageLoader.Finish((work) => OnFinish(new Args.FinishEventArgs(work))); imageLoader.Success((imageInformation, loadingResult) => OnSuccess(new Args.SuccessEventArgs(imageInformation, loadingResult))); imageLoader.Error((exception) => OnError(new Args.ErrorEventArgs(exception))); _currentTask = imageLoader.Into(internalImage); } }
public CacheKeyFactoryTests() { CacheKeyFactory = new CacheKeyFactory(); }
/// <summary> /// Setups the on before image loading. /// You can add additional logic here to configure image loader settings before loading /// </summary> /// <param name="imageLoader">Image loader.</param> /// <param name="source">Source.</param> /// <param name="loadingPlaceholderSource">Loading placeholder source.</param> /// <param name="errorPlaceholderSource">Error placeholder source.</param> protected internal virtual void SetupOnBeforeImageLoading(out Work.TaskParameter imageLoader, IImageSourceBinding source, IImageSourceBinding loadingPlaceholderSource, IImageSourceBinding errorPlaceholderSource) { if (source.ImageSource == Work.ImageSource.Url) { imageLoader = ImageService.Instance.LoadUrl(source.Path, CacheDuration); } else if (source.ImageSource == Work.ImageSource.CompiledResource) { imageLoader = ImageService.Instance.LoadCompiledResource(source.Path); } else if (source.ImageSource == Work.ImageSource.ApplicationBundle) { imageLoader = ImageService.Instance.LoadFileFromApplicationBundle(source.Path); } else if (source.ImageSource == Work.ImageSource.Filepath) { imageLoader = ImageService.Instance.LoadFile(source.Path); } else if (source.ImageSource == Work.ImageSource.Stream) { imageLoader = ImageService.Instance.LoadStream(source.Stream); } else if (source.ImageSource == Work.ImageSource.EmbeddedResource) { imageLoader = ImageService.Instance.LoadEmbeddedResource(source.Path); } else { imageLoader = null; return; } // CustomKeyFactory if (CacheKeyFactory != null) { var bindingContext = BindingContext; imageLoader.CacheKey(CacheKeyFactory.GetKey(Source, bindingContext)); } // LoadingPlaceholder if (LoadingPlaceholder != null) { if (loadingPlaceholderSource != null) { imageLoader.LoadingPlaceholder(loadingPlaceholderSource.Path, loadingPlaceholderSource.ImageSource); } } // ErrorPlaceholder if (ErrorPlaceholder != null) { if (errorPlaceholderSource != null) { imageLoader.ErrorPlaceholder(errorPlaceholderSource.Path, errorPlaceholderSource.ImageSource); } } // Enable vector image source var vect1 = Source as IVectorImageSource; var vect2 = LoadingPlaceholder as IVectorImageSource; var vect3 = ErrorPlaceholder as IVectorImageSource; if (vect1 != null) { imageLoader.WithCustomDataResolver(vect1.GetVectorDataResolver()); } if (vect2 != null) { imageLoader.WithCustomLoadingPlaceholderDataResolver(vect2.GetVectorDataResolver()); } if (vect3 != null) { imageLoader.WithCustomErrorPlaceholderDataResolver(vect3.GetVectorDataResolver()); } if (CustomDataResolver != null) { imageLoader.WithCustomDataResolver(CustomDataResolver); imageLoader.WithCustomLoadingPlaceholderDataResolver(CustomDataResolver); imageLoader.WithCustomErrorPlaceholderDataResolver(CustomDataResolver); } // Downsample if (DownsampleToViewSize && (WidthRequest > 0 || HeightRequest > 0)) { if (HeightRequest > WidthRequest) { imageLoader.DownSampleInDip(height: (int)HeightRequest); } else { imageLoader.DownSampleInDip(width: (int)WidthRequest); } } else if (DownsampleToViewSize && (Width > 0 || Height > 0)) { if (Height > Width) { imageLoader.DownSampleInDip(height: (int)Height); } else { imageLoader.DownSampleInDip(width: (int)Width); } } else if ((int)DownsampleHeight != 0 || (int)DownsampleWidth != 0) { if (DownsampleHeight > DownsampleWidth) { if (DownsampleUseDipUnits) { imageLoader.DownSampleInDip(height: (int)DownsampleHeight); } else { imageLoader.DownSample(height: (int)DownsampleHeight); } } else { if (DownsampleUseDipUnits) { imageLoader.DownSampleInDip(width: (int)DownsampleWidth); } else { imageLoader.DownSample(width: (int)DownsampleWidth); } } } else if (DownsampleToViewSize) { // Fallback to a constant value due to a lot people misusing DownsampleToViewSize property // More here: https://github.com/luberda-molinet/FFImageLoading/wiki/Xamarin.Forms-API#downsampletoviewsize-bool-default-false imageLoader.DownSample(height: 100); ImageService.Instance.Config.Logger?.Error("DownsampleToViewSize failed - view is expandable in both dimensions, so it doesn't have a size. Please use DownsampleWidth or DownsampleHeight property."); } // RetryCount if (RetryCount > 0) { imageLoader.Retry(RetryCount, RetryDelay); } if (BitmapOptimizations.HasValue) { imageLoader.BitmapOptimizations(BitmapOptimizations.Value); } // FadeAnimation if (FadeAnimationEnabled.HasValue) { imageLoader.FadeAnimation(FadeAnimationEnabled.Value, duration: FadeAnimationDuration); } // FadeAnimationForCachedImages if (FadeAnimationEnabled.HasValue && FadeAnimationForCachedImages.HasValue) { imageLoader.FadeAnimation(FadeAnimationEnabled.Value, FadeAnimationForCachedImages.Value, FadeAnimationDuration); } // TransformPlaceholders if (TransformPlaceholders.HasValue) { imageLoader.TransformPlaceholders(TransformPlaceholders.Value); } // Transformations if (Transformations != null && Transformations.Count > 0) { imageLoader.Transform(Transformations); } imageLoader.WithPriority(LoadingPriority); if (CacheType.HasValue) { imageLoader.WithCache(CacheType.Value); } if (LoadingDelay.HasValue) { imageLoader.Delay(LoadingDelay.Value); } imageLoader.DownloadStarted((downloadInformation) => OnDownloadStarted(new CachedImageEvents.DownloadStartedEventArgs(downloadInformation))); imageLoader.DownloadProgress((progress) => OnDownloadProgress(new CachedImageEvents.DownloadProgressEventArgs(progress))); imageLoader.FileWriteFinished((fileWriteInfo) => OnFileWriteFinished(new CachedImageEvents.FileWriteFinishedEventArgs(fileWriteInfo))); imageLoader.Error((exception) => OnError(new CachedImageEvents.ErrorEventArgs(exception))); imageLoader.Finish((work) => OnFinish(new CachedImageEvents.FinishEventArgs(work))); imageLoader.Success((imageInformation, loadingResult) => OnSuccess(new CachedImageEvents.SuccessEventArgs(imageInformation, loadingResult))); SetupOnBeforeImageLoading(imageLoader); }
private async Task SaveKeyAsync <T>(KeyTypeEnum keyType, T key) { this.memoryCache.Set(CacheKeyFactory.GetKeyCipher(keyType), key); this.logger.LogDebug($"Successfully sync {keyType.ToString()} key(s) from KMS."); await Task.CompletedTask; }
private string GetPartitionKey(bool isAppCache, MsalAccessTokenCacheItem atItem) { return(isAppCache ? CacheKeyFactory.GetClientCredentialKey(atItem.ClientId, atItem.TenantId, atItem.KeyId) : CacheKeyFactory.GetKeyFromCachedItem(atItem)); }
/// <summary> /// Add Signing credential by Redis /// </summary> /// <param name="builder">IIdentityServerBuilder</param> /// <param name="appSettings">AppSettings</param> /// <returns>IIdentityServerBuilder</returns> public static IIdentityServerBuilder AddSigningCredentialByRedis( this IIdentityServerBuilder builder, AppSettings appSettings) { // Variables const int DEFAULT_EXPIRY_YEAR = 1; var utcNow = DateTimeOffset.UtcNow; var redisKeyWorkingSk = CacheKeyFactory.SigningCredential(); var redisKeyDeprecatedSk = CacheKeyFactory.SigningCredential(isDeprecated: true); // RSA key object Microsoft.IdentityModel.Tokens.RsaSecurityKey key = null; // The Key for Idsrv // Signing credetial object from Redis SigningCredential credential = null; // The Signing credential stored in Redis List <SigningCredential> deprecatedCredentials = null; // The Deprecated Signing credentials stored in Redis using (ICacheService redis = new RedisService(appSettings)) { bool isSigningCredentialExists = redis.GetCache(redisKeyWorkingSk, out credential); if (isSigningCredentialExists && credential.ExpireOn >= utcNow) { // Use the RSA key pair stored in redis key = CryptoHelper.CreateRsaSecurityKey(credential.Parameters, credential.KeyId); } else if (isSigningCredentialExists && credential.ExpireOn < utcNow) { #region Move the expired Signing credential to Redis's Decprecated-Signing-Credential key _ = redis.GetCache(redisKeyDeprecatedSk, out deprecatedCredentials); if (deprecatedCredentials == null) { deprecatedCredentials = new List <SigningCredential>(); } deprecatedCredentials.Add(credential); redis.SaveCache(redisKeyDeprecatedSk, deprecatedCredentials); #endregion #region Clear the expired Signing credential from Redis's Signing-Credential key redis.ClearCache(redisKeyWorkingSk); #endregion // Set flag as False isSigningCredentialExists = false; } #region If no available Signing credial, create a new one if (!isSigningCredentialExists) { key = CryptoHelper.CreateRsaSecurityKey(); RSAParameters parameters = key.Rsa == null ? parameters = key.Parameters : key.Rsa.ExportParameters(includePrivateParameters: true); var expireOn = appSettings.Global?.SigningCredential?.DefaultExpiry == null? utcNow.AddYears(DEFAULT_EXPIRY_YEAR) : appSettings.Global.SigningCredential.DefaultExpiry.GetExpireOn(); credential = new SigningCredential { Parameters = parameters, KeyId = key.KeyId, ExpireOn = expireOn }; // Save to Redis redis.SaveCache(redisKeyWorkingSk, credential); } #endregion // Add the key as the Signing credential for Idsrv builder.AddSigningCredential(key, IdentityServerConstants.RsaSigningAlgorithm.RS256); // Also add the expired key for clients' old tokens if (redis.GetCache(redisKeyDeprecatedSk, out deprecatedCredentials)) { IList <SecurityKeyInfo> deprecatedKeyInfos = new List <SecurityKeyInfo>(); deprecatedCredentials.ForEach(dc => { var deprecatedKeyInfo = new SecurityKeyInfo { Key = CryptoHelper.CreateRsaSecurityKey(dc.Parameters, dc.KeyId), SigningAlgorithm = SecurityAlgorithms.RsaSha256 }; deprecatedKeyInfos.Add(deprecatedKeyInfo); // builder.AddValidationKey(deprecatedKey, IdentityServerConstants.RsaSigningAlgorithm.RS256)); }); builder.AddValidationKey(deprecatedKeyInfos.ToArray()); } } return(builder); }
private async void LoadImage() { if (_currentTask != null) { _currentTask.Cancel(); } TaskParameter imageLoader = null; var ffSource = await FFImageSourceBinding.GetImageSourceBinding(Source); if (ffSource == null) { if (internalImage != null) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { internalImage.Source = null; }); } } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Url) { imageLoader = ImageService.LoadUrl(ffSource.Path, TimeSpan.FromDays(CacheDuration)); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.CompiledResource) { imageLoader = ImageService.LoadCompiledResource(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.ApplicationBundle) { imageLoader = ImageService.LoadFileFromApplicationBundle(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Filepath) { imageLoader = ImageService.LoadFile(ffSource.Path); } if (imageLoader != null) { // CustomKeyFactory if (CacheKeyFactory != null) { var dataContext = DataContext; imageLoader.CacheKey(CacheKeyFactory.GetKey(Source, dataContext)); } // LoadingPlaceholder if (LoadingPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(LoadingPlaceholder); if (placeholderSource != null) { imageLoader.LoadingPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // ErrorPlaceholder if (ErrorPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(ErrorPlaceholder); if (placeholderSource != null) { imageLoader.ErrorPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // Downsample if (DownsampleToViewSize && (Width > 0 || Height > 0)) { if (Height > Width) { imageLoader.DownSample(height: Height.PointsToPixels()); } else { imageLoader.DownSample(width: Width.PointsToPixels()); } } else if (DownsampleToViewSize && (MinWidth > 0 || MinHeight > 0)) { if (MinHeight > MinWidth) { imageLoader.DownSample(height: MinHeight.PointsToPixels()); } else { imageLoader.DownSample(width: MinWidth.PointsToPixels()); } } else if ((int)DownsampleHeight != 0 || (int)DownsampleWidth != 0) { if (DownsampleHeight > DownsampleWidth) { imageLoader.DownSample(height: DownsampleUseDipUnits ? DownsampleHeight.PointsToPixels() : (int)DownsampleHeight); } else { imageLoader.DownSample(width: DownsampleUseDipUnits ? DownsampleWidth.PointsToPixels() : (int)DownsampleWidth); } } // Downsample mode imageLoader.DownSampleMode(DownsampleMode); // RetryCount if (RetryCount > 0) { imageLoader.Retry(RetryCount, RetryDelay); } // FadeAnimation imageLoader.FadeAnimation(FadeAnimationEnabled); // TransformPlaceholders imageLoader.TransformPlaceholders(TransformPlaceholders); // Transformations if (Transformations != null && Transformations.Count != 0) { imageLoader.Transform(Transformations); } _currentTask = imageLoader.Into(internalImage); } }
private bool TryFindBinary(string url, string localPath, bool retrieveData, out IBinary binary) { string physicalPath = localPath ?? Path.Combine(Configuration.BinaryFileSystemCachePath, Path.GetFileName(url)); LoggerService.Debug($"Using physical path {physicalPath}"); binary = new Binary(); Dimensions dimensions = null; string urlWithoutDimensions = StripDimensions(url, out dimensions); if (LoadBinariesAsStream) { LoggerService.Information("retrieving binaries as a stream is obsolete; support will be dropped in future versions of DD4T"); binary.BinaryStream = BinaryProvider.GetBinaryStreamByUrl(urlWithoutDimensions); if (binary.BinaryStream == null) { return(false); } } string cacheKey = CacheKeyFactory.GenerateKey(urlWithoutDimensions); try { IBinaryMeta binaryMeta = CacheAgent.Load(cacheKey) as IBinaryMeta; bool metaWasInCache = true; if (binaryMeta == null) { metaWasInCache = false; binaryMeta = BinaryProvider.GetBinaryMetaByUrl(urlWithoutDimensions); if (binaryMeta == null) { throw new BinaryNotFoundException(); } CacheAgent.Store(cacheKey, "Binary", binaryMeta, new List <string> { binaryMeta.Id }); } if (FileExistsAndIsNotEmpty(physicalPath)) { if (binaryMeta.HasLastPublishedDate || metaWasInCache) { DateTime fileModifiedDate = File.GetLastWriteTime(physicalPath); if (fileModifiedDate.CompareTo(binaryMeta.LastPublishedDate) >= 0) { LoggerService.Debug("binary {0} is still up to date, no action required", urlWithoutDimensions); // TODO: load bytes from file system into binary if (retrieveData) { FillBinaryFromLocalFS(binary, physicalPath); } CopyBinaryMetaToBinary(binaryMeta, binary); return(true); } } } // the normal situation (where a binary is still in Tridion and it is present on the file system already and it is up to date) is now covered // Let's handle the exception situations. byte[] bytes = BinaryProvider.GetBinaryByUrl(urlWithoutDimensions); if (bytes == null || bytes.Length == 0) { throw new BinaryNotFoundException(); } bool fileIsCreated = WriteBinaryToFile(bytes, physicalPath, dimensions); if (!fileIsCreated) { LoggerService.Warning($"file '{physicalPath}' could not be created, binary {binary.Id} cannot be returned"); return(false); } if (retrieveData) { if (dimensions == null) { binary.BinaryData = bytes; } else { FillBinaryFromLocalFS(binary, physicalPath); } } CopyBinaryMetaToBinary(binaryMeta, binary); return(true); } catch (BinaryNotFoundException) { LoggerService.Debug("Binary with url {0} not found", urlWithoutDimensions); // binary does not exist in Tridion, it should be removed from the local file system too if (File.Exists(physicalPath)) { DeleteFile(physicalPath); } return(false); } catch (Exception e) { LoggerService.Warning($"Caught unexpected exception while retrieving binary with url {urlWithoutDimensions} (requested url: {url}. Error message: {e.Message}\r\n{e.StackTrace}"); if (File.Exists(physicalPath)) { DeleteFile(physicalPath); } throw e; } }