예제 #1
0
        /// <summary>
        /// Read the raw value from file, this method is used by the Metadata Editor
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="path"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static string ReadRawValue(cmSite domain, string path, string lang = null)
        {
            // fix the path to filesystem path
            path = Regex.Replace(path, @"([^\/]\.(\w|\-|_)+)$"
                                 , new MatchEvaluator(delegate(Match m) { string x = m.ToString(); return(x[0].ToString() + "/" + x.Substring(1)); })
                                 , RegexOptions.Compiled | RegexOptions.ECMAScript
                                 );

            string postfix      = string.IsNullOrWhiteSpace(lang) ? string.Empty : "." + lang;
            string physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}{2}", domain.DistinctName, path.TrimStart('/'), postfix)
                );

            if (!File.Exists(physicalPath) && !string.IsNullOrWhiteSpace(domain.TemplateDomainDistinctName))
            {
                physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}{2}", domain.TemplateDomainDistinctName, path.TrimStart('/'), postfix)
                    );
            }
            string rawValue = WinFileIO.ReadWithoutLock(physicalPath);

            if (rawValue != null)
            {
                return(rawValue);
            }
            return(string.Empty);
        }
예제 #2
0
        /// <summary>
        /// Get the metadata entries for special languages
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="path"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static Dictionary <string, string> GetSpecialLanguageEntries(cmSite domain, string path, string lang)
        {
            Dictionary <string, string> entries
                = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            string physicalPath;

            if (!string.IsNullOrWhiteSpace(domain.TemplateDomainDistinctName))
            {
                physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, path.TrimStart('/'))
                    );
                if (Directory.Exists(physicalPath))
                {
                    var files = Directory.EnumerateFiles(physicalPath, ".*", SearchOption.TopDirectoryOnly);
                    foreach (string file in files)
                    {
                        Regex pattern;
                        if (!patterns.TryGetValue(lang, out pattern))
                        {
                            pattern        = new Regex(string.Format(@"^\.(?<name>[^\.]+)\.{0}$", lang.Replace("-", "\\-")), RegexOptions.ECMAScript | RegexOptions.Compiled);
                            patterns[lang] = pattern;
                        }
                        string filename = Path.GetFileName(file);
                        Match  match    = pattern.Match(filename);
                        if (match.Success)
                        {
                            entries[match.Groups["name"].Value] = WinFileIO.ReadWithoutLock(file);
                        }
                    }
                }
            }

            physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}", domain.DistinctName, path.TrimStart('/'))
                );
            if (Directory.Exists(physicalPath))
            {
                var files = Directory.EnumerateFiles(physicalPath, ".*", SearchOption.TopDirectoryOnly);
                foreach (string file in files)
                {
                    Regex pattern;
                    if (!patterns.TryGetValue(lang, out pattern))
                    {
                        pattern        = new Regex(string.Format(@"^\.(?<name>[^\.]+)\.{0}$", lang.Replace("-", "\\-")), RegexOptions.ECMAScript | RegexOptions.Compiled);
                        patterns[lang] = pattern;
                    }
                    string filename = Path.GetFileName(file);
                    Match  match    = pattern.Match(filename);
                    if (match.Success)
                    {
                        entries[match.Groups["name"].Value] = WinFileIO.ReadWithoutLock(file);
                    }
                }
            }

            return(entries);
        }
예제 #3
0
        /// <summary>
        /// Read first available entry in given path
        /// </summary>
        /// <param name="paths"></param>
        /// <returns></returns>
        private static string ReadFirstAvailableEntry(List <string> paths)
        {
            foreach (string path in paths)
            {
                string   physicalPath;
                FileInfo fileInfo;
                try
                {
                    physicalPath = HostingEnvironment.MapPath(path);
                    fileInfo     = new FileInfo(physicalPath);
                    if (!fileInfo.Exists)
                    {
                        continue;
                    }
                }
                catch
                {
                    continue;
                }

                // verify the metadata is not disabled
                try
                {
                    string    propertiesXml = Path.Combine(Path.GetDirectoryName(physicalPath), ".properties.xml");
                    XDocument doc           = PropertyFileHelper.OpenReadWithoutLock(propertiesXml);
                    if (string.Compare(doc.Root.GetElementValue("IsDisabled", "false"), "true", true) == 0)
                    {
                        continue;
                    }
                }
                catch
                {
                }

                // if value is empty, then continue
                if (fileInfo.Length == 0L)
                {
                    continue;
                }
                string ret = WinFileIO.ReadWithoutLock(physicalPath);
                if (!string.IsNullOrWhiteSpace(ret))
                {
                    return(ret);
                }
            }
            return(string.Empty);
        }
