public TestReportService(IDatabaseProvider dbProvider, ILogger logger = null) { DatabaseProvider = dbProvider; logger = logger ?? Log.Default; TestReportingRepository repo = new TestReportingRepository(); DatabaseProvider.SetDatabases(repo); repo.SchemaWarning += (s, e) => { logger.AddEntry("SchemaWarning: {0}", LogEventType.Warning, e.TryPropertiesToString()); }; repo.CreateFailed += (s, e) => { logger.AddEntry("CreateFailed: {0}", LogEventType.Error, e.TryPropertiesToString()); }; repo.RetrieveFailed += (s, e) => { logger.AddEntry("RetrieveFailed: {0}", LogEventType.Error, e.TryPropertiesToString()); }; repo.UpdateFailed += (s, e) => { logger.AddEntry("UpdateFailed: {0}", LogEventType.Error, e.TryPropertiesToString()); }; Logger = logger; Repository = repo; }
public void End(Database db = null, ILogger logger = null) // TODO: Write unit test { try { if (logger == null) { logger = Log.Default; } User user = UserOfUserId; if (user == null) { user = User.Anonymous; } logger.AddEntry("Ending session ({0}) for user ({1})", this.Id.ToString(), user.UserName); Identifier = Identifier + "-Ended"; IsActive = false; Save(db); } catch (Exception ex) { logger.AddEntry("Exception occurred ending session ({0})", ex, this.Id.ToString()); } }
public void Start(bool usurped, params HostPrefix[] hostPrefixes) { if (hostPrefixes.Length == 0) { hostPrefixes = HostPrefixes; } lock (_startLock) { hostPrefixes.Each(hp => { if (!_listening.ContainsKey(hp)) { AddHostPrefix(hp); } else if (usurped && _listening.ContainsKey(hp)) { _listening[hp].Stop(); _listening.TryRemove(hp, out HttpServer ignore); AddHostPrefix(hp); } else { _logger.AddEntry("HttpServer: Another HttpServer is already listening for host {0}", LogEventType.Warning, hp.ToString()); } }); _listener.Start(); _handlerThread.Start(); } }
public void ImportModel(string path, SetSymbol returnSym) { if (!File.Exists(path)) { throw new QueryException("File not found: " + path); } if (true) //geo off { Console.WriteLine("ImportModel'ing... side effects->"); Console.WriteLine("\tGenerating geometry..."); //ifcEngineTiming, meshingTiming, meshes.Count var importTiming = ifcReader.LoadIfc(path); logger.AddEntry("ImportModelGeo", 0, (int)importTiming[2], importTiming[0]); logger.AddEntry("ImportModelRsTree", 0, (int)importTiming[2], importTiming[1]); Console.WriteLine("\t" + importTiming[2] + " geometry representations created."); } Console.WriteLine("\tGenerating semantic representations..."); var qlEntities = p21Reader.LoadIfcFile(path); //add to global dictionary foreach (var entity in qlEntities) { interpreterRepository.GlobalEntityDictionary.Add(entity.Id, entity); } Console.WriteLine("\t" + qlEntities.Length + " object representations created."); Console.WriteLine("ImportModel'ing finished."); returnSym.EntityDic = qlEntities.ToDictionary(e => e.Id); }
public static string CompileDirectory(DirectoryInfo directory, string fileSearchPattern = "*.dust", SearchOption searchOption = SearchOption.TopDirectoryOnly, string templateNamePrefix = "", ILogger logger = null) { StringBuilder compiled = new StringBuilder(); logger = logger ?? Log.Default; if (directory.Exists) { logger.AddEntry("DustScript::Compiling Dust Directory: {0}", directory.FullName); FileInfo[] files = directory.GetFiles(fileSearchPattern, searchOption); foreach (FileInfo file in files) { string templateName = Path.GetFileNameWithoutExtension(file.Name); if (searchOption == SearchOption.AllDirectories) { if (file.Directory.FullName.Replace("\\", "/") != directory.FullName.Replace("\\", "/")) { string prefix = file.Directory.FullName.TruncateFront(directory.FullName.Length + 1).Replace("\\", "_") + "_"; templateName = prefix + templateName; } } string templateFullName = templateNamePrefix + templateName; logger.AddEntry("DustScript::Starting Dust compile: fileName={0}, templateName={1}", file.FullName, templateFullName); compiled.Append(";\r\n"); compiled.Append(new CompiledDustTemplate(file.FullName, templateFullName)); compiled.Append(";\r\n"); logger.AddEntry("DustScript::Finished Dust compile: fileName={0}, templateName={1}", file.FullName, templateFullName); } } return(compiled.ToString()); }
protected static void WireResponseLogging(IResponder responder, ILogger logger) { responder.Responded += (r, context) => { logger.AddEntry("*** ({0}) Responded ***\r\n{1}", LogEventType.Information, responder.Name, context.Request.PropertiesToString()); }; responder.NotResponded += (r, context) => { logger.AddEntry("*** Didn't Respond ***\r\n{0}", LogEventType.Warning, context.Request.PropertiesToString()); }; }
public virtual void Subscribe(ILogger logger) { lock (_subscriberLock) { if (logger != null && !IsSubscribed(logger)) { _subscribers.Add(logger); Type currentType = this.GetType(); EventInfo[] eventInfos = currentType.GetEvents(); eventInfos.Each(eventInfo => { bool shouldSubscribe = true; VerbosityLevel logEventType = VerbosityLevel.Information; if (eventInfo.HasCustomAttributeOfType(out VerbosityAttribute verbosity)) { shouldSubscribe = (int)verbosity.Value <= (int)LogVerbosity; logEventType = verbosity.Value; } if (shouldSubscribe) { if (eventInfo.EventHandlerType.Equals(typeof(EventHandler))) { eventInfo.AddEventHandler(this, (EventHandler)((s, a) => { string message = ""; if (verbosity != null) { if (!verbosity.TryGetMessage(s, out message)) { verbosity.TryGetMessage(a, out message); } } if (!string.IsNullOrEmpty(message)) { logger.AddEntry(message, (int)logEventType); } else { logger.AddEntry("Event {0} raised on type {1}::{2}", (int)logEventType, logEventType.ToString(), currentType.Name, eventInfo.Name); } })); } } }); } } }
/// <summary> /// Loads the specified logger. /// </summary> /// <param name="logger">The logger.</param> /// <returns></returns> public async Task <bool> Load(ILogger logger = null) { try { if (File.Exists) { logger = logger ?? Log.Default; await Task.Run(() => GetText()); await Task.Run(() => ContentHash = File.ContentHash(HashAlgorithms.MD5)); await Task.Run(() => GetZippedText()); await Task.Run(() => GetZippedBytes()); return(true); } return(false); } catch (Exception ex) { logger.AddEntry("Error loading file {0}: {1}", ex, File?.FullName ?? "<null>", ex.Message); return(false); } }
/// <summary> /// Bind the BamServerEventListener implementations defined in BamConf /// to the server events /// </summary> public void Bind() { ILogger logger = Logger; Type serverType = typeof(BamServer); BamServerEventListener[] listeners = BamConf.GetServerEventListeners(logger); listeners.Each(listener => { Type listenerType = listener.GetType(); listenerType.GetMethodsWithAttributeOfType <ServerEventListenerAttribute>().Each(method => { ServerEventListenerAttribute attr = method.GetCustomAttributeOfType <ServerEventListenerAttribute>(); string eventName = attr.EventName.Or(method.Name); EventInfo eventInfo = serverType.GetEvent(eventName); if (eventInfo != null) { eventInfo.AddEventHandler(Server, Delegate.CreateDelegate(listenerType, method)); } else { logger.AddEntry("{0}::The specified event name ({1}) was not found on type ({2})", LogEventType.Warning, listener.GetType().Name, method.Name, serverType.Name); } }); }); }
/// <summary> /// Execute the methods on the specified instance that are addorned with ConsoleAction /// attributes that have CommandLineSwitch(es) defined that match keys in the /// specified ParsedArguments using the specified ILogger to report any switches not /// found. An ExpectFailedException will be thrown if more than one method is found /// with a matching CommandLineSwitch defined in ConsoleAction attributes /// </summary> /// <param name="arguments"></param> /// <param name="type"></param> /// <param name="warnForNotFoundSwitches"></param> /// <param name="instance"></param> /// <param name="logger"></param> /// <returns>true if command line switches were executed otherwise false</returns> public static bool ExecuteSwitches(ParsedArguments arguments, Type type, bool warnForNotFoundSwitches = true, object instance = null, ILogger logger = null) { bool executed = false; foreach (string key in arguments.Keys) { ConsoleMethod methodToInvoke = GetConsoleMethod(arguments, type, key, instance); if (methodToInvoke != null) { if (IsolateMethodCalls) { methodToInvoke.InvokeInSeparateAppDomain(); } else { methodToInvoke.InvokeInCurrentAppDomain(); } executed = true; logger?.AddEntry("Executed {0}: {1}", key, methodToInvoke.Information); } else { if (logger != null && warnForNotFoundSwitches) { logger.AddEntry("Specified command line switch was not found {0}", LogEventType.Warning, key); } } } return(executed); }
private void Worker() { WaitHandle[] wait = new[] { _ready, _stop }; while (0 == WaitHandle.WaitAny(wait)) { TcpClient client; lock (_queue) { if (_queue.Count > 0) { client = _queue.Dequeue(); } else { _ready.Reset(); continue; } } try { ReadRequest(client); } catch (Exception ex) { _logger.AddEntry("An error occurred processing TCP request: {0}", ex, ex.Message); OnException(ex); } } }
public virtual EnsureSchemaStatus TryEnsureSchema(Type type, bool force, out Exception ex, ILogger logger = null) { EnsureSchemaStatus result = EnsureSchemaStatus.Invalid; ex = null; try { string schemaName = Dao.RealConnectionName(type); if (!SchemaNames.Contains(schemaName) || force) { _schemaNames.Add(schemaName); SchemaWriter schema = ServiceProvider.Get <SchemaWriter>(); schema.WriteSchemaScript(type); ExecuteSql(schema, ServiceProvider.Get <IParameterBuilder>()); result = EnsureSchemaStatus.Success; } else { result = EnsureSchemaStatus.AlreadyDone; } } catch (Exception e) { ex = e; result = EnsureSchemaStatus.Error; logger = logger ?? Log.Default; logger.AddEntry("Non fatal error occurred trying to write schema for type {0}: {1}", LogEventType.Warning, ex, type.Name, ex.Message); } return(result); }
public Type[] Load(ILogger logger = null) { logger = logger ?? Log.Default; List <Type> results = new List <Type>(); Paths.Each(path => { if (Directory.Exists(path)) { DirectoryInfo dir = new DirectoryInfo(path); FileInfo[] files = dir.GetFiles(AssemblySearchPatterns.DelimitSplit(",", "|")); files.Each(file => { try { Assembly assembly = Assembly.LoadFrom(file.FullName); if (SearchClassNames) { results.AddRange(SearchAssembly(assembly)); } else { results.AddRange(GetTypes(assembly, logger)); } } catch (Exception ex) { logger.AddEntry("An exception occurred loading file {0}: {1}", ex, file.FullName, ex.Message); } }); } }); return(results.ToArray()); }
public bool Initialize(ILogger logger, out Exception ex) { bool success = false; ex = null; try { Assembly assembly; Type context; if (!string.IsNullOrEmpty(SchemaAssemblyPath)) { assembly = Assembly.LoadFrom(SchemaAssemblyPath); context = assembly.GetType(SchemaContext); if (context == null) { context = assembly.GetTypes().Where(t => t.AssemblyQualifiedName.Equals(SchemaContext)).FirstOrDefault(); } } else { context = Type.GetType(SchemaContext); } Args.ThrowIf <ArgumentException>(context == null, "The specified SchemaContext ({0}) was not found", SchemaContext); PropertyInfo prop = context.GetProperty("ConnectionName"); Args.ThrowIf <ArgumentException>(prop == null, "{0}.ConnectionName property was not found, make sure you're using the latest Bam.Net.Data.Schema.dll", context.Name); SchemaName = (string)prop.GetValue(null); RegistrarCallerFactory registrarFactory = new RegistrarCallerFactory(); IRegistrarCaller registrarCaller = registrarFactory.CreateRegistrarCaller(RegistrarCaller); Args.ThrowIf <ArgumentException>(registrarCaller == null, "Unable to instanciate IRegistrarCaller of type ({0})", RegistrarCaller); registrarCaller.Register(SchemaName); Exception ensureSchemaException; if (!Db.TryEnsureSchema(SchemaName, out ensureSchemaException)) { string properties = this.PropertiesToString("\r\n\t"); logger.AddEntry("A non fatal error occurred initializing schema ({0}) from ({1}): {2}\r\n{3}", LogEventType.Warning, SchemaName, SchemaContext, ensureSchemaException.Message, properties ); } success = true; } catch (Exception e) { ex = e; success = false; } return(success); }
public T GetProxy <T>(string hostName, int port, ILogger logger = null) { logger = logger ?? Log.Default; T proxy = GetProxy <T>(hostName, port, new HashSet <Assembly>()); SubscribeToInvocationExceptions(proxy, (o, a) => logger.AddEntry("Proxy Invocation Failed:(Cuid={0}):Remote={1}:{2}.{3}: {4}", a.Exception, a.Cuid, a.BaseAddress, a.ClassName, a.MethodName, a.Message)); return(proxy); }
/// <summary> /// Launches the game. /// </summary> public void Launch() { var gameArgs = GetGameArguments(); Process game = new Process(); game.StartInfo.WorkingDirectory = gameArgs.AppPath; game.StartInfo.FileName = gameArgs.AppExe; game.StartInfo.Arguments = GetLaunchArguments(gameArgs); game.StartInfo.Verb = "runas"; logger.AddEntry(new LogEntry(Environment.UserName, String.Format("Trying to launch game with: WDir: {0}; File: {1} {2}", gameArgs.AppPath, game.StartInfo.FileName, game.StartInfo.Arguments), LogEntryType.Information)); game.Start(); logger.AddEntry(new LogEntry(Environment.UserName, String.Format("Succesfully launched game with: WDir: {0}; File: {1} {2}", gameArgs.AppPath, game.StartInfo.FileName, game.StartInfo.Arguments), LogEntryType.Information)); }
public Language DetectLanguage(string text) { var args = new { ApiKey = ApiKey.Or("demo"), Text = text }; string json = Http.Get(ApiDetectEndpointFormat.NamedFormat(args)); Task.Run(() => Logger.AddEntry("DetectLanguageResponse: {0}", json)); DetectLanguageResponse response = json.FromJson <DetectLanguageResponse>(); return(response.GetLanguage(LanguageDatabase)); }
public static DaemonProcessMonitor Start(DaemonProcess process, ILogger logger = null) { logger = logger ?? Log.Default; logger.AddEntry("Monitoring {0}", process.Name); DaemonProcessMonitor result = new DaemonProcessMonitor(process, logger); process.StandardOut += (o, a) => logger.Info(((DaemonProcessEventArgs)a).Message); process.ErrorOut += (o, a) => logger.Warning(((DaemonProcessEventArgs)a).Message); process.Start(result.TryRestart); return(result); }
private Type[] GetTypes(Assembly assembly, ILogger logger = null) { logger = logger ?? Log.Default; List <Type> results = new List <Type>(); TypesToLoad.Each(typeName => { Type type = assembly.GetType(typeName); if (type != null) { results.Add(type); logger.AddEntry("Type FOUND: Type = {0}, Assembly = {1}", typeName, assembly.FullName); } else { logger.AddEntry("Type NOT found: Type = {0}, Assembly = {1}", LogEventType.Warning, typeName, assembly.FullName); } }); return(results.ToArray()); }
private static void SafeLog(this ILogger log, LogEntryType type, string message) { try { log.AddEntry(message, type); } catch { // If we can't log, we're a bit screwed. } }
public void Subscribe(ILogger logger) { if (!IsSubscribed(logger)) { this.Logger = logger; lock (_subscriberLock) { _subscribers.Add(logger); } string className = typeof(ServiceProxyResponder).Name; Initialized += (sp) => { logger.AddEntry("{0}::Initializ(ED)", className); }; Initializing += (sp) => { logger.AddEntry("{0}::Initializ(ING)", className); }; } }
public static void Monitor(ILogger logger = null) { logger = logger ?? Log.Default; AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { if (!_names.Contains(args.Name)) { _names.Add(args.Name); logger.AddEntry("Assembly {0}\r\nAt {1}\r\nRequested {2}\r\n\t, but it was not found", LogEventType.Warning, args.RequestingAssembly?.FullName, args.RequestingAssembly?.GetFileInfo().FullName, args.Name); } return(null); }; }
private Type[] SearchAssembly(Assembly assembly, ILogger logger = null) { logger = logger ?? Log.Default; List <string> typesToLoad = new List <string>(TypesToLoad); Type[] types = assembly.GetTypes().Where(t => typesToLoad.Contains(t.AssemblyQualifiedName) || typesToLoad.Contains(t.Name) || typesToLoad.Contains(t.FullName) ).ToArray(); logger.AddEntry("Specified {0} types to load; Found {1}", TypesToLoad.Length.ToString(), types.Length.ToString()); return(types); }
protected internal BamServerEventListener[] GetServerEventListeners(ILogger logger = null) { logger = logger ?? Log.Default; ReflectionLoader loader = new ReflectionLoader { AssemblySearchPatterns = ServerEventListenerAssemblySearchPattern, Paths = ServerEventListenerSearchPath.DelimitSplit(",", "|"), SearchClassNames = true, TypesToLoad = ServerEventListenerNames }; List <BamServerEventListener> listeners = new List <BamServerEventListener>(); loader.Load(logger).Each(t => { if (t.IsSubclassOf(typeof(BamServerEventListener))) { listeners.Add(t.Construct <BamServerEventListener>()); logger.AddEntry("Found {0}: Type = {1}, Assembly = {2}", typeof(BamServerEventListener).Name, t.FullName, t.Assembly.FullName); } else { logger.AddEntry("{0} specified does not extend BamServerEventListener: Type = {1}, Assembly = {2}", typeof(BamServerEventListener).Name, t.FullName, t.Assembly.FullName); } }); return(listeners.ToArray()); }
/// <summary> /// Compiles all the dust templates in the specified directory returning the combined /// result as a string and each individual template in a list as an out parameter. /// </summary> /// <param name="directory"></param> /// <param name="templates"></param> /// <param name="fileSearchPattern"></param> /// <param name="searchOption"></param> /// <param name="templateNamePrefix"></param> /// <param name="logger"></param> /// <returns></returns> public static string CompileTemplates(this DirectoryInfo directory, out List <ICompiledTemplate> templates, string fileSearchPattern = "*.dust", SearchOption searchOption = SearchOption.TopDirectoryOnly, string templateNamePrefix = "", ILogger logger = null) { StringBuilder compiled = new StringBuilder(); logger = logger ?? Log.Default; templates = new List <ICompiledTemplate>(); if (directory.Exists) { logger.AddEntry("DustScript::Compiling Dust Directory: {0}", directory.FullName); FileInfo[] files = directory.GetFiles(fileSearchPattern, searchOption); foreach (FileInfo file in files) { string templateName = Path.GetFileNameWithoutExtension(file.Name); if (searchOption == SearchOption.AllDirectories) { if (file.Directory.FullName.Replace("\\", "/") != directory.FullName.Replace("\\", "/")) { string prefix = file.Directory.FullName.TruncateFront(directory.FullName.Length + 1).Replace("\\", "_") + "_"; templateName = prefix + templateName; } } string templateFullName = templateNamePrefix + templateName; ICompiledTemplate template = new CompiledDustTemplate(file.FullName, templateFullName); logger.AddEntry("DustScript::Starting Dust compile: fileName={0}, templateName={1}", file.FullName, templateFullName); compiled.Append(";\r\n"); // TODO: do Regex.Unescape(tempalte.Compiled) to prevent having to do it everywhere else that references the resulting "compiled.ToString()" // such as below in Render. Do it here and it shouldn't be necessary anywhere else. compiled.Append(template.Compiled); compiled.Append(";\r\n"); logger.AddEntry("DustScript::Finished Dust compile: fileName={0}, templateName={1}", file.FullName, templateFullName); templates.Add(template); } } return(compiled.ToString()); }
private static void LogAndThrow(Exception ex, ILogger logger) { logger = logger ?? Log.Default; string message = ex.Message; string innerMessage = "NA"; string signature = "ExceptionMessage::{0}::InnerExceptionMessage::{1}"; Exception e = ex; if (ex.InnerException != null) { e = ex.InnerException; innerMessage = ex.InnerException.Message; } logger.AddEntry(signature, e, message, innerMessage); }
public static Database InitializeVaultDatabase(string filePath, ILogger logger = null) { Database db = null; VaultDatabaseInitializer initializer = new VaultDatabaseInitializer(filePath); DatabaseInitializationResult result = initializer.Initialize(); if (!result.Success) { logger.AddEntry(result.Exception.Message, result.Exception); } db = result.Database; return(db); }
public static void Monitor(ILogger logger = null) { logger = logger ?? Log.Default; AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { if (!_names.Contains(args.Name)) { _names.Add(args.Name); string messageFormat = @"AppDomain.CurrentDomain.AssemblyResolve event fired and assembly was not found: tRequesting Assembly: {0} tRequesting Assembly Location: {1} tRequested Assembly: {2} tEvent sender: {3}"; logger.AddEntry(messageFormat, LogEventType.Warning, args.RequestingAssembly?.FullName.Or("[null]"), args.RequestingAssembly?.GetFileInfo().FullName.Or("[null]"), args.Name.Or("[null]"), sender?.ToString().Or("[null]")); } return(null); }; }
public void Subscribe(ILogger logger) { if (!IsSubscribed(logger)) { lock (_subscriberLock) { _subscribers.Add(logger); } string className = this.GetType().Name;//typeof(TemplateInitializerBase).Name; Initializing += (ti) => { logger.AddEntry("{0}::Initializ(ING)", className); }; Initialized += (ti) => { logger.AddEntry("{0}::Initialz(ED)", className); }; InitializingAppDaoTemplates += (appName, daoReg) => { logger.AddEntry("{0}::Initializ(ING) App[{1}] Templates for ({2})", className, appName, daoReg.ContextName); }; InitializedAppDaoTemplates += (appName, daoReg) => { logger.AddEntry("{0}::Initializ(ED) App[{1}] Templates for ({2})", className, appName, daoReg.ContextName); }; InitializingCommonDaoTemplates += (daoReg) => { logger.AddEntry("{0}::Initializ(ING) Common Templates for ({1})", className, daoReg.ContextName); }; InitializedCommonDaoTemplates += (daoReg) => { logger.AddEntry("{0}::Initializ(ED) Common Templates for ({1})", className, daoReg.ContextName); }; InitializationException += (ex) => { logger.AddEntry("{0}::Initialization EXCEPTION: {1}", LogEventType.Warning, className, ex.Message); }; } }
public override void Subscribe(ILogger logger) { if (!IsSubscribed(logger)) { base.Subscribe(logger); string className = typeof(ContentResponder).Name; this.AppContentRespondersInitializing += (c) => { logger.AddEntry("{0}::AppContentRespondersInitializ(ING)", className); }; this.AppContentRespondersInitialized += (c) => { logger.AddEntry("{0}::AppContentRespondersInitializ(ED)", className); }; this.AppContentResponderInitializing += (c, a) => { logger.AddEntry("{0}::AppContentResponderInitializ(ING):{1}", className, a.Name); }; this.AppContentResponderInitialized += (c, a) => { logger.AddEntry("{0}::AppContentResponderInitializ(ED):{1}", className, a.Name); }; this.Initializing += (c) => { logger.AddEntry("{0}::Initializ(ING)", className); }; this.Initialized += (c) => { logger.AddEntry("{0}::Initializ(ED)", className); }; this.CommonTemplateRendererInitializing += (c) => { logger.AddEntry("{0}::TemplatesInitializ(ING)", className); }; this.CommonTemplateRendererInitialized += (c) => { logger.AddEntry("{0}::TemplatesInitializ(ED)", className); }; } }