Ejemplo n.º 1
0
        /// <summary>
        /// Returns the integer id for a given GUID
        /// </summary>
        /// <param name="key"></param>
        /// <param name="umbracoObjectType"></param>
        /// <returns></returns>
        public Attempt <int> GetIdForKey(Guid key, UmbracoObjectTypes umbracoObjectType)
        {
            var result = _runtimeCache.GetCacheItem <int?>(CacheKeys.IdToKeyCacheKey + key, () =>
            {
                using (var uow = UowProvider.GetUnitOfWork())
                {
                    switch (umbracoObjectType)
                    {
                    case UmbracoObjectTypes.Document:
                    case UmbracoObjectTypes.MemberType:
                    case UmbracoObjectTypes.Media:
                    case UmbracoObjectTypes.Template:
                    case UmbracoObjectTypes.MediaType:
                    case UmbracoObjectTypes.DocumentType:
                    case UmbracoObjectTypes.Member:
                    case UmbracoObjectTypes.DataType:
                        return(uow.Database.ExecuteScalar <int?>(new Sql().Select("id").From <NodeDto>().Where <NodeDto>(dto => dto.UniqueId == key)));

                    case UmbracoObjectTypes.RecycleBin:
                    case UmbracoObjectTypes.Stylesheet:
                    case UmbracoObjectTypes.MemberGroup:
                    case UmbracoObjectTypes.ContentItem:
                    case UmbracoObjectTypes.ContentItemType:
                    case UmbracoObjectTypes.ROOT:
                    case UmbracoObjectTypes.Unknown:
                    default:
                        throw new NotSupportedException();
                    }
                }
            });

            return(result.HasValue ? Attempt.Succeed(result.Value) : Attempt <int> .Fail());
        }
        /// <inheritdoc/>
        public TreeNode <ProductFilterGroupNode> GetTree(params Guid[] collectionKeys)
        {
            var cacheKey = GetCacheKey(collectionKeys);

            var tree = (TreeNode <ProductFilterGroupNode>)_cache.GetCacheItem(cacheKey);

            if (tree != null)
            {
                return(tree);
            }


            // get all of the filter groups
            var filterGroups = _getter.Invoke().ToArray();

            // create a specific context for each filter group and filter (within the group)
            var contextKeys = GetContextKeys(filterGroups, collectionKeys);

            var tuples = CountKeysThatExistInAllCollections(contextKeys);

            tree = BuildTreeNode(filterGroups, tuples, collectionKeys);


            return((TreeNode <ProductFilterGroupNode>)_cache.GetCacheItem(cacheKey, () => tree, TimeSpan.FromHours(6)));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the Url from the UmbracoUrl type
        /// </summary>
        /// <param name="umbracoUrl">The umbraco url object from the app's config</param>
        /// <returns>The Unauthorised Url, or null</returns>
        public string Url(UmbracoUrl umbracoUrl)
        {
            if (string.IsNullOrEmpty(umbracoUrl.Value))
            {
                LogHelper.Error <UmbracoUrlService>("Error: No Unauthorized URL set in configuration", null);
                return(null);
            }

            if (umbracoUrl.Type == UmbracoUrlTypes.Url)
            {
                return(umbracoUrl.Value);
            }
            if (cache == null)
            {
                cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
            }

            return(cache.GetCacheItem <string>(CacheKeyUrl + umbracoUrl.Value, () =>
            {
                EnsureUmbracoContext(HttpContext.Current);
                var umbContext = UmbracoContext.Current;
                if (umbContext == null)
                {
                    LogHelper.Error <UmbracoUrlService>("Need to run this method from within a valid HttpContext request", null);
                    return null;
                }

                var umbracoContentService = new UmbracoContentService(umbContext);
                switch (umbracoUrl.Type)
                {
                case UmbracoUrlTypes.XPath:
                    var xpathId = umbracoContentService.XPath(umbracoUrl.Value);
                    if (xpathId != null)
                    {
                        return umbracoContentService.Url((int)xpathId);
                    }

                    LogHelper.Error <UmbracoUrlService>($"Error: Unable to find content using xpath of '{umbracoUrl.Value}'", null);
                    break;

                case UmbracoUrlTypes.ContentPicker:
                    if (int.TryParse(umbracoUrl.Value, out var id))
                    {
                        return umbracoContentService.Url(id);
                    }

                    LogHelper.Error <UmbracoUrlService>("Error: Unable to parse the selected unauthorized URL content picker item. Please ensure a valid content node is selected", null);
                    break;

                default:
                    LogHelper.Error <UmbracoUrlService>("Error: Unable to determine which method to use to get the unauthorized URL. Please ensure URL, XPath or Content Picker is selected", null);
                    break;
                }
                return null;
            }, CacheDuration));
        }
        public void GetCachedItem_ReturnsNull()
        {
            //// Arrange
            var key = Guid.NewGuid().ToString();

            //// Act
            var result = runtimeCache.GetCacheItem(key);

            //// Assert
            Assert.That(result, Is.Null);
        }
Ejemplo n.º 5
0
 public TT GetCacheItem <TT>(string cacheKey)
 {
     if (_enableCache == false)
     {
         return(_nullHttpCache.GetCacheItem <TT>(cacheKey));
     }
     else
     {
         return(_httpCache.GetCacheItem <TT>(cacheKey));
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets all entities of type TEntity or a list according to the passed in Guid Keys
        /// </summary>
        /// <param name="keys">The keys of the entities to be returned</param>
        /// <returns>A collection of entities</returns>
        public IEnumerable <TEntity> GetAll(params Guid[] Keys)
        {
            if (Keys.Any())
            {
                var entities = new List <TEntity>();

                foreach (var key in Keys)
                {
                    var entity = _cache.GetCacheItem(GetCacheKey(key));
                    if (entity != null)
                    {
                        entities.Add((TEntity)entity);
                    }
                }

                if (entities.Count().Equals(Keys.Count()) && entities.Any(x => x.Equals(default(TEntity))) == false)
                {
                    return(entities);
                }
            }
            else
            {
                var allEntities = _cache.GetCacheItemsByKeySearch(typeof(TEntity).Name + ".").ToArray();


                if (allEntities.Any())
                {
                    var query      = this.GetBaseQuery(true);
                    var totalCount = PerformCount(query);

                    if (allEntities.Count() == totalCount)
                    {
                        return(allEntities.Select(x => (TEntity)x));
                    }
                }
            }

            var entityCollection = PerformGetAll(Keys).ToArray();

            foreach (var entity in entityCollection)
            {
                if (!entity.Equals(default(TEntity)))
                {
                    var en = entity;
                    _cache.GetCacheItem(GetCacheKey(entity.Key), () => en);
                }
            }

            return(entityCollection);
        }
Ejemplo n.º 7
0
        internal static void DeleteRow(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider cache, IShippingFixedRateTable rateTable, IShipRateTier shipRateTier)
        {
            //var row = Rows.FirstOrDefault(x => x.Key == shipRateTier.Key);
            //if (!Rows.Any() || row == null) return;
            //if (Rows.IndexOf(Rows.Last()) != Rows.IndexOf(row))
            //{
            //    _shipRateTiers[Rows.IndexOf(row) + 1].RangeLow = row.RangeLow;
            //}
            //_shipRateTiers.Remove(row);

            var row = rateTable.Rows.FirstOrDefault(x => x.Key == shipRateTier.Key);

            if (!rateTable.Rows.Any() || row == null)
            {
                return;
            }

            if (rateTable.Rows.IndexOf(rateTable.Rows.Last()) != rateTable.Rows.IndexOf(row))
            {
                rateTable.Rows.First(x => x.RangeLow == row.RangeHigh).RangeLow = row.RangeLow;
            }

            // clear the current cached item
            // TODO : This should use the distributed cache referesher
            cache.ClearCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey));

            gatewayProviderService.Save(rateTable.Rows);
            gatewayProviderService.Delete(shipRateTier);

            cache.GetCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey), () => rateTable);
        }
        /// <summary>
        /// Returns the enumerable of all extension method info's in the app domain = USE SPARINGLY!!!
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// We cache this as a sliding 5 minute exiration, in unit tests there's over 1100 methods found, surely that will eat up a bit of memory so we want
        /// to make sure we give it back.
        /// </remarks>
        private static IEnumerable <MethodInfo> GetAllExtensionMethodsInAppDomain(IRuntimeCacheProvider runtimeCacheProvider)
        {
            if (runtimeCacheProvider == null)
            {
                throw new ArgumentNullException("runtimeCacheProvider");
            }

            return(runtimeCacheProvider.GetCacheItem <MethodInfo[]>(typeof(ExtensionMethodFinder).Name, () => TypeFinder.GetAssembliesWithKnownExclusions()
                                                                    // assemblies that contain extension methods
                                                                    .Where(a => a.IsDefined(typeof(ExtensionAttribute), false))
                                                                    // types that contain extension methods
                                                                    .SelectMany(a => a.GetTypes()
                                                                                .Where(t => t.IsDefined(typeof(ExtensionAttribute), false) && t.IsSealed && t.IsGenericType == false && t.IsNested == false))
                                                                    // actual extension methods
                                                                    .SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public)
                                                                                .Where(m => m.IsDefined(typeof(ExtensionAttribute), false)))
                                                                    // and also IEnumerable<T> extension methods - because the assembly is excluded
                                                                    .Concat(typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public))
                                                                    //If we don't do this then we'll be scanning all assemblies each time!
                                                                    .ToArray(),

                                                                    //only cache for 5 minutes
                                                                    timeout: TimeSpan.FromMinutes(5),

                                                                    //each time this is accessed it will be for 5 minutes longer
                                                                    isSliding: true));
        }