예제 #4
0
        private static PreparsedContent GetPreparsedContent(cmSite site, string path)
        {
            string           cacheKey         = string.Format("snippet_{0}_preparsed_{1}", site.DistinctName, path);
            PreparsedContent preparsedContent = HttpRuntime.Cache[cacheKey] as PreparsedContent;

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

            preparsedContent = new PreparsedContent();

            List <string> paths = new List <string>();

            paths.Add(string.Format(CultureInfo.InvariantCulture, "~/Views/{0}/{1}", site.DistinctName, path.TrimStart('/')));
            if (!string.IsNullOrEmpty(site.TemplateDomainDistinctName))
            {
                paths.Add(string.Format(CultureInfo.InvariantCulture, "~/Views/{0}/{1}", site.TemplateDomainDistinctName, path.TrimStart('/')));
            }

            string content = null;

            foreach (string relativePath in paths)
            {
                string physicalPath = HostingEnvironment.MapPath(relativePath);
                preparsedContent.DependedFiles.Add(physicalPath);
                content = WinFileIO.ReadWithoutLock(physicalPath);
                if (content == null)
                {
                    continue;
                }
                break;
            }

            if (!string.IsNullOrEmpty(content))
            {
                // remove comments
                content = Regex.Replace(content
                                        , @"(\<\!\-\-)(.*?)(\-\-\>)"
                                        , string.Empty
                                        , RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline
                                        );
                preparsedContent.Content = content;

                // parse tags
                string currentMetadataPath = Regex.Replace(path
                                                           , @"(\/[^\/]+)$"
                                                           , delegate(Match m) { return(string.Format(CultureInfo.InvariantCulture, "/_{0}", Regex.Replace(m.ToString().TrimStart('/'), @"[^\w\-_]", "_", RegexOptions.Compiled))); }
                                                           , RegexOptions.Compiled);

                MatchCollection matches = Regex.Matches(content
                                                        , @"\[(\s*)metadata(\s*)\:(\s*)(?<method>((htmlencode)|(scriptencode)|(value)))(\s*)\((\s*)(?<path>(\w|\/|\-|\_|\.)+)(\s*)\)(\s*)\]"
                                                        , RegexOptions.Multiline | RegexOptions.ECMAScript | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
                                                        );
                foreach (Match match in matches)
                {
                    PreparsedContentTag tag = new PreparsedContentTag()
                    {
                        StartIndex   = match.Index,
                        Length       = match.Length,
                        Method       = match.Groups["method"].Value.ToLowerInvariant(),
                        MetadataPath = Metadata.ResolvePath(currentMetadataPath, match.Groups["path"].Value)
                    };
                    preparsedContent.Tags.Add(tag);
                }
                preparsedContent.Tags.Sort((a, b) =>
                {
                    if (a.StartIndex > b.StartIndex)
                    {
                        return(1);
                    }
                    else if (a.StartIndex < b.StartIndex)
                    {
                        return(-1);
                    }
                    else
                    {
                        return(0);
                    }
                });
            }

            HttpRuntime.Cache.Insert(cacheKey
                                     , preparsedContent
                                     , new CacheDependencyEx(preparsedContent.DependedFiles.ToArray(), false)
                                     , Cache.NoAbsoluteExpiration
                                     , Cache.NoSlidingExpiration
                                     , CacheItemPriority.NotRemovable
                                     , null
                                     );

            return(preparsedContent);
        }
예제 #5
0
 public string GetFileContent()
 {
     return(WinFileIO.ReadWithoutLock(this.PhysicalPath));
 }
