Exemplo n.º 1
0
        public Scanner(ScanProperties props)
        {
            _props       = props;
            _serviceName = $"Scanner_{Guid.NewGuid()}";

            if (!Directory.Exists(props.InDir))
            {
                Directory.CreateDirectory(props.InDir);
            }

            if (!Directory.Exists(props.ErrorDir))
            {
                Directory.CreateDirectory(props.ErrorDir);
            }

            _watcher          = new FileSystemWatcher(props.InDir);
            _watcher.Changed += Watcher_Changed;

            _workThread   = new Thread(WorkingMethod);
            _stopEvent    = new ManualResetEvent(false);
            _newFileEvent = new AutoResetEvent(false);

            _sbClient = new ServerSbClient(string.Empty, props.CnString, props.InfoQueueName);
            _sbClient.InitTopics();

            _imagesAggregator = new ImagesAggregator(props, FilePattern, _sbClient);
        }
        public override async Task OnExecuteAsync(ProgramOptions pOptions, CommandOptions cOptions, CancellationToken cToken)
        {
            Console.WriteLine("Scanning for serial ports...");

            if (!Enum.TryParse(pOptions.Status, out PortStatus portStatus))
            {
                Console.WriteLine("Invalid port status.");
                return;
            }

            try
            {
                var portScanner = new SerialPortScanner();
                var settings    = new ScanProperties(pOptions.MinPort, pOptions.MaxPort, portStatus);

                var scanResult = await portScanner.ScanAsync(settings, cToken);

                new PortStatusPrinter().PrintTable(scanResult);

                Console.WriteLine("\nDone.");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Command 'serialPort', ran into exception: {e.Message}");
            }
        }
Exemplo n.º 3
0
        public Scanner(ScanProperties props, IFileSystemHelper fileSystemHelper, ILogger logger)
        {
            _fileSystemHelper = fileSystemHelper;
            _logger           = logger;

            _inputFolders = props.InputLocations;

            fileSystemHelper.CreateDirectoryIfNotExists(_inputFolders);
            fileSystemHelper.CreateDirectoryIfNotExists(props.OutputLocation);
        }
Exemplo n.º 4
0
        public ImagesAggregator(ScanProperties props, string filePattern, ServerSbClient serviceBusClient)
        {
            _props         = props;
            _patternPrefix = filePattern.Split('*')[0];

            _logger             = Logger.Logger.Current;
            _usedFiles          = new List <string>();
            _saveTimer          = new Timer(props.ScanTimeout);
            _saveTimer.Elapsed += (sender, args) => SendDocument();
            _lockObj            = new object();
            InitDocAndSection();

            _serviceBusClient = serviceBusClient;
        }
Exemplo n.º 5
0
        public void Test_InvalidPortScanRange(int minPort, int maxPort)
        {
            var wpScanner = new WebPortScanner();

            Assert.ThrowsAsync <ArgumentException>(async() =>
            {
                var scanProperties = new ScanProperties
                {
                    MinPort = minPort,
                    MaxPort = maxPort
                };

                await wpScanner.ScanAsync(scanProperties, CancellationToken.None);
            });
        }
Exemplo n.º 6
0
        public void Test_MaxPortLimit()
        {
            var wpScanner = new WebPortScanner();

            Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() =>
            {
                var scanProperties = new ScanProperties
                {
                    MinPort = 1,
                    MaxPort = 65536
                };

                await wpScanner.ScanAsync(scanProperties, CancellationToken.None);
            });
        }
