Ejemplo n.º 1
0
        public string ResolveLink(string sourcePageUri, string componentUri, string excludeComponentTemplateUri)
        {
            string cacheKey = String.Format(CacheKeyFormatExtended, sourcePageUri, componentUri, excludeComponentTemplateUri);
            string link     = (string)CacheAgent.Load(cacheKey);

            if (link != null)
            {
                if (link.Equals(CacheValueNull))
                {
                    return(null);
                }
                return(link);
            }
            else
            {
                string resolvedUrl = LinkProvider.ResolveLink(sourcePageUri, componentUri, excludeComponentTemplateUri);
                if (resolvedUrl == null)
                {
                    //CacheAgent.Store(cacheKey, CacheRegion, CacheValueNull, new List<string>() { String.Format("ComponentByUri_{0}", componentUri) });
                    CacheAgent.Store(cacheKey, CacheRegion, CacheValueNull);
                }
                else
                {
                    //CacheAgent.Store(cacheKey, CacheRegion, resolvedUrl, new List<string>() { String.Format("ComponentByUri_{0}", componentUri) });
                    CacheAgent.Store(cacheKey, CacheRegion, resolvedUrl);
                }
                return(resolvedUrl);
            }
        }
Ejemplo n.º 2
0
        public bool TryGetPageContent(string tcmUri, out string pageContent)
        {
            pageContent = string.Empty;

            string cacheKey = String.Format("PageContentByUri_{0}", tcmUri);

            pageContent = (string)CacheAgent.Load(cacheKey);
            if (pageContent != null)
            {
                return(true);
            }
            else
            {
                string tempPageContent = PageProvider.GetContentByUri(tcmUri);
                if (tempPageContent != string.Empty)
                {
                    pageContent = tempPageContent;
                    CacheAgent.Store(cacheKey, CacheRegion, pageContent);
                    return(true);
                }
            }


            return(false);
        }