예제 #6
0
        /// <summary>
        /// Write the metadata entry
        /// </summary>
        /// <param name="site"></param>
        /// <param name="path"></param>
        /// <param name="lang">If language is null, then default value is written</param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Save(cmSite site, string path, string lang, string name, string value)
        {
            string postfix      = string.IsNullOrWhiteSpace(lang) ? string.Empty : "." + lang;
            string physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}/.{2}{3}", site.DistinctName, path.TrimStart('/').TrimEnd('/'), name, postfix)
                );

            ContentTree.EnsureDirectoryExistsForFile(site, physicalPath);

            SqlQuery <cmRevision> query = new SqlQuery <cmRevision>();
            string filePath;
            string localFile;
            string metadataPath = path.TrimEnd('/') + "/." + name + postfix;

            if (File.Exists(physicalPath))
            {
                // nothing changed
                if (WinFileIO.ReadWithoutLock(physicalPath) == value)
                {
                    return(false);
                }

                // if last revision not exist, backup first
                {
                    RevisionAccessor ra       = DataAccessor.CreateInstance <RevisionAccessor>();
                    cmRevision       revision = ra.GetLastRevision(site.ID, metadataPath);
                    if (revision == null || !File.Exists(Revisions.GetLocalPath(revision.FilePath)))
                    {
                        localFile = Revisions.GetNewFilePath(out filePath);
                        File.Copy(physicalPath, localFile);

                        revision              = new cmRevision();
                        revision.Comments     = string.Format("No revision found for [{0}], language=[{1}], make a backup.", name, lang.DefaultIfNullOrEmpty("default"));
                        revision.SiteID       = site.ID;
                        revision.FilePath     = filePath;
                        revision.Ins          = DateTime.Now;
                        revision.RelativePath = metadataPath;
                        revision.UserID       = CustomProfile.Current.UserID;
                        query.Insert(revision);
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(site.TemplateDomainDistinctName))
            {
                string inheritedPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}/.{2}{3}", site.TemplateDomainDistinctName, path.TrimStart('/').TrimEnd('/'), name, postfix)
                    );
                if (File.Exists(inheritedPath))
                {
                    // nothing changed
                    if (WinFileIO.ReadWithoutLock(inheritedPath) == value)
                    {
                        return(false);
                    }
                }
                else if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
            }
            else if (string.IsNullOrWhiteSpace(value))
            {
                return(false);
            }

            using (FileStream fs = new FileStream(physicalPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite))
            {
                fs.SetLength(0);
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.Write(value);
                }
            }

            // copy the file to backup
            localFile = Revisions.GetNewFilePath(out filePath);
            File.Copy(physicalPath, localFile);

            // save to cmRevision
            {
                cmRevision revision = new cmRevision();
                revision.Comments     = string.Format("update the entry [{0}], language=[{1}].", name, lang.DefaultIfNullOrEmpty("default"));
                revision.SiteID       = site.ID;
                revision.FilePath     = filePath;
                revision.Ins          = DateTime.Now;
                revision.RelativePath = metadataPath;
                revision.UserID       = CustomProfile.Current.UserID;
                query.Insert(revision);
            }


            return(true);
        }
