private void CleanupLogger() { if (_logger != null) { _logger.Dispose(); _logger = null; } if (!string.IsNullOrEmpty(_loggerFilename)) { //** remove the log file System.IO.File.Delete(_loggerFilename); _loggerFilename = null; } if (_loggerTransDetails != null) { _loggerTransDetails.Dispose(); _loggerTransDetails = null; } if (!string.IsNullOrEmpty(_loggerTransDetailsFilename)) { System.IO.File.Delete(_loggerTransDetailsFilename); _loggerTransDetailsFilename = null; } //** dispose the text log file if (_loggerTransDetailsFileStream != null) { _loggerTransDetailsFileStream.Dispose(); _loggerTransDetailsFileStream = null; _loggerTransDetailsBuffer = null; System.IO.File.Delete(_loggerTransDetailsLogFilename); } //if (System.IO.Directory.Exists(LogFolder)) // System.IO.Directory.Delete(LogFolder, true); }
public void TestSetup() { this.logger = new GenericLogger(); this.xmlLoader = new XmlLoader(this.logger); string xmlString; using (Stream s = typeof(CommandDefinitionCollection).Assembly.GetManifestResourceStream("Chaskis.Plugins.MeetBot.Config.SampleCommands.xml")) { using (StreamReader reader = new StreamReader(s)) { xmlString = reader.ReadToEnd(); } } // Replace all occurrances with !command instead of #command. xmlString = xmlString.Replace("<prefix>#", "<prefix>!"); // Load both default and user-defined. User-defined will override the default ones. IList <CommandDefinition> defaultDefs = this.xmlLoader.ParseDefaultFile(); IList <CommandDefinition> userDefs = this.xmlLoader.ParseCommandFileFromString(xmlString); List <CommandDefinition> allDefs = new List <CommandDefinition>(defaultDefs); allDefs.AddRange(userDefs); this.collection = new CommandDefinitionCollection(allDefs); // Ensure our collection validates. Assert.DoesNotThrow(() => collection.InitStage1_ValidateDefinitions()); Assert.DoesNotThrow(() => collection.InitStage2_FilterOutOverrides()); }
// ---------------- Functions ---------------- public void Init(PluginInitor pluginInit) { string configPath = Path.Combine( pluginInit.ChaskisConfigPluginRoot, "HttpServer", "HttpServerConfig.xml" ); this.config = XmlLoader.LoadConfig(configPath); this.log = pluginInit.Log; IChaskisEventCreator eventCreator = pluginInit.ChaskisEventCreator; ChaskisEventHandler coreEvent = eventCreator.CreateCoreEventHandler( ChaskisEventProtocol.IRC, this.OnConnect ); this.handlers.Add(coreEvent); ConnectedEventConfig connectedEventConfig = new ConnectedEventConfig { ConnectedAction = this.OnConnect }; this.handlers.Add( new ConnectedEventHandler(connectedEventConfig) ); }
// -------- Functions -------- /// <summary> /// Initializes the plugin. This includes loading any configuration files, /// starting services, etc. Allowed to throw Exceptions. /// /// This function should be used to validates that the environment is good for the plugin. /// For example, it has all dependencies installed, config files are in the correct spot, etc. /// It should also load GetHandlers() with the handlers. /// </summary> /// <param name="pluginInit">The class that has information required for initing the plugin.</param> public void Init(PluginInitor initor) { string configPath = Path.Combine( initor.ChaskisConfigPluginRoot, "CapsWatcher", "CapsWatcherConfig.xml" ); this.log = initor.Log; if (File.Exists(configPath) == false) { throw new FileNotFoundException( "Can not open " + configPath ); } this.config = XmlLoader.LoadCapsWatcherConfig(configPath); this.ignoreRegex = new Regex(CollectionToRegex(config.Ignores), RegexOptions.Compiled | RegexOptions.ExplicitCapture); this.config.Ignores.Clear(); // No need to eat-up RAM, we won't need this again. MessageHandlerConfig msgConfig = new MessageHandlerConfig { LineRegex = ".+", LineAction = this.HandleMessage }; MessageHandler handler = new MessageHandler( msgConfig ); this.handlers.Add(handler); }
// ---------------- Constructor ---------------- public HttpServer() { this.HangTime = 0; this.fileMap = new Dictionary <string, string>(); this.serverLog = Logger.GetLogFromContext("http_server"); this.listeningThread = new Thread(this.HandleRequest); }
// ---------------- Constructor ----------------- public FilesingRunner(FilesingConfig config, GenericLogger log) { if (config == null) { throw new ArgumentNullException(nameof(config)); } config.Validate(); this.threads = new List <Thread>(config.NumberOfThreads); this.keepRunning = false; this.started = false; this.keepRunningObject = new object(); for (int i = 0; i < config.NumberOfThreads; ++i) { string threadName = i.ToString(); Thread thread = new Thread(() => this.ThreadEntry(threadName)) { Name = threadName }; this.threads.Add(thread); } this.config = config; this.log = log; }
// ---------------- Constructor ---------------- public IrcWatchdog(GenericLogger log, Action testAction, Action failureAction, int watchdogTimeout) { ArgumentChecker.IsNotNull(log, nameof(log)); ArgumentChecker.IsNotNull(testAction, nameof(testAction)); ArgumentChecker.IsNotNull(failureAction, nameof(failureAction)); this.isDisposed = false; this.log = log; this.thread = new Thread(this.ThreadEntry) { Name = "Watchdog" }; this.keepGoing = false; this.keepGoingLock = new object(); this.testAction = testAction; this.failureAction = failureAction; this.timeout = watchdogTimeout; this.Started = false; this.threadStartedEvent = new ManualResetEventSlim(false); this.watchdogResetEvent = new AutoResetEvent(false); }
private static IDownloader GenerateDownloader(RetailerConfiguration retailer) { try { switch (retailer.RetailerName) { case "Cel": { return(new CelDownloader(retailer)); } case "PcGarage": { return(new PcGarageDownloader(retailer)); } default: { return(null); } } } catch (Exception ex) { GenericLogger.Error($"could not create downloader for {retailer.RetailerName}"); return(null); } }
private void ParseProducts(DbModelContext dbContext) { int counter = 0; do { Thread.Sleep(3 * 1000); if (products.Count > 0) { var currentProduct = products[counter]; parser.GetProduct(ref currentProduct); counter++; try { dbContext.SaveChanges(); } catch (Exception ex) { GenericLogger.Error($"Error when trying to save changes for updating process for {currentProduct.Url}, \n ex : {ex.Message} \n {ex.StackTrace} \n {ex.InnerException.InnerException.Message}"); } } } while (counter < products.Count); }
public void TestSetup() { this.logger = new GenericLogger(); this.logger.OnWriteLine += (s => Console.WriteLine(s)); this.logger.OnErrorWriteLine += (s => Console.WriteLine(s)); this.reader = new UrlReader(this.logger, PluginTestHelpers.HttpClient); }
public ChaskisTestFramework(string dllFolderPath) { this.EnvironmentManager = new EnvironmentManager(dllFolderPath); this.HttpServer = new HttpServer(); this.HttpClient = new TestHttpClient(); this.IrcServer = new IrcServer(); this.testStateLog = Logger.GetLogFromContext("TestState"); }
public void TestSetup() { this.log = new GenericLogger(); this.log.OnErrorWriteLine += delegate(string s) { Console.Error.WriteLine(s); }; this.testConfig = new IrcLoggerConfig(); this.testConfig.LogName = "TestLog"; this.testConfig.LogFileLocation = testLogDirectory; }
// ---------------- Functions ---------------- public void Init(PluginInitor initor) { this.chaskisEventCreator = initor.ChaskisEventCreator; this.eventSender = initor.ChaskisEventSender; this.ircConfig = initor.IrcConfig; this.logger = initor.Log; this.pluginDir = Path.Combine( initor.ChaskisConfigPluginRoot, "NewVersionNotifier" ); string configPath = Path.Combine( this.pluginDir, "NewVersionNotifierConfig.xml" ); this.config = XmlLoader.LoadConfig(configPath); this.cachedFilePath = Path.Combine( this.pluginDir, cacheFileName ); if (File.Exists(this.cachedFilePath) == false) { this.cachedVersion = string.Empty; } else { string[] lines = File.ReadAllLines(this.cachedFilePath); if (lines.Length == 0) { this.cachedVersion = string.Empty; } else { this.cachedVersion = lines[0].Trim(); } } ChaskisEventHandler eventHandler = this.chaskisEventCreator.CreatePluginEventHandler( "chaskis", this.HandleChaskisEvent ); this.ircHandlers.Add(eventHandler); JoinHandlerConfig joinHandlerConfig = new JoinHandlerConfig { JoinAction = this.OnJoinChannel, RespondToSelf = true }; JoinHandler joinHandler = new JoinHandler(joinHandlerConfig); this.ircHandlers.Add(joinHandler); }
/// <summary> /// Calls the CredUIConfirmCredentials function which confirms that the credentials /// provided for the target should be kept in the case they are persisted.</summary> /// <param name="value">A value of true if the credentials should be persisted.</param> public void Confirm(bool value) { Credmgmtui.ReturnCodes res = Credmgmtui.ConfirmCredentials(this.Target, value); if (res != Credmgmtui.ReturnCodes.NoError && res != Credmgmtui.ReturnCodes.ErrorInvalidParameter) { GenericLogger <CredPrompt> .Error( LocalizibleStrings.ConfirmationFailed + res); } }
public void TestSetup() { this.uut = new GenericLogger(); this.writeLineLoggedMessages = new StringBuilder(); this.warningWriteLineLoggedMessages = new StringBuilder(); this.errorWriteLineLoggedMessages = new StringBuilder(); this.uut.OnWriteLine += Uut_OnWriteLine; this.uut.OnWarningWriteLine += this.Uut_OnWarningWriteLine; this.uut.OnErrorWriteLine += Uut_OnErrorWriteLine; }
private static void StartSearch(CloudQueueMessage message, CrawlSettingsModel model) { GenericLogger.Info($"Started searching for message {message.AsString}"); Parallel.ForEach(model.Retailers , new ParallelOptions() { MaxDegreeOfParallelism = 2 } , retailer => SearchMessageCrawler.StartMessageCrawling(message, retailer) ); }
public void GenericLoggerTest8() { FileLogger instance1 = GenericLogger <FileLogger> .GetInstance(); FileLogger instance2 = GenericLogger <FileLogger> .GetInstance(); Assert.Same(instance1, instance1); instance1.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); instance2.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); }
public void GenericLoggerTest9() { EventLogger instance1 = GenericLogger <EventLogger> .GetInstance(); EventLogger instance2 = GenericLogger <EventLogger> .GetInstance(); Assert.Same(instance1, instance1); instance1.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); instance2.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); }
public void TestSetup() { this.logger = new GenericLogger(); this.xmlLoader = new XmlLoader(this.logger); IList <CommandDefinition> defs = this.xmlLoader.ParseDefaultFile(); this.collection = new CommandDefinitionCollection(defs); // Ensure our collection validates. Assert.DoesNotThrow(() => collection.InitStage1_ValidateDefinitions()); Assert.DoesNotThrow(() => collection.InitStage2_FilterOutOverrides()); }
internal void DownloadProduct(ref Produs product) { try { CreateProductDocument(product); ExtractNeededInformation(ref product); } catch (Exception ex) { GenericLogger.Error($"Exception popped when trying to extract product information for {Url}", ex); } }
// ---------------- Functions ---------------- /// <summary> /// Initializes the plugin. /// </summary> /// <param name="pluginInit">The class that has information required for initing the plugin.</param> public void Init(PluginInitor initor) { string configPath = Path.Combine( initor.ChaskisConfigPluginRoot, "RssBot", "RssBotConfig.xml" ); this.admins = initor.IrcConfig.Admins; this.pluginLogger = initor.Log; if (File.Exists(configPath) == false) { throw new FileNotFoundException( "Can not open " + configPath ); } this.scheduler = initor.EventScheduler; this.rssConfig = XmlLoader.ParseConfig(configPath); foreach (Feed feed in this.rssConfig.Feeds) { FeedReader reader = new FeedReader(feed, initor.HttpClient); reader.Init(); int eventId = this.scheduler.ScheduleRecurringEvent( feed.RefreshInterval, delegate(IIrcWriter writer) { CheckForUpdates(reader, writer, feed.Channels); } ); this.feedReaders.Add(eventId, reader); } MessageHandlerConfig msgConfig = new MessageHandlerConfig { LineRegex = @"!debug\s+rssbot\s+updatefeed\s+(?<url>\S+)", LineAction = this.HandleDebug }; MessageHandler debugHandler = new MessageHandler( msgConfig ); this.handlers.Add(debugHandler); }
public static void Run(GenericLogger log, string message, Action action) { try { log.WriteLine(message + "..."); action(); log.WriteLine(message + "... Done!"); } catch (Exception e) { log.WriteLine(message + ": failed due to crash."); throw new Exception("Rethrow", e); } }
private static void StartMainCrawl() { while (true) { GenericLogger.Info("Starting CrawlUtilities"); var model = CrawlSettingsHelper.LoadCrawlSettings("Update"); MainCrawlStarter.CrawlStart(model); GenericLogger.Info($"Update process finished starting again in 12 hours"); Thread.Sleep(1000 * 60 * 60 * 12); } }
/// <summary> Logs a message to generic log file (the log configuration named '*') </summary> /// <param name="logLevel">LogLevel of the attached logMessage</param> /// <param name="logMessage">String containing message to be logged</param> /// <param name="error">Optional exception to be logged</param> private static void UseGenericLogger(LogLevel logLevel, string logMessage, Exception error = null) { if (!Enabled) { return; } if (null != error) { GenericLogger.Log(logLevel, error, logMessage); } else { GenericLogger.Log(logLevel, logMessage); } }
private static FilesingConfig GenerateConfig(Regex regex, string searchDir, GenericLogger log, string inFile) { FilesingConfig config; if (regex == null) { log.WriteLine( FilesingConstants.LightVerbosity, "- Using regexes from config file '{0}'", inFile ); config = XmlLoader.LoadConfigFromXml(inFile, searchDir); } else { log.WriteLine( FilesingConstants.LightVerbosity, "- Regex specified on command line. Using regex '" + regex.ToString() + "'" ); if (string.IsNullOrWhiteSpace(inFile)) { log.WriteLine( FilesingConstants.LightVerbosity, "- No config file specified, not ignoring any files or directories." ); config = new FilesingConfig(); } else { log.WriteLine( FilesingConstants.LightVerbosity, "- Config file '{0}' specified. Using config file's global ignores and requires. Ignoring file's patterns since 'regex' was specified on CLI.", inFile ); config = XmlLoader.LoadConfigFromXml(inFile, searchDir); } config.PatternConfigs.Clear(); PatternConfig patternConfig = new PatternConfig(regex); config.PatternConfigs.Add(patternConfig); } config.SearchDirectoryLocation = searchDir; return(config); }
// ---------------- Constructor ---------------- public ChaskisProcess(string distDir, string environmentDir) { this.consoleOutLog = Logger.GetLogFromContext("chaskis"); this.consoleErrorLog = Logger.GetLogFromContext("chaskis_error"); this.testConsoleOutLog = Logger.GetLogFromContext("chaskis_status"); this.exeLocation = Path.Combine( distDir, "bin" ); this.dllLocation = Path.Combine( exeLocation, "Chaskis.dll" ); string exeString; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { exeString = ".exe"; } else { exeString = string.Empty; } this.exeFile = Path.Combine( exeLocation, "Chaskis" + exeString ); this.consoleOutLog.WriteLine("Chaskis.exe Location: " + this.exeFile); this.startInfo = new ProcessStartInfo( this.exeFile, $"--chaskisroot=\"{environmentDir}\"" ) { RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; this.buffer = new StringBuffer(); this.isDisposed = false; }
// ---------------- Functions ---------------- public void Init(PluginInitor initor) { this.logger = initor.Log; string pluginDir = Path.Combine( initor.ChaskisConfigPluginRoot, "IsItDownBot" ); string configPath = Path.Combine( pluginDir, "IsItDownBotConfig.xml" ); this.config = XmlLoader.LoadConfig(configPath); }
// ---------------- Functions ---------------- public void Init(PluginInitor initor) { this.logger = initor.Log; this.pluginDir = Path.Combine( initor.ChaskisConfigPluginRoot, PluginName ); this.defaultNotesDirectory = Path.Combine( this.pluginDir, "meeting_notes" ); ReadConfigFiles(); BuildRootHelpMsg(); }
// ---------------- Constructor ---------------- /// <summary> /// Constructor. /// </summary> /// <param name="path">Absolute Path to the assembly</param> public PluginConfig( string path, string name, IList <string> blacklistedChannels, IPlugin plugin, GenericLogger log ) { ArgumentChecker.StringIsNotNullOrEmpty(path, nameof(path)); this.AssemblyPath = path; this.DirectoryPath = Path.GetDirectoryName(this.AssemblyPath); this.Name = name; this.BlackListedChannels = new List <string>(blacklistedChannels).AsReadOnly(); this.Plugin = plugin; this.Log = log; }
/// <summary> /// Gets the log of the given context (e.g. Console Out). /// </summary> public static GenericLogger GetLogFromContext(string context) { lock (instance.logs) { if (instance.logs.ContainsKey(context) == false) { GenericLogger logger = new GenericLogger(); string contextInternal = context; logger.OnWriteLine += delegate(string line) { GenericLogger_OnWriteLine(line, contextInternal); }; instance.logs[context] = logger; } return(instance.logs[context]); } }