Ejemplo n.º 3
0
        public bool TryGetPage(string tcmUri, out IPage page)
        {
            page = null;

            string cacheKey = String.Format("PageByUri_{0}", tcmUri);


            page = (IPage)CacheAgent.Load(cacheKey);
            if (page != null)
            {
                return(true);
            }
            string tempPageContent = PageProvider.GetContentByUri(tcmUri);

            if (tempPageContent != string.Empty)
            {
                page = GetIPageObject(tempPageContent);
                if (IncludeLastPublishedDate)
                {
                    ((Page)page).LastPublishedDate = PageProvider.GetLastPublishedDateByUri(tcmUri);
                }

                CacheAgent.Store(cacheKey, CacheRegion, page);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
        public virtual bool TryFindPageContent(string url, out string pageContent)
        {
            LoggerService.Debug(">>TryFindPageContent ({0}", LoggingCategory.Performance, url);

            pageContent = string.Empty;

            string cacheKey = String.Format("PageContent_{0}_{1}", PublicationId, url);

            LoggerService.Debug("about to load page content from cache with key {0}", LoggingCategory.Performance, cacheKey);
            pageContent = (string)CacheAgent.Load(cacheKey);
            LoggerService.Debug("finished loading page content from cache with key {0}, pageContent found {1}", LoggingCategory.Performance, cacheKey, Convert.ToString(!(string.IsNullOrEmpty(pageContent))));
            if (pageContent != null)
            {
                LoggerService.Debug("<<TryFindPageContent ({0}", LoggingCategory.Performance, url);
                return(true);
            }
            else
            {
                LoggerService.Debug("about to load page content from provider with url {0}", LoggingCategory.Performance, url);
                string tempPageContent = PageProvider.GetContentByUrl(url);
                LoggerService.Debug("finished loading page content from provider with url {0}, has value: {1}", LoggingCategory.Performance, url, Convert.ToString(!(string.IsNullOrEmpty(tempPageContent))));
                if (tempPageContent != string.Empty)
                {
                    pageContent = tempPageContent;
                    LoggerService.Debug("about to store page in cache with key {0}", LoggingCategory.Performance, cacheKey);
                    CacheAgent.Store(cacheKey, CacheRegion, pageContent);
                    LoggerService.Debug("finished storing page in cache with key {0}", LoggingCategory.Performance, cacheKey);
                    LoggerService.Debug("<<TryFindPageContent ({0}", LoggingCategory.Performance, url);
                    return(true);
                }
            }

            LoggerService.Debug("<<TryFindPageContent ({0}", LoggingCategory.Performance, url);
            return(false);
        }
        public string ResolveLink(string componentUri)
        {
            string cacheKey = String.Format(CacheKeyFormat, componentUri);
            string link     = (string)CacheAgent.Load(cacheKey);

            if (link != null)
            {
                if (link.Equals(CacheValueNull))
                {
                    return(null);
                }
                return(link);
            }
            else
            {
                ILinkProvider lp = GetLinkProvider(componentUri);
                if (lp == null)
                {
                    return(string.Empty);
                }
                string resolvedUrl = lp.ResolveLink(componentUri);
                if (resolvedUrl == null)
                {
                    //CacheAgent.Store(cacheKey, CacheRegion, CacheValueNull, new List<string>() { String.Format(ComponentFactory.CacheKeyFormatByUri, componentUri) });
                    CacheAgent.Store(cacheKey, CacheRegion, CacheValueNull);
                }
                else
                {
                    //CacheAgent.Store(cacheKey, CacheRegion, resolvedUrl, new List<string>() { String.Format(ComponentFactory.CacheKeyFormatByUri, componentUri) });
                    CacheAgent.Store(cacheKey, CacheRegion, resolvedUrl);
                }
                return(resolvedUrl);
            }
        }
        private SiteMapNode ReadSitemapFromXml(string siteprefix, string sitemapUrl)
        {
            string cachekey = String.Format("SITEMAP_{0}", sitemapUrl);
            object result   = CacheAgent.Load(cachekey);

            if (result != null)
            {
                if (!(result is SiteMapNode) && ((string)result).Equals(CacheNullValue))
                {
                    return(null);
                }
                return(result as SiteMapNode);
            }

            LoggerService.Debug(">>ReadSitemapFromXml", LoggingCategory.Performance);
            SiteMapNode rootNode = null;

            var existingNode = FindSiteMapNodeFromKey("root_" + siteprefix);

            if (existingNode != null)
            {
                RemoveNode(existingNode);
            }

            var nodeDictionary = new Dictionary <string, SiteMapNode>();

            PublicationNodeDictionary[siteprefix] = nodeDictionary;

            string sitemap;

            if (!PageFactory.TryFindPageContent(sitemapUrl, out sitemap))
            {
                sitemap = emptySiteMapString();
            }
            LoggerService.Debug(string.Format("loaded sitemap with url {0}, length {1}", sitemapUrl, sitemap.Length), LoggingCategory.Performance);

            XDocument xDoc = XDocument.Parse(sitemap);

            LoggerService.Debug("parsed sitemap into XDocument", LoggingCategory.Performance);

            XElement siteMapRoot = xDoc.Root;

            rootNode = new NavigationNode(this, "root_" + siteprefix, "root_" + siteprefix, String.Format("/{0}", siteprefix), String.Empty, String.Empty, new ArrayList(), new NameValueCollection(), new NameValueCollection(), String.Empty);
            LoggerService.Debug("created root node", LoggingCategory.Performance);

            //Fill down the hierarchy.

            AddChildren(rootNode, siteMapRoot.Elements("siteMapNode"), 1, nodeDictionary);

            CacheAgent.Store(cachekey, rootNode);

            LoggerService.Debug("<<ReadSitemapFromXml", LoggingCategory.Performance);
            return(rootNode);
        }
Ejemplo n.º 7
0
        public virtual bool TryFindPage(string url, out IPage page)
        {
            LoggerService.Debug(">>TryFindPage ({0}", LoggingCategory.Performance, url);
            page = null;

            string cacheKey = CacheKeyFactory.GenerateKey(CacheRegion, url, Convert.ToString(PublicationId));

            LoggerService.Debug("about to load page from cache with key {0}", LoggingCategory.Performance, cacheKey);
            page = (IPage)CacheAgent.Load(cacheKey);
            LoggerService.Debug("finished loading page from cache with key {0}, page found = {1}", LoggingCategory.Performance, cacheKey, Convert.ToString(page != null));

            if (page != null)
            {
                if (page.Title == CacheValueNullTitle)
                {
                    page = null;
                    return(false);
                }

                LoggerService.Debug("<<TryFindPage ({0}", LoggingCategory.Performance, url);
                return(true);
            }
            else
            {
                LoggerService.Debug("about to load page content from provider with url {0}", LoggingCategory.Performance, url);
                string pageContentFromBroker = PageProvider.GetContentByUrl(url);
                LoggerService.Debug("finished loading page content from provider with url {0}, has value: {1}", LoggingCategory.Performance, url, Convert.ToString(!(string.IsNullOrEmpty(pageContentFromBroker))));

                if (string.IsNullOrEmpty(pageContentFromBroker))
                {
                    CacheAgent.Store(cacheKey, CacheRegion404, CacheValueNull);
                }
                else
                {
                    LoggerService.Debug("about to create IPage from content for url {0}", LoggingCategory.Performance, url);
                    page = GetIPageObject(pageContentFromBroker);
                    if (IncludeLastPublishedDate)
                    {
                        ((Page)page).LastPublishedDate = PageProvider.GetLastPublishedDateByUrl(url);
                    }
                    LoggerService.Debug("finished creating IPage from content for url {0}", LoggingCategory.Performance, url);
                    LoggerService.Debug("about to store page in cache with key {0}", LoggingCategory.Performance, cacheKey);
                    CacheAgent.Store(cacheKey, CacheRegion, page, new List <string> {
                        page.Id
                    });
                    LoggerService.Debug("finished storing page in cache with key {0}", LoggingCategory.Performance, cacheKey);
                    LoggerService.Debug("<<TryFindPage ({0}", LoggingCategory.Performance, url);
                    return(true);
                }
            }

            LoggerService.Debug("<<TryFindPage ({0}", LoggingCategory.Performance, url);
            return(false);
        }
        ///// <summary>
        ///// Get or set the CacheAgent
        ///// </summary>
        //public override ICacheAgent CacheAgent
        //{
        //    get
        //    {
        //        if (_cacheAgent == null)
        //        {
        //            _cacheAgent = new NullCacheAgent();
        //            // the next line is the only reason we are overriding this property: to set a callback
        //            _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack;
        //        }
        //        return _cacheAgent;
        //    }
        //    set
        //    {
        //        _cacheAgent = value;
        //        _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack;
        //    }
        //}



        public bool TryGetComponentPresentation(out IComponentPresentation cp, string componentUri, string templateUri = "")
        {
            cp = null;

            string[] cacheUris = { componentUri };

            if (!String.IsNullOrEmpty(templateUri))
            {
                cacheUris = new string[] { componentUri, templateUri };
            }

            string cacheKey = CacheKeyFactory.GenerateKey(CacheRegion, cacheUris);

            cp = (IComponentPresentation)CacheAgent.Load(cacheKey);

            if (cp != null)
            {
                LoggerService.Debug("<<TryGetComponentPresentation ({0}) - from cache", LoggingCategory.Performance, componentUri);
                return(true);
            }

            string content = !String.IsNullOrEmpty(templateUri) ?
                             ComponentPresentationProvider.GetContent(componentUri, templateUri) :
                             ComponentPresentationProvider.GetContent(componentUri);

            if (string.IsNullOrEmpty(content))
            {
                LoggerService.Debug("<<TryGetComponentPresentationOrComponent - no content found by provider for uris {0} and {1}", LoggingCategory.Performance, componentUri, templateUri);
                return(false);
            }
            LoggerService.Debug("about to create IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri);
            cp = GetIComponentPresentationObject(content);
            LoggerService.Debug("finished creating IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri);

            // if there is no ComponentTemplate, the content of this CP probably represents a component instead of a component PRESENTATION
            // in that case, we should at least add the template uri method parameter (if there is one) to the object
            if (cp.ComponentTemplate == null)
            {
                ((ComponentPresentation)cp).ComponentTemplate = new ComponentTemplate();
            }
            if (cp.ComponentTemplate.Id == null)
            {
                ((ComponentPresentation)cp).ComponentTemplate.Id = templateUri;
            }

            LoggerService.Debug("about to store IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri);
            CacheAgent.Store(cacheKey, CacheRegion, cp, new List <string> {
                cp.Component.Id
            });
            LoggerService.Debug("finished storing IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri);
            LoggerService.Debug("<<TryGetComponentPresentation ({0})", LoggingCategory.Performance, componentUri);

            return(cp != null);
        }
Ejemplo n.º 9
0
        public IBinaryMeta FindBinaryMeta(string url)
        {
            string      cacheKey   = CacheKeyFactory.GenerateKey(url);
            IBinaryMeta binaryMeta = CacheAgent.Load(cacheKey) as IBinaryMeta;

            if (binaryMeta != null)
            {
                return(binaryMeta);
            }
            binaryMeta = BinaryProvider.GetBinaryMetaByUrl(url);
            if (binaryMeta == null) // TODO: cache null result
            {
                return(null);
            }
            CacheAgent.Store(cacheKey, "Binary", binaryMeta, new List <string> {
                binaryMeta.Id
            });
            return(binaryMeta);
        }
Ejemplo n.º 10
0
        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
                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}");

                // in case of error, the binary should be removed from the local file system too
                DeleteFile(physicalPath);
                throw e;
            }
        }
        /// <summary>
        /// Gets the cached local file for a given URL path.
        /// </summary>
        /// <param name="urlPath">The URL path.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(string urlPath, Localization localization)
        {
            string localFilePath = GetFilePathFromUrl(urlPath, localization);

            using (new Tracer(urlPath, localization, localFilePath))
            {
                Dimensions dimensions;
                urlPath = StripDimensions(urlPath, out dimensions);

                string   cacheKey          = GetCacheKey(urlPath);
                DateTime?lastPublishedDate = CacheAgent.Load(cacheKey) as DateTime?;
                if (lastPublishedDate == null)
                {
                    IBinaryFactory binaryFactory = DD4TFactoryCache.GetBinaryFactory(localization);
                    try
                    {
                        DateTime lpb = binaryFactory.FindLastPublishedDate(urlPath);
                        if (lpb != DateTime.MinValue.AddSeconds(1)) // this is the secret code for 'does not exist'
                        {
                            lastPublishedDate = lpb;
                            CacheAgent.Store(cacheKey, "Binary", lastPublishedDate);
                        }
                    }
                    catch (NullReferenceException)
                    {
                        //Binary not found, this should return a min date, but theres a bug in DD4T where it throws a NRE
                        //DO NOTHING - binary removed later
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                        if (File.Exists(localFilePath))
                        {
                            //if theres an error connecting, but we still have a version on disk, serve this
                            return(localFilePath);
                        }
                    }
                }

                if (lastPublishedDate != null)
                {
                    if (File.Exists(localFilePath))
                    {
                        if (localization.LastRefresh.CompareTo(lastPublishedDate) < 0)
                        {
                            //File has been modified since last application start but we don't care
                            Log.Debug("Binary with URL '{0}' is modified, but only since last application restart, so no action required", urlPath);
                            return(localFilePath);
                        }
                        FileInfo fi = new FileInfo(localFilePath);
                        if (fi.Length > 0)
                        {
                            DateTime fileModifiedDate = File.GetLastWriteTime(localFilePath);
                            if (fileModifiedDate.CompareTo(lastPublishedDate) >= 0)
                            {
                                Log.Debug("Binary with URL '{0}' is still up to date, no action required", urlPath);
                                return(localFilePath);
                            }
                        }
                    }
                }

                // 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.
                IBinary binary;
                try
                {
                    IBinaryFactory binaryFactory = DD4TFactoryCache.GetBinaryFactory(localization);
                    binaryFactory.TryFindBinary(urlPath, out binary);
                }
                catch (BinaryNotFoundException)
                {
                    // TryFindBinary throws an Exception if not found ?!
                    binary = null;
                }
                catch (Exception ex)
                {
                    throw new DxaException(string.Format("Error loading binary for URL '{0}'", urlPath), ex);
                }

                //For some reason DD4T sometimes returns a non-null binary with null binary data if it doesnt exist
                if (binary == null || binary.BinaryData == null)
                {
                    // Binary does not exist in Tridion, it should be removed from the local file system too
                    if (File.Exists(localFilePath))
                    {
                        CleanupLocalFile(localFilePath);
                    }
                    throw new DxaItemNotFoundException(urlPath, localization.LocalizationId);
                }

                WriteBinaryToFile(binary, localFilePath, dimensions);
                return(localFilePath);
            }
        }