Exemplo n.º 7
0
        private static void Main()
        {
            var inputFolder    = ConfigurationManager.AppSettings["input"];
            var errorsFolder   = ConfigurationManager.AppSettings["errors"];
            var cnString       = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
            var infoQueueName  = ConfigurationManager.AppSettings["infoQueueName"];
            var stateQueueName = ConfigurationManager.AppSettings["stateQueueName"];
            var scanTimeout    = Convert.ToInt32(ConfigurationManager.AppSettings["scanTimeout"]);
            var stateInterval  = Convert.ToInt32(ConfigurationManager.AppSettings["stateInterval"]);
            var barcodeText    = ConfigurationManager.AppSettings["barcodeText"];

            var props = new ScanProperties(inputFolder, errorsFolder, infoQueueName, stateQueueName, cnString, scanTimeout, stateInterval, barcodeText);

            var logPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
            var logConfig = new LoggingConfiguration();
            var target    = new FileTarget
            {
                Name     = "Def",
                FileName = logPath,
                Layout   = "${date} ${message} ${onexception:inner=${exception:format=toString}}"
            };

            logConfig.AddTarget(target);
            logConfig.AddRuleForAllLevels(target);

            var logFactory    = new LogFactory(logConfig);
            var currentLogger = logFactory.GetLogger("Topshelf");

            Logger.Logger.SetLogger(currentLogger);

            HostFactory.Run(x =>
            {
                x.Service <ScannerService>(
                    conf =>
                {
                    conf.ConstructUsing(() => new ScannerService(props));
                    conf.WhenStarted(srv => srv.Start());
                    conf.WhenStopped(srv => srv.Stop());
                }
                    ).UseNLog(logFactory);

                x.SetDescription("ImgScaner Service");
                x.SetDisplayName("ImgScaner Service");
                x.SetServiceName("ImgScaner Service");
                x.RunAsLocalService();
            });
        }
Exemplo n.º 8
0
        public async Task <IEnumerable <PortStatusData> > ScanAsync(ScanProperties properties, CancellationToken cToken)
        {
            var host = Dns.GetHostEntry(Dns.GetHostName())
                       .AddressList[0];

            var taskList = new List <Task <PortStatusData> >((properties.MaxPort - properties.MinPort) + 1);

            for (var i = properties.MinPort; i < properties.MaxPort + 1; i++)
            {
                var portNumber = i;
                var t          = new Task <PortStatusData>(() => GetPortStatus(host, portNumber), cToken);
                t.Start();

                taskList.Add(t);
            }

            return(await Task.WhenAll(taskList));
        }
Exemplo n.º 9
0
        public void Test_ValidPortScanRange(int minPort, int maxPort)
        {
            var wpScanner  = new WebPortScanner();
            var totalPorts = (maxPort - minPort) + 1;

            var scanProperties = new ScanProperties
            {
                MinPort = minPort,
                MaxPort = maxPort
            };

            var actual = wpScanner.ScanAsync(scanProperties, CancellationToken.None)
                         .GetAwaiter()
                         .GetResult()
                         .Count();

            Assert.Equal(totalPorts, actual);
        }
