/// <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); } }
private static IBSharpProject DoBuild(IDictionary <string, string> adict, IUserLog log, BSharpBuilder builder, bool errorsafe = false) { var project = SetupProject(adict, log, builder); project.NoOutput = ConsoleMode; try { builder.Log = log; builder.Initialize(project); var resultContext = builder.Build(); if (ConsoleMode) { WriteOutConsoleMode(resultContext); } else { WriteOutErrors(resultContext, log); } } catch (Exception e) { if (errorsafe) { project.Log.Error("Error in cycle " + e, e); return(project); } throw; } return(project); }
/// <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> /// Формирует конфиг из XML /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <param name="machineName"></param> /// <param name="log"></param> public HostConfig(XElement xml,IBSharpContext context = null, string machineName = null, IUserLog log = null) : this() { if (!string.IsNullOrWhiteSpace(machineName)) MachineName = machineName; if (null != log) Log = log; if (null != xml){ LoadXmlConfig(xml,context); } }
//private readonly IRepository<UserLog> logs; public UserLogController() { StandardKernel _kernal = new StandardKernel(); _kernal.Load(Assembly.GetExecutingAssembly()); IUserLog ulog = _kernal.Get <IUserLog>(); this.userlog = ulog; }
public Invoker(Type eventType, IApplication context, IEventHandler[] handlers, object locker, IUserLog userLog) { _hs = handlers; _userLog = userLog; _locker = locker ?? new object(); _context = context; _eventType = eventType; }
/// <summary> /// Вызывается при присоединении расширения к билдеру /// </summary> /// <param name="builder"></param> public void SetUp(IBSharpBuilder builder){ _builder = (BSharpBuilderBase) builder; _tasks = Builder.Tasks; _log = Builder.Log; _project = Builder.GetProject(); WriteSetupStartLog(); RefineProject(); PrepareTasks(); WriteSetupEndLog(); }
/// <summary> /// Вызывается при присоединении расширения к билдеру /// </summary> /// <param name="builder"></param> public void SetUp(IBSharpBuilder builder) { _builder = (BSharpBuilderBase)builder; _tasks = Builder.Tasks; _log = Builder.Log; _project = Builder.GetProject(); WriteSetupStartLog(); RefineProject(); PrepareTasks(); WriteSetupEndLog(); }
/// <summary> /// Removes given event handler /// </summary> /// <typeparam name="TEvent"> </typeparam> /// <param name="handler"> </param> /// <param name="userLog"> </param> public void Remove <TEvent>(IEventHandler <TEvent> handler, IUserLog userLog = null) where TEvent : IEvent { lock (Sync) { if (!_handlers.ContainsKey(typeof(TEvent))) { return; } _handlers[typeof(TEvent)].Remove(handler); Log.Debug("event handler " + handler + " removed from " + typeof(TEvent).Name + " event "); } }
/// <summary> /// register event handler for event class /// </summary> /// <param name="handler"> </param> /// <param name="userLog"> </param> /// <typeparam name="TEvent"> </typeparam> public void Add <TEvent>(IEventHandler <TEvent> handler, IUserLog userLog = null) where TEvent : IEvent { lock (Sync) { if (!_handlers.ContainsKey(typeof(TEvent))) { _handlers[typeof(TEvent)] = new List <IEventHandler>(); } _handlers[typeof(TEvent)].Add(handler); Log.Debug("event handler " + handler + " added for " + typeof(TEvent).Name + " event "); } }
public AccountController( UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, IEmailSender emailSender, ILogger <AccountController> logger, ApplicationDbContext context, IUserLog userLog) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _logger = logger; _userLog = userLog; }
/// <summary> /// Resolves the best posible path. /// </summary> /// <param name="type"> The type. </param> /// <param name="dir"> The dir. </param> /// <param name="file"> The file. </param> /// <param name="userLog"> The UserLog. </param> /// <returns> </returns> /// <remarks> /// </remarks> private string ResolveBestPosiblePath(FileSearchResultType type, string dir, string file, IUserLog userLog) { if (file.StartsWith("~/")) { return(AdaptFilePath(type, Path.Combine(Root, ResolveStandardPath(file.Substring(2))).NormalizePath())); } var path = "/" + dir + "/" + file; var resolved = (Root + path).NormalizePath(); var result = AdaptFilePath(type, resolved); userLog.Debug("resolved to best possible " + result, Application); return(result); }
/// <summary> /// Формирует конфиг из XML /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <param name="machineName"></param> /// <param name="log"></param> public HostConfig(XElement xml, IBSharpContext context = null, string machineName = null, IUserLog log = null) : this() { if (!string.IsNullOrWhiteSpace(machineName)) { MachineName = machineName; } if (null != log) { Log = log; } if (null != xml) { LoadXmlConfig(xml, context); } }
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); }
/// <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> /// Запись форматированного сообщения в лог /// </summary> /// <param name="log">Экземпляр лога</param> /// <param name="level">Уровень логгирования</param> /// <param name="message">Сообщение</param> /// <param name="host">Хост-объект</param> /// <param name="setup">Действие для дополнительной донастройки</param> /// <param name="substitute">Замещение для интерполяции</param> /// <param name="format">Замещение для <see cref="string.Format(string,object)"/></param> public static void Write(this IUserLog log, LogLevel level, string message, object host = null, Action <LogMessage> setup = null, object substitute = null, string[] format = null) { var logMessage = new LogMessage { HostObject = host, Level = level }; var realMessage = message; if (null != substitute) { realMessage = realMessage.Interpolate(substitute); } else if (null != format) { realMessage = string.Format(realMessage, (string[])format); } logMessage.Message = realMessage; if (null != setup) { setup(logMessage); } log.Write(logMessage); }
private static void WriteOutErrors(IBSharpContext resultContext, IUserLog log) { foreach (var e in resultContext.GetErrors()) { var el = LogLevel.Error; if (e.Level == ErrorLevel.Warning) { el = LogLevel.Warn; } else if (e.Level == ErrorLevel.Fatal) { el = LogLevel.Fatal; } else if (e.Level == ErrorLevel.Hint) { el = LogLevel.Info; } var m = e.ToLogString(); log.Write(el, m, e, e); } Thread.Sleep(200); }
/// <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"); }
private static IBSharpProject SingleFileProject(string resolvePath, IDictionary <string, string> adict, IUserLog log, BSharpBuilder builder) { var result = new BSharpProject { IsFullyQualifiedProject = true, Log = log }; result.RootDirectory = Path.GetDirectoryName(resolvePath); result.Targets.Paths[resolvePath] = BSharpBuilderTargetType.Include; if (adict.ContainsKey("cls")) { result.Targets.Classes[adict["cls"]] = BSharpBuilderTargetType.Include; } return(result); }
/// <summary> /// Resolves the best posible path. /// </summary> /// <param name="type"> The type. </param> /// <param name="dir"> The dir. </param> /// <param name="file"> The file. </param> /// <param name="userLog"> The UserLog. </param> /// <returns> </returns> /// <remarks> /// </remarks> private string ResolveBestPosiblePath(FileSearchResultType type, string dir, string file, IUserLog userLog) { if (file.StartsWith("~/")) { return AdaptFilePath(type,Path.Combine(Root, ResolveStandardPath( file.Substring(2))).NormalizePath()); } var path = "/" + dir + "/" + file; var resolved = (Root + path).NormalizePath(); var result = AdaptFilePath(type, resolved); userLog.Debug("resolved to best possible " + result, Application); return result; }
private static void WriteOutErrors(IBSharpContext resultContext, IUserLog log) { foreach (var e in resultContext.GetErrors()) { var el = LogLevel.Error; if (e.Level == ErrorLevel.Warning) { el = LogLevel.Warning; } else if (e.Level == ErrorLevel.Fatal) { el = LogLevel.Fatal; } else if (e.Level == ErrorLevel.Hint) { el = LogLevel.Info; } var m = e.ToLogString(); log.Write(el, m, e, e); } Thread.Sleep(200); }
private static IBSharpProject SetupProject(IDictionary<string, string> adict, IUserLog log, BSharpBuilder builder) { var project = new BSharpProject {IsFullyQualifiedProject = true}; project.IsFullyQualifiedProject = true; if (adict.ContainsKey("project")) { project.ProjectName = adict["project"]; project.IsFullyQualifiedProject = false; }else if (adict.ContainsKey("arg1")) { project.ProjectName = adict["arg1"]; project.IsFullyQualifiedProject = false; } if (!project.OutputAttributes.HasFlag(BSharpBuilderOutputAttributes.IncludeWork)) { if (!adict.ContainsKey("noIncludeWork")) { project.OutputAttributes |= BSharpBuilderOutputAttributes.IncludeWork; } } if (adict.ContainsKey("out-layout")) { project.OutputAttributes = adict["out-layout"].To<BSharpBuilderOutputAttributes>(); } if (adict.ContainsKey("out")) { project.MainOutputDirectory = adict["out"]; } if (adict.ContainsKey("log")) { project.LogOutputDirectory = adict["log"]; } if (adict.ContainsKey("extension")) { project.OutputExtension = adict["extension"]; } if (adict.ContainsKey("root")) { project.RootDirectory = adict["root"]; } if (adict.ContainsKey("dot")) { project.GenerateGraph = adict["dot"].ToBool(); } if (adict.ContainsKey("include")) { project.Targets.Paths.RemoveTarget("*"); var parsed = ParseKeyValueEnumeration(adict["include"], ',', ':'); foreach (var el in parsed) { Console.WriteLine("Include: <" +el.Key+ "," + el.Value+">"); WriteTarget(project, el.Key, el.Value, BSharpBuilderTargetType.Include); } } if (adict.ContainsKey("exclude")) { var parsed = ParseKeyValueEnumeration(adict["exclude"], ',', ':'); foreach (var el in parsed) { Console.WriteLine("Exclude: <" + el.Key + "," + el.Value + ">"); WriteTarget(project, el.Key, el.Value, BSharpBuilderTargetType.Exclude); } } project.Log = log; foreach (var c in adict) { if (c.Key.StartsWith("set-")) { project.Conditions[c.Key.Substring(4)] = c.Value; log.Info("set option " + c.Key.Substring(4) + " = " + c.Value); } } log.Info("root dir = " + project.GetRootDirectory()); log.Info("out dir = " + project.GetOutputDirectory()); log.Info("log dir = " + project.GetLogDirectory()); return project; }
/// <summary> /// Setup UserLog /// </summary> /// <param name="listener"> </param> public void SetLog(IUserLog listener) { _userLog = listener; }
/// <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> /// Запись сообщения об ошибке /// </summary> /// <param name="log">Экземпляр лога</param> /// <param name="message">Сообщение</param> /// <param name="format">Данные для форматированного вывода</param> public static void WriteError(this IUserLog log, string message, params string[] format) { log.Write(LogLevel.Error, message, format: format); }
private static IBSharpProject SetupProject(IDictionary <string, string> adict, IUserLog log, BSharpBuilder builder) { var project = new BSharpProject { IsFullyQualifiedProject = true }; project.IsFullyQualifiedProject = true; var filename = adict.resolvestr("arg1"); if (!string.IsNullOrWhiteSpace(filename) && filename.Contains(".")) { //direct file log.Info("Single file compiled"); project = (BSharpProject)SingleFileProject(EnvironmentInfo.ResolvePath(filename), adict, log, builder); } else { if (adict.ContainsKey("project")) { project.ProjectName = adict["project"]; project.IsFullyQualifiedProject = false; } else if (adict.ContainsKey("arg1")) { project.ProjectName = adict["arg1"]; project.IsFullyQualifiedProject = false; } } if (!project.OutputAttributes.HasFlag(BSharpBuilderOutputAttributes.IncludeWork)) { if (!adict.ContainsKey("noIncludeWork")) { project.OutputAttributes |= BSharpBuilderOutputAttributes.IncludeWork; } } if (adict.ContainsKey("out-layout")) { project.OutputAttributes = adict["out-layout"].To <BSharpBuilderOutputAttributes>(); } if (adict.ContainsKey("compile-extensions")) { project.DoCompileExtensions = adict["compile-extensions"].ToBool(); } if (adict.ContainsKey("out")) { project.MainOutputDirectory = adict["out"]; } if (adict.ContainsKey("log")) { project.LogOutputDirectory = adict["log"]; } if (adict.ContainsKey("extension")) { project.OutputExtension = adict["extension"]; } if (adict.ContainsKey("root")) { project.RootDirectory = adict["root"]; } if (adict.ContainsKey("dot")) { project.GenerateGraph = adict["dot"].ToBool(); } if (adict.ContainsKey("include")) { project.Targets.Paths.RemoveTarget("*"); var parsed = ParseKeyValueEnumeration(adict["include"], ',', ':'); foreach (var el in parsed) { Console.WriteLine("Include: <" + el.Key + "," + el.Value + ">"); WriteTarget(project, el.Key, el.Value, BSharpBuilderTargetType.Include); } } if (adict.ContainsKey("exclude")) { var parsed = ParseKeyValueEnumeration(adict["exclude"], ',', ':'); foreach (var el in parsed) { Console.WriteLine("Exclude: <" + el.Key + "," + el.Value + ">"); WriteTarget(project, el.Key, el.Value, BSharpBuilderTargetType.Exclude); } } project.Log = log; foreach (var c in adict) { if (c.Key.StartsWith("set-")) { project.Conditions[c.Key.Substring(4)] = c.Value; log.Info("set option " + c.Key.Substring(4) + " = " + c.Value); } } log.Info("root dir = " + project.GetRootDirectory()); log.Info("out dir = " + project.GetOutputDirectory()); log.Info("log dir = " + project.GetLogDirectory()); return(project); }