/// <summary> /// Extract resources to given path /// </summary> /// <param name="resolver"> </param> /// <param name="mask"> </param> /// <param name="assembly"> </param> /// <param name="outdir"> </param> /// <param name="cleanupnamepattern"> </param> /// <param name="userLog"> </param> public static void Externalize(this IFileNameResolver resolver, string mask, Assembly assembly = null, string outdir = "~/tmp/_internal", string cleanupnamepattern = @"^(?i)[\s\S]+?\.resources\.", IUserLog userLog = null) { lock (writelock) { if (mask.IsEmpty()) { mask = "."; } assembly = assembly ?? Assembly.GetCallingAssembly(); outdir = outdir ?? "~/tmp/_internal"; cleanupnamepattern = cleanupnamepattern ?? @"^(?i)[\s\S]+?\.resources\."; var maskregex = new Regex(mask, RegexOptions.Compiled); var cleanupregex = new Regex(cleanupnamepattern, RegexOptions.Compiled); var resourcenames = assembly.GetManifestResourceNames().Where(x => maskregex.IsMatch(x)).ToArray(); foreach (var resourcename in resourcenames) { using (var sr = new StreamReader(assembly.GetManifestResourceStream(resourcename))) { var name = cleanupregex.Replace(resourcename, "").Replace("___", ".").Replace("__", "/"); //psuedo folder support for embeded resources and avoid for limitation of CS embeded resources var path = outdir + "/" + name; var fullpath = (resolver).Resolve(path, false, userLog: userLog); var dirpath = Path.GetDirectoryName(fullpath); Directory.CreateDirectory(dirpath); var content = sr.ReadToEnd(); File.WriteAllText(fullpath, content); } } } }
/// <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); } }
/// <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)); }
/// <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 })); }
/// <summary> /// Повторяет поведение ResolveAll из старого ядра /// </summary> /// <param name="resolver"></param> /// <param name="rootdir"></param> /// <param name="mask"></param> /// <param name="existedOnly"></param> /// <returns></returns> public static string[] ResolveAll(this IFileNameResolver resolver, string rootdir, string mask, bool existedOnly) { return (resolver.ResolveAll(new FileSearchQuery { All = true, ExistedOnly = existedOnly, PathType = FileSearchResultType.FullPath, ProbeFiles = new[] { mask }, ProbePaths = new[] { rootdir } })); }
/// <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); } }
private static IUserLog checkUserLog(IFileNameResolver r, IUserLog userLog) { if (null == userLog) { if (r is ILogBound) { userLog = ((ILogBound)r).Log; } if (null == userLog) { userLog = Application.Current.LogManager.GetLog(typeof(FileNameResolverExtensions).FullName, typeof(FileNameResolverExtensions)); } } return(userLog); }
public ThemaFactory( IThemaLoader loader = null, IRoleResolver roleresolver = null, IFileNameResolver fileresolver = null, ITypeLocator locator = null, IEntityResolver entityResolver = null, ILogListener log = null, IPeriodProvider periodprovider = null) { Themas = new ThemaCollection {Factory = this}; RoleResolver = roleresolver ?? QWebServiceRegistry.Default.RoleResolver; FileResolver = fileresolver ?? QWebServiceRegistry.Default.FileNameResolver; TypeLocator = locator ?? QWebServiceRegistry.Default.TypeLocator; PeriodProvider = periodprovider ?? TypeLocator.Get<IPeriodProvider>().create<IPeriodProvider>(); EntityResolver = entityResolver ?? TypeLocator.Get<IEntityResolver>().create<IEntityResolver>(); Sources = new List<IThemaSource>(); Log = log ?? QWebServiceRegistry.Default.Log; Loader = loader ?? new Loader(this); }
/// <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 })); }
/// <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 })); }
/// <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])); }
/// <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"); }
public WebResourceLocator(HttpContext context, IResourceCompressor compressor) { this.context = context; this.compressor = compressor; resolver = FileNameResolver.GetResolver(); }
/// <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); }
/// <summary> /// Асинхронно форсирует компиляцию скриптов /// </summary> public void Compile() { Resolver = Resolver ?? Application.Current.Files; CompileTask = Task.Run((Action) CompileWorker); }
public RemoteResourceProvider(HttpContext context, IFileNameResolver resolver) { this.context = context; this.resolver = resolver; }
/// <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()); }
IDataSetConfigBuilder <TDb, TKey, TEntity> .UseCustomNameResolver (IFileNameResolver <TKey> resolver) { _dataSetConfig.NameResolver = resolver; return(this); }
public LocalFileProvider(HttpContext context, IFileNameResolver resolver, string defaultPath) { this.context = context; this.resolver = resolver; this.defaultPath = defaultPath; }
/// <summary> /// Асинхронно форсирует компиляцию скриптов /// </summary> public void Compile() { Resolver = Resolver ?? Application.Current.Files; CompileTask = Task.Run((Action)CompileWorker); }