Exemplo n.º 10
0
        private static void Main(string[] args)
        {
            var logFactory = GetLogFactory(args, @"C:\winserv\scanner.log");

            var logger   = HW.Logging.Logger.Current;
            var props    = BaseProperties.GetProperties(args);
            var logProps = new LogBaseProperties(props);

            logger.SetActualLogger(logFactory.GetLogger("HW.ScanService"), logProps.UseCodeRewritingLogs);


            logger.LogInfo("Main");
            foreach (var arg in args)
            {
                logger.LogInfo(arg);
            }

            var scanProperties = new ScanProperties(props);
            var container      = GetContainer(scanProperties, logProps);

            var serv = new ScannerService(container);

            if (args.Length > 0 && args[0].Equals("console"))
            {
                serv.StartScanning();

                Console.ReadKey();
                serv.StopScanning();
            }
            else //windows service
            {
                try
                {
                    ScannerService.Run(serv);
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.LogError(e);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public async Task <IEnumerable <PortStatusData> > ScanAsync(ScanProperties properties, CancellationToken cToken)
        {
            var serialPorts = GetPortNames(properties).ToList();

            if (serialPorts.Count < 1)
            {
                return(ArraySegment <PortStatusData> .Empty);
            }

            var taskList = new List <Task <PortStatusData> >((properties.MaxPort - properties.MinPort) + 1);

            for (var i = properties.MinPort; i < properties.MaxPort + 1; i++)
            {
                var index = i;
                var t     = new Task <PortStatusData>(() => GetPortStatus(serialPorts[index]), cToken);
                t.Start();

                taskList.Add(t);
            }

            return(await Task.WhenAll(taskList));
        }
Exemplo n.º 12
0
        public void Test_InvalidPortScanRange()
        {
            var spScanner = new SerialPortScanner();
            var cancellationTokenSource = new CancellationTokenSource();
            var cToken = cancellationTokenSource.Token;

            try
            {
                Assert.ThrowsAsync <ArgumentException>(async() =>
                {
                    var scanProperties = new ScanProperties(3, 1, PortStatus.Any);
                    await spScanner.ScanAsync(scanProperties, cToken);
                });
            }
            catch (Exception e)
            {
                Assert.True(false, e.Message);
            }
            finally
            {
                cancellationTokenSource.Dispose();
            }
        }
Exemplo n.º 13
0
        private static IContainer GetContainer(ScanProperties parameters, LogBaseProperties logBaseProperties)
        {
            var builder = new ContainerBuilder();

            builder.Register(c => new LoggerInterceptor(logBaseProperties.UseDynamicProxyLogs)).Named <IInterceptor>("logger-interceptor");


            builder.RegisterType <ScannerWorker>().As <IScannerWorker>().EnableInterfaceInterceptors().InterceptedBy("logger-interceptor");
            builder.RegisterType <Scanner>().As <IScanner>().EnableInterfaceInterceptors().InterceptedBy("logger-interceptor");
            builder.RegisterType <FileSystemHelper>().As <IFileSystemHelper>().EnableInterfaceInterceptors().InterceptedBy("logger-interceptor");
            builder.RegisterType <PdfAggregatorFilesHandler>().As <IPdfAggregatorFilesHandler>().EnableInterfaceInterceptors().InterceptedBy("logger-interceptor");
            builder.RegisterType <LocalFolderStorage>().As <IStorageService>().EnableInterfaceInterceptors().InterceptedBy("logger-interceptor");

            builder.RegisterInstance(HW.Logging.Logger.Current).As <WindowsServices.HW.Logging.ILogger>();
            builder.RegisterInstance(parameters).As <ScanProperties>();
            builder.RegisterInstance(parameters.ServiceProperties).As <ServiceProperties>();
            builder.RegisterInstance(logBaseProperties).As <LogBaseProperties>();


            var container = builder.Build();

            return(container);
        }
        public void Test_MaxPortLimit()
        {
            var wpScanner = new WebPortScanner();
            var cancellationTokenSource = new CancellationTokenSource();
            var cToken = cancellationTokenSource.Token;

            try
            {
                Assert.ThrowsAsync <ArgumentOutOfRangeException>(async() =>
                {
                    var scanProperties = new ScanProperties(10, 65536, PortStatus.Any);
                    await wpScanner.ScanAsync(scanProperties, cToken);
                });
            }
            catch (Exception e)
            {
                Assert.True(false, e.Message);
            }
            finally
            {
                cancellationTokenSource.Dispose();
            }
        }
Exemplo n.º 15
0
 public ScannerService(ScanProperties props)
 {
     _scanner = new Scanner(props);
 }
Exemplo n.º 16
0
 public LocalFolderStorage(ScanProperties props, ILogger logger)
 {
     _logger = logger;
     this._outputLocation = props.OutputLocation;
 }
Exemplo n.º 17
0
 private static IEnumerable <string> GetPortNames(ScanProperties properties)
 {
     return(SerialPort.GetPortNames()
            .Where(x => int.Parse(x.Substring(3)) >= properties.MinPort &&
                   int.Parse(x.Substring(3)) <= properties.MaxPort));
 }