Ejemplo n.º 9
0
 public List <DtgeManifest> GetAllCachedManifests(bool purgeCache = false)
 {
     if (purgeCache)
     {
         _cache.ClearCacheItem("skttlDtgeTreeManifests");
     }
     return(_cache.GetCacheItem <List <DtgeManifest> >("skttlDtgeTreeManifests", () => GetAllManifests(), new TimeSpan(1, 0, 0)));
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Get all registered manifests
 /// </summary>
 /// <returns></returns>
 /// <remarks>
 /// This ensures that we only build and look for all manifests once per Web app (based on the IRuntimeCache)
 /// </remarks>
 public IEnumerable <PackageManifest> GetManifests()
 {
     return(_cache.GetCacheItem <IEnumerable <PackageManifest> >(typeof(ManifestParser) + "GetManifests", () =>
     {
         //get all Manifest.js files in the appropriate folders
         var manifestFileContents = GetAllManifestFileContents(_pluginsDir);
         return CreateManifests(manifestFileContents.ToArray());
     }, new TimeSpan(0, 10, 0)));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// The perform geocode.
 /// </summary>
 /// <param name="formattedAddress">
 /// The formatted address.
 /// </param>
 /// <returns>
 /// The <see cref="IGeocodeProviderResponse"/>.
 /// </returns>
 private IGeocodeProviderResponse TryGetGeocode(string formattedAddress)
 {
     return(_settings.EnableCaching
         ? (IGeocodeProviderResponse)_cache
            .GetCacheItem(
                Caching.CacheKeys.GetGeocodeRequestCacheKey(GetType(), formattedAddress),
                () => GetResponse(formattedAddress),
                new TimeSpan(0, 0, 0, _settings.CacheDuration))
         : GetResponse(formattedAddress));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// The get ship rate table.
 /// </summary>
 /// <param name="gatewayProviderService">
 /// The gateway provider service.
 /// </param>
 /// <param name="runtimeCacheProvider">
 /// The runtime cache provider.
 /// </param>
 /// <param name="shipMethodKey">
 /// The ship method key.
 /// </param>
 /// <returns>
 /// The <see cref="ShippingFixedRateTable"/>.
 /// </returns>
 internal static ShippingFixedRateTable GetShipRateTable(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider runtimeCacheProvider, Guid shipMethodKey)
 {
     return((ShippingFixedRateTable)runtimeCacheProvider.GetCacheItem(
                CacheKeys.GatewayShipMethodCacheKey(shipMethodKey),
                delegate
     {
         var rows = gatewayProviderService.GetShipRateTiersByShipMethodKey(shipMethodKey);
         return new ShippingFixedRateTable(shipMethodKey, rows);
     }, TimeSpan.FromHours(6)));
 }
Ejemplo n.º 13
0
        /// <summary>
        /// The save.
        /// </summary>
        /// <param name="gatewayProviderService">
        /// The gateway provider service.
        /// </param>
        /// <param name="cache">
        /// The cache.
        /// </param>
        /// <param name="rateTable">
        /// The rate table.
        /// </param>
        internal static void Save(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider cache, IShippingFixedRateTable rateTable)
        {
            // clear the current cached item
            // TODO : This should use the distributed cache referesher
            cache.ClearCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey));

            // persist and enter into cache
            gatewayProviderService.Save(rateTable.Rows);
            cache.GetCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey), () => rateTable, TimeSpan.FromHours(6));
        }
