Пример #1
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="defaultBannedIPAddressHandlerUrl">Url for banned ip handling or null to not handle banned ip</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null, string defaultBannedIPAddressHandlerUrl = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            DefaultHttpRequestMaker.DisableLiveRequests = true;

            // cleanup any db, set or tbl files
            foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set")
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.set6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tbl6"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite-wal"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sqlite-shm"))
                     .Union(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*-journal")))
            {
                ExtensionMethods.FileDeleteWithRetry(file, 1000);
            }

            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Path.GetDirectoryName(IPBanAssembly.Location);
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanService.ConfigFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            ExtensionMethods.FileWriteAllTextWithRetry(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            if (defaultBannedIPAddressHandlerUrl is null)
            {
                service.BannedIPAddressHandler = NullBannedIPAddressHandler.Instance;
            }
            else
            {
                service.BannedIPAddressHandler = new DefaultBannedIPAddressHandler {
                    BaseUrl = defaultBannedIPAddressHandlerUrl
                };
            }
            service.Version = "1.1.1.1";
            service.StartAsync().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }
Пример #2
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="defaultBannedIPAddressHandlerUrl">Url for banned ip handling or null to not handle banned ip</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null, string defaultBannedIPAddressHandlerUrl = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            ExtensionMethods.RemoveDatabaseFiles();
            DefaultHttpRequestMaker.DisableLiveRequests = true;
            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = Path.GetDirectoryName(IPBanAssembly.Location);
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanConfig.DefaultFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            ExtensionMethods.FileWriteAllTextWithRetry(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            service.DnsList = null; // too slow for tests, turn off
            if (defaultBannedIPAddressHandlerUrl is null)
            {
                service.BannedIPAddressHandler = NullBannedIPAddressHandler.Instance;
            }
            else
            {
                service.BannedIPAddressHandler = new DefaultBannedIPAddressHandler {
                    BaseUrl = defaultBannedIPAddressHandlerUrl
                };
            }
            service.Version = "1.1.1.1";
            service.RunAsync(CancellationToken.None).Sync();
            service.RunCycle().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }
Пример #3
0
        /// <summary>
        /// Start typed ipban service
        /// </summary>
        /// <typeparam name="T">Type of ipban service</typeparam>
        /// <param name="args">Args</param>
        /// <param name="started">Started callback</param>
        /// <returns>Task</returns>
        public static async Task MainService <T>(string[] args, Action started = null) where T : IPBanService
        {
            T service = IPBanService.CreateService <T>();

            await MainService(args, async (_args) =>
            {
                // kick off start in background thread, make sure service starts up in a timely manner
                await service.StartAsync();
                started?.Invoke();

                // wait for service to end
                await service.WaitAsync(Timeout.Infinite);
            }, () =>
            {
                // stop the service, will cause any WaitAsync to exit
                service.Stop();
            });
        }
Пример #4
0
        /// <summary>
        /// Create a test IPBanService
        /// </summary>
        /// <param name="directory">Root directory</param>
        /// <param name="configFileName">Config file name</param>
        /// <param name="defaultBannedIPAddressHandlerUrl">Url for banned ip handling or null to not handle banned ip</param>
        /// <param name="configFileModifier">Change config file (param are file text, returns new file text)</param>
        /// <returns>Service</returns>
        public static T CreateAndStartIPBanTestService <T>(string directory = null, string configFileName = null, string defaultBannedIPAddressHandlerUrl = null,
                                                           Func <string, string> configFileModifier = null) where T : IPBanService
        {
            NLog.Time.TimeSource.Current = new TestTimeSource();
            string defaultNLogConfig = $@"<?xml version=""1.0""?>
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" throwExceptions=""false"" internalLogToConsole=""false"" internalLogToConsoleError=""false"" internalLogLevel=""Trace"">
  <targets>
    <target name=""logfile"" xsi:type=""File"" fileName=""${{basedir}}/logfile.txt"" encoding=""UTF-8""/>
    <target name=""console"" xsi:type=""Console""/>
  </targets>
  <rules>
    <logger name=""*"" minlevel=""Debug"" writeTo=""logfile""/>
    <logger name=""*"" minlevel=""Debug"" writeTo=""console""/>
  </rules>
</nlog>";

            File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "nlog.config"), defaultNLogConfig);

            string logFilePath = Path.Combine(AppContext.BaseDirectory, "logfile.txt");

            if (File.Exists(logFilePath))
            {
                File.Delete(logFilePath);
            }

            ExtensionMethods.RemoveDatabaseFiles();
            DefaultHttpRequestMaker.DisableLiveRequests = true;
            if (string.IsNullOrWhiteSpace(directory))
            {
                directory = AppContext.BaseDirectory;
            }
            if (string.IsNullOrWhiteSpace(configFileName))
            {
                configFileName = IPBanConfig.DefaultFileName;
            }
            string configFilePath = Path.Combine(directory, configFileName);
            string configFileText = File.ReadAllText(configFilePath);

            configFilePath += ".tmp";
            if (configFileModifier != null)
            {
                configFileText = configFileModifier(configFileText);
            }
            ExtensionMethods.FileWriteAllTextWithRetry(configFilePath, configFileText);
            T service = IPBanService.CreateService <T>() as T;

            service.ExternalIPAddressLookup = LocalMachineExternalIPAddressLookupTest.Instance;
            service.ConfigFilePath          = configFilePath;
            service.MultiThreaded           = false;
            service.ManualCycle             = true;
            service.DnsList = null; // too slow for tests, turn off
            if (defaultBannedIPAddressHandlerUrl is null)
            {
                service.BannedIPAddressHandler = NullBannedIPAddressHandler.Instance;
            }
            else
            {
                service.BannedIPAddressHandler = new DefaultBannedIPAddressHandler {
                    BaseUrl = defaultBannedIPAddressHandlerUrl
                };
            }
            service.Version = "1.1.1.1";
            service.RunAsync(CancellationToken.None).Sync();
            service.RunCycleAsync().Sync();
            service.DB.Truncate(true);
            service.Firewall.Truncate();
            return(service);
        }