public async Task LogResponseMiddleware_Debug_Logger_Called_For_Info_And_Debug() { var path = "/api/"; var bodyText = "response body text"; NLogConfig.TrackDebugEnabled("LogResponseMiddleware", NL.LogLevel.Debug); var LogResponseMiddleware = new LogResponseMiddleware( async(innerHttpContext) => { await innerHttpContext.Response.WriteAsync(bodyText); }, _mockLoggerFactory.Object); var context = CreateContext(path); await LogResponseMiddleware.Invoke(context); context.Response.StatusCode.Should().Be((int)HttpStatusCode.OK); _mockLogger.Verify(x => x.Log(LogLevel.Information, It.IsAny <EventId>(), It.Is <FormattedLogValues>(v => v.ToString().Contains(path)), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Once); _mockLogger.Verify(x => x.Log(LogLevel.Debug, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Once); _mockLogger.Verify(x => x.Log(LogLevel.Debug, It.IsAny <EventId>(), It.Is <FormattedLogValues>(v => v.ToString().Contains(bodyText)), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Once); }
public LogForm(ShadowsocksController controller) { this.controller = controller; InitializeComponent(); Icon = Icon.FromHandle(Resources.ssw128.GetHicon()); var nLogConfig = NLogConfig.LoadXML(); try { this.filename = nLogConfig.GetLogFileName(); } catch (Exception) { // failed to get the file name } if (string.IsNullOrEmpty(this.filename)) { LogMessageTextBox.AppendText("Cannot get the log file name from NLog config file. Please check if the nlog config file exists with corresponding XML nodes."); } LogViewerConfig config = controller.GetConfigurationCopy().logViewer; topMostTrigger = config.topMost; wrapTextTrigger = config.wrapText; toolbarTrigger = config.toolbarShown; LogMessageTextBox.BackColor = config.BackgroundColor; LogMessageTextBox.ForeColor = config.TextColor; LogMessageTextBox.Font = config.Font; controller.TrafficChanged += controller_TrafficChanged; UpdateTexts(); }
private static void Main(string[] args) { Console.Title = "Pingu - Private Server"; Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; KeepRunning.Set(); }; LogManager.Configuration = NLogConfig.Create(); LogManager.GetCurrentClassLogger().Debug("Configured NLog.."); PacketHandler.Initialize(); using (var server = new Server()) { server.Start(); KeepRunning.WaitOne(); server.Stop(); } // In production mode, we do not want to hang with readkey. if (!Debugger.IsAttached) { return; } Logger.Info("Exiting, press a key to close.."); Console.ReadKey(); }
public void ToggleVerboseLogging(bool enabled) { _config.isVerboseLogging = enabled; SaveConfig(_config); NLogConfig.LoadConfiguration(); // reload nlog VerboseLoggingStatusChanged?.Invoke(this, new EventArgs()); }
protected void Application_Start() { NLogConfig.RegisterConfig(); RouteConfig.RegisterRoutes(RouteTable.Routes); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); NLogConfig.RegisterConfig(); }
protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); NLogConfig.LoadConfiguration(); privoxyRunner = privoxyRunner ?? new PrivoxyRunner(); _pacDaemon = _pacDaemon ?? new PACDaemon(); _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged; _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged; _pacServer = _pacServer ?? new PACServer(_pacDaemon); _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled. gfwListUpdater = gfwListUpdater ?? new GFWListUpdater(); gfwListUpdater.UpdateCompleted += PacServer_PACUpdateCompleted; gfwListUpdater.Error += PacServer_PACUpdateError; // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open privoxyRunner.Stop(); _pacServer.Stop(); try { privoxyRunner.Start(this, _config); _pacServer.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e); } } logger.LogUsefulException(e); ReportError(e); } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); Utils.ReleaseMemory(true); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var rhm = new RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, "application/json"); GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(rhm); RouteConfig.RegisterRoutes(RouteTable.Routes); AutoMapperConfig.Configure(); AreaRegistration.RegisterAllAreas(); NLogConfig.nLogger().Log(new NLog.LogEventInfo(NLog.LogLevel.Info, "this", "webservice Started")); }
protected void Application_Start() { // My configurations AutofacConfig.ConfigureContainer(); AutoMapperConfig.Configure(); NLogConfig.Configure(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); NLogConfig.Init(); #if !DEBUG DispatcherUnhandledException += (s, ex) => { LogManager.GetLogger("DispatcherUnhandledException").Error(ex.Exception); }; // ui thread AppDomain.CurrentDomain.UnhandledException += (s, ex) => { LogManager.GetLogger("AppDomainUnhandledException").Error((Exception)ex.ExceptionObject); }; // non ui threads #endif Settings.Load(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services .AddEntityFrameworkSqlServer() .AddDbContext <LogDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SolutionLoggerDataConnection"))); services .AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddSingleton <IConfiguration>(AppJsonConfig.Configuration); services.AddApplicationInsightsTelemetry(AppJsonConfig.Configuration); services.AddDbContext <LogDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SolutionLoggerDataConnection")), ServiceLifetime.Transient); services.AddTransient <IAppSettingRepository, AppSettingRepository>(); services.AddTransient(typeof(ServiceAppSetting)); ServiceProvider provider = services.BuildServiceProvider(); provider.GetService <ServiceAppSetting>().GetDefaultServiceAppSettings(); #region Event bus config start ConcurrentDictionary <string, string> eventBusConfigurationList = new ConcurrentDictionary <string, string>(); eventBusConfigurationList.TryAdd("BrokerConnection", Configuration.GetValue <string>("Logger:BrokerConnection")); services.AddSingleton <EventBusConfiguration>(s => new EventBusConfiguration(eventBusConfigurationList)); services.AddSingleton <IEventBus, AzureServiceBusManager>(); services.Configure <DomainManager>(s => { s.ServiceType = ServiceType.General_LoggerService; s.DomainConfiguration = new List <Type> { typeof(ErrorLoggerModel), typeof(FatalLoggerModel), typeof(DebugLoggerModel), typeof(WarningLoggerModel), typeof(InfoLoggerModel) }; }); #endregion Event bus config End #region Setup NLog Configuration string EnableInternalLogForNLog = Configuration.GetSection("AppConfiguration").GetSection("EnableInternalLogForNLog").Value ?? General.RaiseConfigurationMissingException("EnableInternalLogForNLog"); NLogConfig.SetLogTarget(Configuration.GetConnectionString("SolutionLoggerDataConnection"), string.IsNullOrWhiteSpace(EnableInternalLogForNLog) ? false : Convert.ToBoolean(EnableInternalLogForNLog)); #endregion Setup NLog Configuration services.AddSingleton <IHostedService, CleanApplicationLogScheduler>(); }
private static void Main() { // Set NLog config. LogManager.Configuration = NLogConfig.Create(); // Run program. Run().GetAwaiter().GetResult(); // Catch exit. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); NLogConfig.ConfigureLogger(); AppKernel = new StandardKernel(new NinjectModule[] { new JobVacancyModule(), new UserModule(), new SearcherModule(), new ResumeModule() }); StartRolesConfig.Configure(); Logger.Info("Application start"); }
public static IServiceCollection AddLogging(IServiceCollection serviceCollection) { var config = NLogConfig.GetNLogConfig(); // Apply config NLog.LogManager.Configuration = config; return(serviceCollection .AddLogging(loggingBuilder => { // configure Logging with NLog loggingBuilder.ClearProviders(); loggingBuilder.SetMinimumLevel(LogLevel.Trace); loggingBuilder.AddNLog(config); })); }
public void CreateConfiguration_Does_Not_Create_All_Logs_Target_In_Test_Envn() { _mockEnvironment.SetupGet(env => env.EnvironmentName).Returns("Test"); var loggingConfiguration = NLogConfig.CreateConfiguration(_mockEnvironment.Object); loggingConfiguration.Should().NotBe(null); loggingConfiguration.ConfiguredNamedTargets.Should().NotBeEmpty(); loggingConfiguration.LoggingRules.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().ContainKey("appName"); loggingConfiguration.Variables.Should().ContainKey("logDirectory"); loggingConfiguration.Variables["appName"].Text.Should().Be(ENVN_APP_NAME); loggingConfiguration.ConfiguredNamedTargets.Count.Should().Be(1); loggingConfiguration.ConfiguredNamedTargets[0].Should().BeOfType(typeof(FileTarget)); }
public void Build_Logging_Rule() { var rule = NLogConfig.BuildLoggingRule("*Service", "Trace", LogLevel.Info); rule.LoggerNamePattern.Should().Be("*Service"); rule.Levels[0].Should().Be(LogLevel.Trace); var rule2 = NLogConfig.BuildLoggingRule("*Service", "Error", LogLevel.Info); rule2.LoggerNamePattern.Should().Be("*Service"); rule2.Levels[0].Should().Be(LogLevel.Error); var rule3 = NLogConfig.BuildLoggingRule("*Service", "Garbage", LogLevel.Info); rule3.LoggerNamePattern.Should().Be("*Service"); rule3.Levels[0].Should().Be(LogLevel.Info); }
public void CreateConfiguration_Returns_Default_LoggingConfiguration() { _mockEnvironment.SetupGet(env => env.EnvironmentName).Returns("Local"); var loggingConfiguration = NLogConfig.CreateConfiguration(_mockEnvironment.Object); loggingConfiguration.Should().NotBe(null); loggingConfiguration.ConfiguredNamedTargets.Should().NotBeEmpty(); loggingConfiguration.LoggingRules.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().ContainKey("appName"); loggingConfiguration.Variables.Should().ContainKey("logDirectory"); loggingConfiguration.Variables["appName"].Text.Should().Be(ENVN_APP_NAME); loggingConfiguration.ConfiguredNamedTargets.Count.Should().BeGreaterThan(1); loggingConfiguration.ConfiguredNamedTargets[0].Should().BeOfType(typeof(FileTarget)); loggingConfiguration.ConfiguredNamedTargets[1].Should().BeOfType(typeof(FileTarget)); }
static void Main(string[] args) { NLogConfig.InitConsoleLogger(); var service = new NodeSomeService(); service.Start(); Console.CancelKeyPress += (sender, eventArgs) => { service.Stop().Wait(); eventArgs.Cancel = true; }; service.WhenTerminated.Wait(); }
public static LoggingConfiguration CreateConfigration(NLogConfig userConfig) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var fileTarget = new FileTarget(); //%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } [%traceId] [%t][%logger] : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx //2017-07-24 18:42:28.699 ERROR 10997 [null][viceImpl-0-exe0] com.Farseer.dubbo.example.service.Handle: aaaaaaaaa //时间,日志类别,进程ID,TraceId,线程名称,命名空间.类名 日志内容 // Step 3. Set target properties //fileTarget.FileName = "c:/Farseerlog/应用名称/日志文件.log"; //fileTarget.FileName = $"{itemConfig.FolderPath}{itemConfig.AppName}/日志文件.log"; fileTarget.FileName = $"c:/Farseerlog/{userConfig.AppName}/日志文件.log"; //fileTarget.Layout = @"${MyDateTime} ${level:uppercase=True} ${processid} [${traceid}] [${threadid}] ${callsite:className=True:includeNamespace=True:fileName=False:includeSourcePath=True:methodName = False:cleanNamesOfAnonymousDelegates = False:skipFrames = 0}: ${message} ${newline}"; //fileTarget.Layout = @"[${MyDateTime}] ${level:uppercase=True} ${processid} [${traceid}] [${threadname}] ${callsite:className=True:includeNamespace=True:fileName=False:includeSourcePath=True:methodName = False:cleanNamesOfAnonymousDelegates = False:skipFrames = 0}: ${message}"; fileTarget.Layout = @"[${date:format=yyyy-MM-dd HH\:mm\:ss.fff}] ${level} ${processid} [${traceid}] [${threadid}] [${callsite:className=True:includeNamespace=True:fileName=False:includeSourcePath=True:methodName = False:cleanNamesOfAnonymousDelegates = False:skipFrames = 0}] : ${message}${exception:innerFormat=StackTrace:maxInnerExceptionLevel=100:format=StackTrace}"; //fileTarget.ArchiveFileName = "c:/Farseerlog/应用名称/日志文件{#}.log"; //fileTarget.ArchiveFileName = itemConfig.FolderPath+itemConfig.AppName+"/日志文件{#}.log"; fileTarget.ArchiveFileName = "c:/Farseerlog/" + userConfig.AppName + "/日志文件{#}.log"; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling; fileTarget.MaxArchiveFiles = 10; fileTarget.ArchiveAboveSize = 1024 * 1024 * 512; //1024 * 1024 * 1024; fileTarget.ConcurrentWrites = true; fileTarget.KeepFileOpen = true; fileTarget.OpenFileCacheTimeout = 30; fileTarget.Encoding = Encoding.UTF8; var asyncTargetWrapper = new AsyncTargetWrapper(fileTarget, 10000, AsyncTargetWrapperOverflowAction.Discard); config.AddTarget("Farseer_log_file", asyncTargetWrapper); // Step 4. Define rules var rule2 = new LoggingRule("*", LogLevel.Trace, asyncTargetWrapper); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration return(config); }
public void CreateConfiguration_Returns_No_FileTarget_LoggingConfiguration() { _mockEnvironment.SetupGet(env => env.EnvironmentName).Returns("Local"); _mockLogConfiguration.SetupGet(config => config.AppName).Returns(CUSTOM_APP_NAME); _mockLogConfiguration.SetupGet(config => config.EnableWebLogs).Returns(false); _mockLogConfiguration.SetupGet(config => config.EnableAllLogs).Returns(true); var loggingConfiguration = NLogConfig.CreateConfiguration(_mockEnvironment.Object, _mockLogConfiguration.Object); loggingConfiguration.Should().NotBe(null); loggingConfiguration.ConfiguredNamedTargets.Should().NotBeEmpty(); loggingConfiguration.LoggingRules.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().ContainKey("appName"); loggingConfiguration.Variables.Should().ContainKey("logDirectory"); loggingConfiguration.Variables["appName"].Text.Should().Be(CUSTOM_APP_NAME); loggingConfiguration.ConfiguredNamedTargets.Count.Should().Be(1); loggingConfiguration.ConfiguredNamedTargets[0].Should().BeOfType(typeof(FileTarget)); }
public static void Main(string[] args) { NLogConfig.Configure(); var logger = NLog.LogManager.GetCurrentClassLogger(); try { logger.Trace($"In '{nameof(Main)}'."); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { logger.Error(ex, $"Error in {nameof(Main)}'."); throw; } finally { NLog.LogManager.Shutdown(); } }
private static void Main() { // Set console title. Console.Title = "Wolfteam.Client"; Console.CancelKeyPress += (sender, args) => { args.Cancel = true; QuitEvent.Set(); }; Console.WriteLine("Press CTRL+C to exit."); // Set NLog config. LogManager.Configuration = NLogConfig.Create(); // Run program. Run().GetAwaiter().GetResult(); // Wait until cancel. QuitEvent.WaitOne(); }
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { // Logger Config LogManager.Configuration = NLogConfig.GetConfig(); Logger logger = LogManager.GetCurrentClassLogger(); try { logger.Info("Quorra server initialising."); CreateHostBuilder(args).Build().Run(); } catch (Exception e) { logger.Fatal(e, "Stopped Nexus server because of a fatal exception."); throw; } finally { // Flush and stop internal timers/threads before application-exit LogManager.Shutdown(); } }
public static void Main(string[] args) { Console.Title = "QPangReborn | Server.Auth PROTOTYPE"; LogManager.Configuration = NLogConfig.Create(); Logger.Warn("Starting up Server.Auth."); _keepRunning = true; _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8003)); _serverSocket.Listen(20); AcceptNewConnection(); while (_keepRunning) { var command = Console.ReadLine(); switch (command) { case "exit": case "quit": case "q": _keepRunning = false; break; default: Logger.Warn("Unknown command, available commands: exit, quit & q."); break; } } Logger.Warn("Shutting down Server.Auth."); _serverSocket.Close(); _serverSocket.Dispose(); Logger.Warn("Press any key to exit."); Console.ReadKey(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelBinders.Binders.Add( typeof(decimal), new DecimalModelBinder()); ModelBinders.Binders.Add( typeof(decimal?), new DecimalModelBinder()); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); LogManager.Configuration = NLogConfig.Configure(); if (!Directory.Exists(HttpContext.Current.Server.MapPath($"~/App_Data"))) { throw new Exception("O diretório App_Data não foi encontrado"); } }
public void CreateConfiguration_Using_Appsettings() { _mockEnvironment.SetupGet(env => env.EnvironmentName).Returns("Local"); _mockLogConfiguration.SetupGet(config => config.AppName).Returns(CUSTOM_APP_NAME); _mockLogConfiguration.SetupGet(config => config.EnableWebLogs).Returns(false); _mockLogConfiguration.SetupGet(config => config.EnableAllLogs).Returns(true); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false); var testConfig = builder.Build(); var nlogConfig = testConfig.GetSection("Logging:NLog"); var loggingConfiguration = NLogConfig.CreateConfiguration(_mockEnvironment.Object, nlogConfig); loggingConfiguration.Should().NotBe(null); loggingConfiguration.ConfiguredNamedTargets.Should().NotBeEmpty(); loggingConfiguration.LoggingRules.Should().NotBeEmpty(); loggingConfiguration.LoggingRules.Count.Should().Be(5); loggingConfiguration.LoggingRules[0].LoggerNamePattern.Should().Be("*"); loggingConfiguration.LoggingRules[0].Levels[0].Should().Be(LogLevel.Debug); loggingConfiguration.LoggingRules[1].LoggerNamePattern.Should().Be("*Controller"); loggingConfiguration.LoggingRules[1].Levels[0].Should().Be(LogLevel.Trace); loggingConfiguration.LoggingRules[2].LoggerNamePattern.Should().Be("Default"); loggingConfiguration.LoggingRules[2].Levels[0].Should().Be(LogLevel.Debug); loggingConfiguration.LoggingRules[3].LoggerNamePattern.Should().Be("ErrorHandlingMiddleware"); loggingConfiguration.LoggingRules[3].Levels[0].Should().Be(LogLevel.Info); loggingConfiguration.LoggingRules[4].LoggerNamePattern.Should().Be("Service*"); loggingConfiguration.LoggingRules[4].Levels[0].Should().Be(LogLevel.Error); loggingConfiguration.Variables.Should().NotBeEmpty(); loggingConfiguration.Variables.Should().ContainKey("appName"); loggingConfiguration.Variables.Should().ContainKey("logDirectory"); loggingConfiguration.Variables["appName"].Text.Should().Be(ENVN_APP_NAME); loggingConfiguration.ConfiguredNamedTargets.Count.Should().Be(2); loggingConfiguration.ConfiguredNamedTargets[0].Should().BeOfType(typeof(FileTarget)); }
protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); NLogConfig.LoadConfiguration(); StatisticsConfiguration = StatisticsStrategyConfiguration.Load(); privoxyRunner = privoxyRunner ?? new PrivoxyRunner(); _pacDaemon = _pacDaemon ?? new PACDaemon(_config); _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged; _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged; _pacServer = _pacServer ?? new PACServer(_pacDaemon); _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled. GeositeUpdater.ResetEvent(); GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted; GeositeUpdater.Error += PacServer_PACUpdateError; availabilityStatistics.UpdateConfiguration(this); _listener?.Stop(); StopPlugins(); // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open privoxyRunner.Stop(); try { var strategy = GetCurrentStrategy(); strategy?.ReloadServers(); StartPlugin(); privoxyRunner.Start(_config); TCPRelay tcpRelay = new TCPRelay(this, _config); tcpRelay.OnConnected += UpdateLatency; tcpRelay.OnInbound += UpdateInboundCounter; tcpRelay.OnOutbound += UpdateOutboundCounter; tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server); UDPRelay udpRelay = new UDPRelay(this); List <Listener.IService> services = new List <Listener.IService> { tcpRelay, udpRelay, _pacServer, new PortForwarder(privoxyRunner.RunningPort) }; _listener = new Listener(services); _listener.Start(_config); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e); } } logger.LogUsefulException(e); ReportError(e); } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); Utils.ReleaseMemory(true); }
public static void DumpMassIcons(GpkStore store, String outdir, Dictionary <String, List <CompositeMapEntry> > filterList) { logger.Info("Started dumping textures to " + outdir); Directory.CreateDirectory(outdir); SynchronizedCollection <Task> runningTasks = new SynchronizedCollection <Task>(); int MAX_TASKS = 100; foreach (var file in filterList) { if (!file.Value.Any(x => x.UID.StartsWith("Icon_"))) { continue; } //throttle thread creation while (runningTasks.Count > MAX_TASKS) { Thread.Sleep(1000); } //limit to 5 threads by default foreach (var entry in file.Value) { if (!entry.UID.StartsWith("Icon_")) { continue; } Task newTask = null; newTask = new Task(() => { string path = string.Format("{0}\\{1}.gpk", store.BaseSearchPath, entry.SubGPKName); var fullName = entry.UID.Split('.'); //create out dir var fileOutPath = string.Format("{0}\\{1}\\", outdir, fullName[0]); Directory.CreateDirectory(fileOutPath); if (!File.Exists(path)) { logger.Warn("GPK to load not found. Searched for: " + path); return; } Reader r = new Reader(); var package = r.ReadSubGpkFromComposite(path, entry.UID, entry.FileOffset, entry.FileLength); package.LowMemMode = true; //extract var exports = package.GetExportsByClass("Core.Texture2D"); foreach (var export in exports) { //UID->Composite UID //S1UI_Chat2.Chat2,c7a706fb_6a349a6f_1d212.Chat2_dup | //we use this uid from pkgmapper //var imagePath = string.Format("{0}{1}_{2}.dds", fileOutPath, entry.UID, export.UID); var imagePath = string.Format("{0}{1}.dds", fileOutPath, fullName[1]); TextureTools.exportTexture(export, imagePath); logger.Info("Extracted texture {0} to {1}", entry.UID, imagePath); } //remove ref to ease gc exports.Clear(); package = null; runningTasks.Remove(newTask); }); newTask.Start(); runningTasks.Add(newTask); } } Task.WaitAll(runningTasks.ToArray()); NLogConfig.EnableFormLogging(); logger.Info("Dumping done"); }
protected void Reload() { Encryption.RNG.Reload(); // some logic in configuration updated the config when saving, we need to read it again _config = Configuration.Load(); Configuration.Process(ref _config); NLogConfig.LoadConfiguration(); logger.Info($"WPF Localization Extension|Current culture: {LocalizeDictionary.CurrentCulture}"); // set User-Agent for httpClient try { if (!string.IsNullOrWhiteSpace(_config.userAgentString)) { httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString); } } catch { // reset userAgent to default and reapply Configuration.ResetUserAgent(_config); httpClient.DefaultRequestHeaders.Add("User-Agent", _config.userAgentString); } privoxyRunner = privoxyRunner ?? new PrivoxyRunner(); _pacDaemon = _pacDaemon ?? new PACDaemon(_config); _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged; _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged; _pacServer = _pacServer ?? new PACServer(_pacDaemon); _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled. GeositeUpdater.ResetEvent(); GeositeUpdater.UpdateCompleted += PacServer_PACUpdateCompleted; GeositeUpdater.Error += PacServer_PACUpdateError; _tcpListener?.Stop(); _udpListener?.Stop(); StopPlugins(); // don't put PrivoxyRunner.Start() before pacServer.Stop() // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1 // though UseShellExecute is set to true now // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open privoxyRunner.Stop(); try { var strategy = GetCurrentStrategy(); strategy?.ReloadServers(); StartPlugin(); privoxyRunner.Start(_config); TCPRelay tcpRelay = new TCPRelay(this, _config); tcpRelay.OnInbound += UpdateInboundCounter; tcpRelay.OnOutbound += UpdateOutboundCounter; tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server); UDPRelay udpRelay = new UDPRelay(this); _tcpListener = new TCPListener(_config, new List <IStreamService> { tcpRelay, _pacServer, new PortForwarder(privoxyRunner.RunningPort), }); _tcpListener.Start(); _udpListener = new UDPListener(_config, new List <IDatagramService> { udpRelay, }); _udpListener.Start(); } catch (Exception e) { // translate Microsoft language into human language // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use if (e is SocketException se) { if (se.SocketErrorCode == SocketError.AddressAlreadyInUse) { e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e); } else if (se.SocketErrorCode == SocketError.AccessDenied) { e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e); } } logger.LogUsefulException(e); ReportError(e); } ConfigChanged?.Invoke(this, new EventArgs()); UpdateSystemProxy(); }