Ejemplo n.º 14
0
 public static JArray GetResult(IRuntimeCacheProvider cache, string url)
 {
     return((JArray)cache.GetCacheItem(url, () =>
     {
         using (var client = new HttpClient())
         {
             var result = client.GetStringAsync(url);
             Task.WaitAll(result);
             return JsonConvert.DeserializeObject <JArray>(result.Result);
         }
     }));
 }
Ejemplo n.º 15
0
        public static T GetCacheItem <T>(this IRuntimeCacheProvider provider,
                                         string cacheKey,
                                         Func <T> getCacheItem,
                                         TimeSpan?timeout,
                                         bool isSliding             = false,
                                         CacheItemPriority priority = CacheItemPriority.Normal,
                                         CacheItemRemovedCallback removedCallback = null,
                                         string[] dependentFiles = null)
        {
            var result = provider.GetCacheItem(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles);

            return(result == null ? default(T) : result.TryConvertTo <T>().Result);
        }
Ejemplo n.º 16
0
        public static JArray GetResult(IRuntimeCacheProvider cache, string url)
        {
            return (JArray)cache.GetCacheItem(url, () =>
            {
                using (var client = new HttpClient())
                {
                    var result = client.GetStringAsync(url);
                    Task.WaitAll(result);
                    return JsonConvert.DeserializeObject<JArray>(result.Result);
                }
            });

        }
        /// <summary>
        /// Returns permissions for a given user for any number of nodes
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="entityIds"></param>
        /// <returns></returns>
        public IEnumerable <EntityPermission> GetUserPermissionsForEntities(int userId, params int[] entityIds)
        {
            var entityIdKey = string.Join(",", entityIds.Select(x => x.ToString(CultureInfo.InvariantCulture)));

            return(_runtimeCache.GetCacheItem <IEnumerable <EntityPermission> >(
                       string.Format("{0}{1}{2}", CacheKeys.UserPermissionsCacheKey, userId, entityIdKey),
                       () =>
            {
                var whereBuilder = new StringBuilder();

                //where userId = @userId AND
                whereBuilder.Append(_sqlSyntax.GetQuotedColumnName("userId"));
                whereBuilder.Append("=");
                whereBuilder.Append(userId);

                if (entityIds.Any())
                {
                    whereBuilder.Append(" AND ");

                    //where nodeId = @nodeId1 OR nodeId = @nodeId2, etc...
                    whereBuilder.Append("(");
                    for (var index = 0; index < entityIds.Length; index++)
                    {
                        var entityId = entityIds[index];
                        whereBuilder.Append(_sqlSyntax.GetQuotedColumnName("nodeId"));
                        whereBuilder.Append("=");
                        whereBuilder.Append(entityId);
                        if (index < entityIds.Length - 1)
                        {
                            whereBuilder.Append(" OR ");
                        }
                    }
                    whereBuilder.Append(")");
                }

                var sql = new Sql();
                sql.Select("*")
                .From <User2NodePermissionDto>()
                .Where(whereBuilder.ToString());

                //ToArray() to ensure it's all fetched from the db once.
                var result = _unitOfWork.Database.Fetch <User2NodePermissionDto>(sql).ToArray();
                return ConvertToPermissionList(result);
            },
                       //Since this cache can be quite large (http://issues.umbraco.org/issue/U4-2161) we will only have this exist in cache for 20 minutes,
                       // then it will refresh from the database.
                       new TimeSpan(0, 20, 0),
                       //Since this cache can be quite large (http://issues.umbraco.org/issue/U4-2161) we will make this priority below average
                       priority: CacheItemPriority.BelowNormal));
        }