예제 #7
0
        public static string[] GetChildrenPaths(cmSite domain, string path, bool useCache = true, bool ignoreUKLicense = false)
        {
            string cacheKey = string.Format("metadata_children_{0}_{1}_{2}", domain.ID, path, IsUKLicense);

            string[] paths = HttpRuntime.Cache[cacheKey] as string[];
            if (useCache && paths != null)
            {
                return(paths);
            }

            // sort
            List <string> dependedFiles = new List <string>();
            List <string> priority      = new List <string>();
            {
                string orderList    = null;
                string physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", domain.DistinctName, path.TrimStart('/'))
                    );
                dependedFiles.Add(physicalPath);
                physicalPath = Path.Combine(physicalPath, "_orderlist");
                if (!File.Exists(physicalPath))
                {
                    if (!string.IsNullOrEmpty(domain.TemplateDomainDistinctName))
                    {
                        physicalPath = HostingEnvironment.MapPath(
                            string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, path.TrimStart('/'))
                            );
                        dependedFiles.Add(physicalPath);
                        physicalPath = Path.Combine(physicalPath, "_orderlist");
                    }
                }
                orderList = WinFileIO.ReadWithoutLock(physicalPath);
                if (orderList != null)
                {
                    priority = orderList.Split(',').Where(i => !string.IsNullOrEmpty(i)).ToList();
                }
            }

            Dictionary <string, bool> ret     = GetChildren(domain, path);
            Dictionary <string, bool> tempDic = new Dictionary <string, bool>();

            {
                foreach (var item in priority)
                {
                    string key = string.Format("{0}/{1}", path.TrimEnd('/'), item);
                    if (ret.ContainsKey(key))
                    {
                        tempDic.Add(key, ret[key]);
                        ret.Remove(key);
                    }
                }
            }
            foreach (KeyValuePair <string, bool> item in ret)
            {
                tempDic.Add(item.Key, item.Value);
            }

            DateTime      now             = DateTime.Now;
            DateTime      cacheExpiryTime = now.AddHours(1);
            List <string> temp            = new List <string>();

            {
                foreach (KeyValuePair <string, bool> item in tempDic)
                {
                    DateTime validFrom;
                    DateTime expiryTime;
                    bool     availableForUKLicense;
                    bool     availableForNonUKLicense;

                    string physicalPath = HostingEnvironment.MapPath(
                        string.Format("~/Views/{0}/{1}"
                                      , item.Value ? domain.TemplateDomainDistinctName : domain.DistinctName
                                      , item.Key.TrimStart('/'))
                        );
                    if (IsInherited(physicalPath))
                    {
                        physicalPath = HostingEnvironment.MapPath(string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, item.Key.TrimStart('/')));
                    }

                    Metadata.GetProperties(physicalPath, out validFrom, out expiryTime, out availableForUKLicense, out availableForNonUKLicense);

                    if (ignoreUKLicense ||
                        (IsUKLicense && availableForUKLicense) ||
                        (!IsUKLicense && availableForNonUKLicense))
                    {
                        if (now >= validFrom && now <= expiryTime)
                        {
                            temp.Add(item.Key);
                        }

                        if (cacheExpiryTime > validFrom && validFrom > now)
                        {
                            cacheExpiryTime = validFrom;
                        }

                        if (cacheExpiryTime > expiryTime && expiryTime > now)
                        {
                            cacheExpiryTime = expiryTime;
                        }
                    }
                }
            }

            HttpRuntime.Cache.Insert(cacheKey
                                     , temp.ToArray()
                                     , new CacheDependencyEx(dependedFiles.ToArray(), false)
                                     , cacheExpiryTime//, DateTime.Now.AddHours(1)
                                     , Cache.NoSlidingExpiration
                                     , CacheItemPriority.NotRemovable
                                     , null
                                     );

            return(temp.ToArray());
        }
예제 #8
0
        private static string GetFileContent(string appRelativeVirtualPath, string path)
        {
            try
            {
                appRelativeVirtualPath = VirtualPathUtility.GetDirectory(appRelativeVirtualPath.TrimStart('~'));

                Match match = pathRegex.Match(appRelativeVirtualPath);
                if (match.Success)
                {
                    appRelativeVirtualPath = match.Groups["path"].Value;
                }

                if (!path.StartsWith("/"))
                {
                    path = VirtualPathUtility.Combine(appRelativeVirtualPath, path);
                }


                cmSite site      = SiteManager.Current;
                string cachePath = string.Format("ContentHelper.GetFileContent.{0}.{1}"
                                                 , site.DistinctName
                                                 , path
                                                 );

                string content = HttpRuntime.Cache[cachePath] as string;
                if (content != null)
                {
                    return(content);
                }

                List <string> dependedFiles = new List <string>();

                string filePath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", site.DistinctName, (path ?? string.Empty).TrimStart('/'))
                    );
                dependedFiles.Add(filePath);
                content = WinFileIO.ReadWithoutLock(filePath);
                if ((content == null) && (!string.IsNullOrWhiteSpace(site.TemplateDomainDistinctName)))
                {
                    filePath = HostingEnvironment.MapPath(
                        string.Format("~/Views/{0}/{1}", site.TemplateDomainDistinctName, (path ?? string.Empty).TrimStart('/'))
                        );
                    dependedFiles.Add(filePath);
                    content = WinFileIO.ReadWithoutLock(filePath);
                }

                if (content == null)
                {
                    content = string.Empty;
                }

                HttpRuntime.Cache.Insert(cachePath
                                         , content
                                         , new CacheDependencyEx(dependedFiles.ToArray(), false)
                                         , Cache.NoAbsoluteExpiration
                                         , Cache.NoSlidingExpiration
                                         );
                return(content);
            }
            catch
            {
                return(string.Empty);
            }
        }