Ejemplo n.º 1
0
 /// <summary>
 ///     Writes content to file
 /// </summary>
 /// <param name="r"> </param>
 /// <param name="name"> </param>
 /// <param name="content"> </param>
 /// <param name="userLog"> </param>
 /// <param name="append"> </param>
 /// <returns> </returns>
 public static IFileNameResolver Write(this IFileNameResolver r, string name, object content,
                                       IUserLog userLog = null, bool append = false)
 {
     if (r == null)
     {
         throw new ArgumentNullException("r");
     }
     lock (writelock) {
         userLog = checkUserLog(r, userLog);
         userLog.Debug("start write " + name);
         var path = r.Resolve(name, false, null, userLog);
         userLog.Debug("path resolved as " + path);
         Directory.CreateDirectory(Path.GetDirectoryName(path));
         if (append)
         {
             appendFile(path, content);
         }
         else
         {
             rewriteFile(path, content);
         }
         r.ClearCache();
         userLog.Trace("file saved " + path);
         return(r);
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 ///     overload for multiple file resolving to EXISTED FILE URL AND DEFAULT PROBES on current Application by default
 /// </summary>
 /// <param name="resolver"> </param>
 /// <param name="names"> </param>
 /// <param name="existedOnly"> </param>
 /// <param name="probePaths"> </param>
 /// <param name="userLog"> </param>
 /// <returns> </returns>
 public static string ResolveUrl(this IFileNameResolver resolver, string[] names, bool existedOnly = true,
                                 string[] probePaths = null, IUserLog userLog = null)
 {
     if (names == null || names.Length == 0)
     {
         throw new IOException("cannot resolve empty names");
     }
     names = names.Select(x => x.NormalizePath()).ToArray();
     if (probePaths.IsEmptyCollection())
     {
         probePaths = DEFAULT_USRFILE_RESOLVE_PROBE_PATHS;
     }
     else
     {
         if (probePaths != null)
         {
             probePaths = probePaths.Select(x => x.NormalizePath()).ToArray();
         }
     }
     return(resolver.Resolve(new FileSearchQuery
     {
         PathType = FileSearchResultType.FullPath,
         ExistedOnly = existedOnly,
         ProbeFiles = names,
         ProbePaths = probePaths,
         UserLog = userLog
     }));
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Получает имя ресурса
        /// </summary>
        /// <param name="level"></param>
        /// <param name="pathtype"></param>
        /// <returns></returns>
        public string GetFileName(LoadLevel level, FileSearchResultType pathtype = FileSearchResultType.FullPath)
        {
            Resolver = Resolver ?? Application.Current.Files;
            var name = "~/.tmp/load." + level.ToString().ToLower() + ".js";

            return(Resolver.Resolve(name, false, pathtype: pathtype));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Позволяет сформировать файловую структуру из ресурсов сборки
        /// </summary>
        /// <param name="resolver"> резольвер имен файлов </param>
        /// <param name="assembly"> сборка, содержащая ресурсы </param>
        /// <param name="externalizeMap"> мапинк суффиксов имен ресурсов (первый подходящий будет использован) и итоговых имен файлов </param>
        /// <param name="overwriteExisted"> true - файлы будут переписаны даже если они существуют </param>
        /// <param name="throwErrorOnErrorExisted"> ситуация ненахождения ресурса рассматривается как ошибочная (false - пропустить) </param>
        public static void ExternalizeInternalResources(this IFileNameResolver resolver, Assembly assembly,
                                                        IDictionary <string, string> externalizeMap,
                                                        bool overwriteExisted = false, bool throwErrorOnErrorExisted = true)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }
            if (externalizeMap == null)
            {
                throw new ArgumentNullException("externalizeMap");
            }
            if (0 == externalizeMap.Count)
            {
                return;
            }
            var allnames = assembly.GetManifestResourceNames();

            foreach (var map in externalizeMap)
            {
                var resourcename = allnames.FirstOrDefault(x => x.EndsWith(map.Key));
                if (null == resourcename)
                {
                    if (throwErrorOnErrorExisted)
                    {
                        throw new QorpentException("Не найдено ресурса с суффиксом " + map.Key);
                    }
                    continue;
                }
                var outfilename = resolver.Resolve(map.Value, false);
                Directory.CreateDirectory(Path.GetDirectoryName(outfilename));
                if (File.Exists(outfilename))
                {
                    if (!overwriteExisted)
                    {
                        continue;
                    }
                }
                byte[] content = null;
                using (var r = assembly.GetManifestResourceStream(resourcename)) {
                    content = new byte[r.Length];
                    r.Read(content, 0, (int)r.Length);
                }
                File.WriteAllBytes(outfilename, content);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 ///     overload for single file resolving to EXISTED FILE URL AND DEFAULT PROBES on current Application by default
 /// </summary>
 /// <param name="resolver"> </param>
 /// <param name="name"> </param>
 /// <param name="existedOnly"> </param>
 /// <param name="probePaths"> </param>
 /// <param name="userLog"> </param>
 /// <returns> </returns>
 public static string ResolveUrl(this IFileNameResolver resolver, string name, bool existedOnly = true,
                                 string[] probePaths = null, IUserLog userLog = null)
 {
     if (name.IsEmpty())
     {
         throw new IOException("cannot resolve empty names");
     }
     name       = name.NormalizePath();
     probePaths = probePaths ?? new string[] {};
     probePaths = probePaths.IsEmptyCollection()
                                      ? GetDefaultProbesPaths(Path.GetExtension(name))
                                      : probePaths.Select(x => x.NormalizePath()).ToArray();
     return(resolver.Resolve(new FileSearchQuery
     {
         PathType = FileSearchResultType.LocalUrl,
         ExistedOnly = existedOnly,
         ProbeFiles = new[] { name },
         ProbePaths = probePaths,
         UserLog = userLog
     }));
 }
Ejemplo n.º 6
0
 /// <summary>
 ///     overload for single file resolving to EXISTED FILE AND DEFAULT PROBES on current Application by default
 /// </summary>
 /// <param name="resolver"> </param>
 /// <param name="name"> </param>
 /// <param name="existedOnly"> </param>
 /// <param name="probePaths"> </param>
 /// <param name="userLog"> </param>
 /// <param name="pathtype"> </param>
 /// <returns> </returns>
 public static string Resolve(this IFileNameResolver resolver, string name, bool existedOnly = true,
                              string[] probePaths           = null, IUserLog userLog = null,
                              FileSearchResultType pathtype = FileSearchResultType.FullPath)
 {
     if (name.IsEmpty())
     {
         throw new IOException("cannot resolve empty names");
     }
     name = name.NormalizePath();
     if (!name.StartsWith("~") && Path.IsPathRooted(name))
     {
         if (existedOnly)
         {
             if (File.Exists(name))
             {
                 return(name);
             }
             else
             {
                 return(null);
             }
         }
         else
         {
             return(name);
         }
     }
     probePaths = probePaths ?? new string[] {};
     probePaths = probePaths.IsEmptyCollection()
                                      ? GetDefaultProbesPaths(Path.GetExtension(name))
                                      : probePaths.Select(x => NormalizePath(x)).ToArray();
     return(resolver.Resolve(new FileSearchQuery
     {
         PathType = pathtype,
         ExistedOnly = existedOnly,
         ProbeFiles = new[] { name },
         ProbePaths = probePaths,
         UserLog = userLog
     }));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Формирует на диске готовые к загрузке JS файлы
        /// </summary>
        public void Generate(string rootdir = "~/.tmp/", string template = "load.{0}.js")
        {
            ConfigReader    = ConfigReader ?? new LoadConfigReader();
            PackageReader   = PackageReader ?? new LoadPackageReader();
            ScriptGenerator = ScriptGenerator ?? new LoadScriptGenerator();
            Resolver        = Resolver ?? Application.Current.Files;

            var targetdir = Resolver.Resolve(rootdir);

            Directory.CreateDirectory(targetdir);
            var guestfile = Path.Combine(targetdir, string.Format(template, LoadLevel.Guest.ToString().ToLower()));
            var authfile  = Path.Combine(targetdir, string.Format(template, LoadLevel.Auth.ToString().ToLower()));
            var adminfile = Path.Combine(targetdir, string.Format(template, LoadLevel.Admin.ToString().ToLower()));

            var config   = ConfigReader.LoadConfig();
            var packages = PackageReader.Read(config);

            var normalpackages = new LoadPackageSet(packages);

            File.WriteAllText(guestfile, ScriptGenerator.Generate(normalpackages[LoadLevel.Guest]));
            File.WriteAllText(authfile, ScriptGenerator.Generate(normalpackages[LoadLevel.Auth]));
            File.WriteAllText(adminfile, ScriptGenerator.Generate(normalpackages[LoadLevel.Admin]));
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Read content of file
        /// </summary>
        /// <param name="r"> </param>
        /// <param name="name"> </param>
        /// <param name="userLog"> </param>
        /// <typeparam name="T"> </typeparam>
        /// <returns> </returns>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static T Read <T>(this IFileNameResolver r, string name, IUserLog userLog = null)
        {
            if (r == null)
            {
                throw new ArgumentNullException("r");
            }
            if (typeof(T) == typeof(string) || typeof(T) == typeof(XElement) || typeof(T) == typeof(byte[]))
            {
                userLog = checkUserLog(r, userLog);
                userLog.Debug("start write " + name);
                var path = r.Resolve(name, true, null, userLog);

                if (null == path)
                {
                    userLog.Error("file not found");
                    throw new FileNotFoundException(name);
                }
                userLog.Debug("path resolved as " + path);
                object result = default(T);
                if (typeof(T) == typeof(string))
                {
                    result = File.ReadAllText(path);
                }
                else if (typeof(T) == typeof(byte))
                {
                    result = File.ReadAllBytes(path);
                }
                else if (typeof(T) == typeof(XElement))
                {
                    result = XElement.Load(path);
                }
                userLog.Trace("file readed " + path);
                return((T)result);
            }
            throw new ArgumentException("Read method supports only strings, XElement and byte[] as result");
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Получает имя ресурса
 /// </summary>
 /// <param name="level"></param>
 /// <param name="pathtype"></param>
 /// <returns></returns>
 public string GetFileName(LoadLevel level, FileSearchResultType pathtype = FileSearchResultType.FullPath) {
     Resolver = Resolver ?? Application.Current.Files;
     var name = "~/.tmp/load." + level.ToString().ToLower() + ".js";
     return Resolver.Resolve(name, false, pathtype: pathtype);
 }
Ejemplo n.º 10
0
 /// <summary>
 ///     Resolves first file that match query
 /// </summary>
 /// <param name="query"> search query </param>
 /// <returns> </returns>
 public string Resolve(FileSearchQuery query)
 {
     return(Fileresolver.Resolve(query));
 }
Ejemplo n.º 11
0
 /// <summary>
 ///     Получение последней даты записи в директорию
 /// </summary>
 /// <param name="resolver"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static DateTime GetDirectoryLastWriteTime(this IFileNameResolver resolver, string name)
 {
     return(new DirectoryInfo(resolver.Resolve(name)).GetFiles().Select(_ => _.LastWriteTime).Max());
 }