Ejemplo n.º 18
0
        public string[] GetResult()
        {
            return((string[])_cache.GetCacheItem(typeof(GitHubFeed).ToString(), () =>
            {
                using (var client = new HttpClient())
                {
                    var result = client.GetStringAsync(_url);
                    Task.WaitAll(result);
                    var xml = XDocument.Parse(result.Result);
                    var ns = XNamespace.Get("http://www.w3.org/2005/Atom");

                    return xml.Root.Descendants(ns + "content").Select(x => x.Value).Take(_maxResults).ToArray();
                }
            }, TimeSpan.FromHours(0.5)));
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Unit of work method that tells the repository to persist the new entity
 /// </summary>
 /// <param name="entity">The entity to be created</param>
 public virtual void PersistNewItem(IEntity entity)
 {
     try
     {
         PersistNewItem((TEntity)entity);
         _cache.GetCacheItem(GetCacheKey(entity.Key), () => entity);
     }
     catch (Exception)
     {
         ////if an exception is thrown we need to remove the entry from cache, this is ONLY a work around because of the way
         //// that we cache entities: http://issues.umbraco.org/issue/U4-4259
         _cache.ClearCacheItem(GetCacheKey(entity.Key));
         throw;
     }
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Unit of work method that tells the repository to persist the new entity
 /// </summary>
 /// <param name="entity">The entity to be created</param>
 public virtual void PersistNewItem(IEntity entity)
 {
     try
     {
         PersistNewItem((TEntity)entity);
         _cache.GetCacheItem(GetCacheKey(entity.Key), () => entity);
     }
     catch (Exception ex)
     {
         LogHelper.Error(GetType(), "An error occurred trying to add a new entity", ex);
         ////if an exception is thrown we need to remove the entry from cache, this is ONLY a work around because of the way
         //// that we cache entities: http://issues.umbraco.org/issue/U4-4259
         _cache.ClearCacheItem(GetCacheKey(entity.Key));
         throw;
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Gets an entity by the passed in Id
        /// </summary>
        /// <returns></returns>
        public TEntity Get(Guid key)
        {
            var fromCache = TryGetFromCache(key);

            if (fromCache.Success)
            {
                return(fromCache.Result);
            }

            var entity = PerformGet(key);

            if (entity != null)
            {
                _cache.GetCacheItem(GetCacheKey(key), () => entity);
            }

            if (entity != null)
            {
                entity.ResetDirtyProperties();
            }

            return(entity);
        }
Ejemplo n.º 22
0
 protected IEnumerable <DeliveryOption> GetCollectionFromCache(IShipment shipment)
 {
     return(_runtimeCache.GetCacheItem(MakeCacheKey(shipment)) as IEnumerable <DeliveryOption>);
 }
Ejemplo n.º 23
0
        public static string GetCropUrl(
            this IPublishedContent mediaItem,
            int?width                       = null,
            int?height                      = null,
            string propertyAlias            = Constants.Conventions.Media.File,
            string cropAlias                = null,
            int?quality                     = null,
            ImageCropMode?imageCropMode     = null,
            ImageCropAnchor?imageCropAnchor = null,
            bool preferFocalPoint           = false,
            bool useCropDimensions          = false,
            bool cacheBuster                = true,
            string furtherOptions           = null,
            ImageCropRatioMode?ratioMode    = null,
            bool upScale                    = true,
            bool resolveCdnPath             = false)
        {
            string cropUrl = ImageCropperTemplateExtensions.GetCropUrl(
                mediaItem, width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor,
                preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode, upScale);

            if (!resolveCdnPath)
            {
                return(cropUrl);
            }

            string cachePrefix      = "Jaywing-AzureBlobCache";
            string cacheKey         = $"{cachePrefix}{cropUrl}";
            string currentDomain    = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            string absoluteCropPath = $"{currentDomain}{cropUrl}";

            IRuntimeCacheProvider runtimeCache = DependencyResolver.Current.GetService <ApplicationContext>()?.ApplicationCache?.RuntimeCache;

            if (runtimeCache == null)
            {
                return(cropUrl);
            }

            var cachedItem = runtimeCache.GetCacheItem <CachedImage>(cacheKey);

            if (cachedItem != null)
            {
                return(cachedItem.CacheUrl);
            }

            var newCachedImage = new CachedImage {
                WebUrl = cropUrl
            };

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(absoluteCropPath);
                request.Method = WebRequestMethods.Http.Head;
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    HttpStatusCode responseCode = response.StatusCode;
                    if (!responseCode.Equals(HttpStatusCode.OK))
                    {
                        return(cachedItem.CacheUrl);
                    }
                    newCachedImage.CacheUrl = response.ResponseUri.AbsoluteUri;
                    runtimeCache.InsertCacheItem <CachedImage>(cacheKey, () => newCachedImage);
                    return(response.ResponseUri.AbsoluteUri);
                }
            }
            catch
            {
                return(cropUrl);
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// The get ship rate table.
 /// </summary>
 /// <param name="gatewayProviderService">
 /// The gateway provider service.
 /// </param>
 /// <param name="runtimeCacheProvider">
 /// The runtime cache provider.
 /// </param>
 /// <param name="shipMethodKey">
 /// The ship method key.
 /// </param>
 /// <returns>
 /// The <see cref="ShippingFixedRateTable"/>.
 /// </returns>
 internal static ShippingFixedRateTable GetShipRateTable(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider runtimeCacheProvider, Guid shipMethodKey)
 {
     return (ShippingFixedRateTable) runtimeCacheProvider.GetCacheItem(
         CacheKeys.GatewayShipMethodCacheKey(shipMethodKey),
         delegate
             {
                 var rows = gatewayProviderService.GetShipRateTiersByShipMethodKey(shipMethodKey);
                 return new ShippingFixedRateTable(shipMethodKey, rows);
             });
 }
Ejemplo n.º 25
0
        /// <summary>
        /// The save.
        /// </summary>
        /// <param name="gatewayProviderService">
        /// The gateway provider service.
        /// </param>
        /// <param name="cache">
        /// The cache.
        /// </param>
        /// <param name="rateTable">
        /// The rate table.
        /// </param>
        internal static void Save(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider cache, IShippingFixedRateTable rateTable)
        {
            // clear the current cached item
            // TODO : This should use the distributed cache referesher
            cache.ClearCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey));

            // persist and enter into cache
            gatewayProviderService.Save(rateTable.Rows);
            cache.GetCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey), () => rateTable);
        }
Ejemplo n.º 26
0
 public T GetCacheValue <T>(string cacheKey) where T : class
 {
     return((T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}"));
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Returns the cached <see cref="IShipmentRateQuote"/> if it exists
 /// </summary>
 /// <param name="shipment">
 /// The shipment.
 /// </param>
 /// <param name="shippingGatewayMethod">
 /// The shipping Gateway Method.
 /// </param>
 /// <returns>
 /// The <see cref="IShipmentRateQuote"/>.
 /// </returns>
 protected IShipmentRateQuote TryGetCachedShipmentRateQuote(IShipment shipment, IShippingGatewayMethod shippingGatewayMethod)
 {
     return(_runtimeCache.GetCacheItem(GetShipmentRateQuoteCacheKey(shipment, shippingGatewayMethod)) as ShipmentRateQuote);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// The delete row.
        /// </summary>
        /// <param name="gatewayProviderService">
        /// The gateway provider service.
        /// </param>
        /// <param name="cache">
        /// The cache.
        /// </param>
        /// <param name="rateTable">
        /// The rate table.
        /// </param>
        /// <param name="shipRateTier">
        /// The ship rate tier.
        /// </param>
        internal static void DeleteRow(IGatewayProviderService gatewayProviderService, IRuntimeCacheProvider cache, IShippingFixedRateTable rateTable, IShipRateTier shipRateTier)
        {
            var row = rateTable.Rows.FirstOrDefault(x => x.Key == shipRateTier.Key);
            if (!rateTable.Rows.Any() || row == null) return;

            if (rateTable.Rows.IndexOf(rateTable.Rows.Last()) != rateTable.Rows.IndexOf(row))
            {
                rateTable.Rows.First(x => x.RangeLow == row.RangeHigh).RangeLow = row.RangeLow;
            }

            // clear the current cached item
            // TODO : This should use the distributed cache referesher
            cache.ClearCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey));

            gatewayProviderService.Save(rateTable.Rows);
            gatewayProviderService.Delete(shipRateTier);

            cache.GetCacheItem(CacheKeys.GatewayShipMethodCacheKey(rateTable.ShipMethodKey), () => rateTable);
        }  
        /// <summary>
        /// This is used to configure the file sources with the main file sources shipped with Umbraco and also including supplemental/plugin based
        /// localization files. The supplemental files will be loaded in and merged in after the primary files.
        /// The supplemental files must be named with the 4 letter culture name with a hyphen such as : en-AU.xml
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="fileSourceFolder"></param>
        /// <param name="supplementFileSources"></param>
        public LocalizedTextServiceFileSources(
            ILogger logger,
            IRuntimeCacheProvider cache,
            DirectoryInfo fileSourceFolder,
            IEnumerable <LocalizedTextServiceSupplementaryFileSource> supplementFileSources)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }
            if (fileSourceFolder == null)
            {
                throw new ArgumentNullException("fileSourceFolder");
            }

            _logger = logger;
            _cache  = cache;

            //Create the lazy source for the _xmlSources
            _xmlSources = new Lazy <Dictionary <CultureInfo, Lazy <XDocument> > >(() =>
            {
                var result = new Dictionary <CultureInfo, Lazy <XDocument> >();

                if (_fileSourceFolder == null)
                {
                    return(result);
                }

                foreach (var fileInfo in _fileSourceFolder.GetFiles("*.xml"))
                {
                    var localCopy = fileInfo;
                    var filename  = Path.GetFileNameWithoutExtension(localCopy.FullName).Replace("_", "-");

                    //TODO: Fix this nonsense... would have to wait until v8 to store the language files with their correct
                    // names instead of storing them as 2 letters but actually having a 4 letter culture. wtf. So now, we
                    // need to check if the file is 2 letters, then open it to try to find it's 4 letter culture, then use that
                    // if it's successful. We're going to assume (though it seems assuming in the legacy logic is never a great idea)
                    // that any 4 letter file is named with the actual culture that it is!
                    CultureInfo culture = null;
                    if (filename.Length == 2)
                    {
                        //we need to open the file to see if we can read it's 'real' culture, we'll use XmlReader since we don't
                        //want to load in the entire doc into mem just to read a single value
                        using (var fs = fileInfo.OpenRead())
                            using (var reader = XmlReader.Create(fs))
                            {
                                if (reader.IsStartElement())
                                {
                                    if (reader.Name == "language")
                                    {
                                        if (reader.MoveToAttribute("culture"))
                                        {
                                            var cultureVal = reader.Value;
                                            try
                                            {
                                                culture = CultureInfo.GetCultureInfo(cultureVal);
                                                //add to the tracked dictionary
                                                _twoLetterCultureConverter[filename] = culture;
                                            }
                                            catch (CultureNotFoundException)
                                            {
                                                LogHelper.Warn <LocalizedTextServiceFileSources>(
                                                    string.Format("The culture {0} found in the file {1} is not a valid culture", cultureVal, fileInfo.FullName));
                                                //If the culture in the file is invalid, we'll just hope the file name is a valid culture below, otherwise
                                                // an exception will be thrown.
                                            }
                                        }
                                    }
                                }
                            }
                    }
                    if (culture == null)
                    {
                        culture = CultureInfo.GetCultureInfo(filename);
                    }

                    //get the lazy value from cache
                    result[culture] = new Lazy <XDocument>(() => _cache.GetCacheItem <XDocument>(
                                                               string.Format("{0}-{1}", typeof(LocalizedTextServiceFileSources).Name, culture.Name), () =>
                    {
                        XDocument xdoc;

                        //load in primary
                        using (var fs = localCopy.OpenRead())
                        {
                            xdoc = XDocument.Load(fs);
                        }

                        //load in supplementary
                        MergeSupplementaryFiles(culture, xdoc);

                        return(xdoc);
                    }, isSliding: true, timeout: TimeSpan.FromMinutes(10), dependentFiles: new[] { localCopy.FullName }));
                }
                return(result);
            });

            if (fileSourceFolder.Exists == false)
            {
                LogHelper.Warn <LocalizedTextServiceFileSources>("The folder does not exist: {0}, therefore no sources will be discovered", () => fileSourceFolder.FullName);
            }
            else
            {
                _fileSourceFolder      = fileSourceFolder;
                _supplementFileSources = supplementFileSources;
            }
        }