Example #1
0
        static void Main(string[] args)
        {
            // start the service
            Console.WriteLine("Starting Communicator...");
            Manager manager = new Manager();

            if (manager.StartService())
            {
                Console.WriteLine("Communicator is started successfully");
            }
            else
            {
                Console.WriteLine("Communicator is started with errors");
            }

            // stop the service if 'x' is pressed or a stop file exists
            Console.WriteLine("Press 'x' or create 'commstop' file to stop Communicator");
            FileListener stopFileListener = new FileListener(Path.Combine(manager.AppDirs.CmdDir, "commstop"));

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X || stopFileListener.FileFound))
            {
                Thread.Sleep(ScadaUtils.ThreadDelay);
            }

            manager.StopService();
            stopFileListener.Terminate();
            stopFileListener.DeleteFile();
            Console.WriteLine("Communicator is stopped");
        }
Example #2
0
        public LoggerService GetDefaultLogger(bool enableTraceLogger = false)
        {
            LoggerService logger;
            var           loggerName = "DefaultLogger";

            if (!IsLoggerActive(loggerName))
            {
                lock (_padLockDefaultLogger)
                {
                    if (!IsLoggerActive(loggerName))
                    {
                        var debugListener = new FileListener(LoggerConfig.DefaultLoggerPath + "debug.txt");

                        CreateLogger(loggerName)
                        .AttachListener(LoggingLevel.Debug, debugListener);
                    }
                }

                if (enableTraceLogger)
                {
                    EnableTraceLogger();
                }
            }
            else if (!defaultTraceLoggerEnabled & enableTraceLogger)
            {
                EnableTraceLogger();
            }

            logger = GetLogger(loggerName);
            return(logger);
        }
Example #3
0
        public void Will_process_existing_files_first()
        {
            var location = @"d:\temp\S37";
            if (Directory.Exists(location))
                Directory.Delete(location, true);
            Directory.CreateDirectory(location);

            var reader = new FileListener(location);
            var range = Enumerable.Range(0, 5);
            foreach (var item in range)
            {
                File.WriteAllText(Path.Combine(location, String.Format("{0}.txt", item)), item.ToString());
                Thread.Sleep(100);
            }

            var stream = reader.GetFilesAsObservable();

            var background = Task.Run(() => Enumerable.Range(6, 10).ForEach(item =>
            {
                File.WriteAllText(Path.Combine(location, String.Format("{0}.txt", item)), item.ToString());
                Thread.Sleep(100);
            }));

            stream.Skip(5).Take(1)
                .Subscribe(first => {
                    Assert.AreEqual("6.txt", first);
                });
            background.Wait();
            Directory.Delete(location, true);
        }
Example #4
0
        /// <summary>
        /// The main entry point for the application
        /// <para>Основная точка входа для приложения</para>
        /// </summary>
        static void Main(string[] args)
        {
            // запуск агента
            Console.WriteLine("Starting Agent...");
            AgentManager agentManager = new AgentManager();

            if (agentManager.StartAgent())
            {
                Console.WriteLine("Agent is started successfully");
            }
            else
            {
                Console.WriteLine("Agent is started with errors");
            }

            Console.WriteLine("Press 'x' or create 'agentstop' file to stop Agent");

            // остановка службы при нажатии 'x' или обнаружении файла остановки
            FileListener stopFileListener = new FileListener(AppData.GetInstance().AppDirs.ConfigDir + "serverstop");

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X || stopFileListener.FileFound))
            {
                Thread.Sleep(ScadaUtils.ThreadDelay);
            }

            agentManager.StopAgent();
            stopFileListener.DeleteFile();
            stopFileListener.Abort();
            Console.WriteLine("Agent is stopped");
        }
Example #5
0
        private static void Main(string[] args)
        {
            // service start
            Console.WriteLine("Starting SCADA-Server...");
            var manager = new Manager();

            manager.StartService();

            Console.WriteLine("SCADA-Server is started");
            Console.WriteLine("Press 'x' or create 'serverstop' file to stop SCADA-Server");

            // stopping the service when you press 'x' or find the file stop
            FileListener stopFileListener =
                new FileListener("Cmd" + Path.DirectorySeparatorChar + "serverstop");

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X ||
                     stopFileListener.FileFound))
            {
                Thread.Sleep(ScadaUtils.ThreadDelay);
            }
            manager.StopService();
            stopFileListener.DeleteFile();
            stopFileListener.Abort();
            Console.WriteLine("SCADA-Server is stopped");
        }
        public async Task CatchAllFilter_AutoDelete_ProcessesAndDeletesFiles()
        {
            Mock <ITriggeredFunctionExecutor> mockExecutor   = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            ConcurrentBag <string>            processedFiles = new ConcurrentBag <string>();
            FunctionResult result = new FunctionResult(true);

            mockExecutor.Setup(p => p.TryExecuteAsync(It.IsAny <TriggeredFunctionData>(), It.IsAny <CancellationToken>())).ReturnsAsync(result);

            var options = new FilesOptions()
            {
                RootPath = rootPath
            };
            FileTriggerAttribute attribute = new FileTriggerAttribute(attributeSubPath, changeTypes: WatcherChangeTypes.Created, filter: "*.*", autoDelete: true);

            FileListener listener = new FileListener(new OptionsWrapper <FilesOptions>(options), attribute, mockExecutor.Object, new TestLogger("Test"), new DefaultFileProcessorFactory());
            await listener.StartAsync(CancellationToken.None);

            // create a few files with different extensions
            WriteTestFile("jpg");
            WriteTestFile("txt");
            WriteTestFile("png");

            // wait for the files to be processed fully and all files deleted (autoDelete = true)
            await TestHelpers.Await(() =>
            {
                return(Directory.EnumerateFiles(testFileDir).Count() == 0);
            });

            listener.Dispose();
        }
Example #7
0
        /// <summary>
        /// The main entry point for the application
        /// <para>The main entry point for the application</para>
        /// </summary>
        static void Main(string[] args)
        {
            // agent start
            Console.WriteLine("Starting Agent...");
            var agentManager = new AgentManager();

            if (agentManager.StartAgent())
            {
                Console.WriteLine("Agent is started successfully");
            }
            else
            {
                Console.WriteLine("Agent is started with errors");
            }

            Console.WriteLine("Press 'x' or create 'agentstop' file to stop Agent");

            // stopping the service when you press 'x' or find the file stop
            FileListener stopFileListener = new FileListener(AppData.GetInstance().AppDirs.ConfigDir + "serverstop");

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X || stopFileListener.FileFound))
            {
                Thread.Sleep(ScadaUtils.ThreadDelay);
            }

            agentManager.StopAgent();
            stopFileListener.DeleteFile();
            stopFileListener.Abort();
            Console.WriteLine("Agent is stopped");
        }
        public void NonExistingFile()
        {
            var v = new MockViewer();
            var f = new FileListener(@"c:\finns_inte.foo", 10, "foo", true);
            var s = new Session(f, v);

            s.Start();
            Thread.Sleep(500);
            s.Stop();
        }
Example #9
0
        public void FormatSimpleJson()
        {
            string msg          = "{\"component\": \"AutoCheckOrder\",\"environment\": \"BACKOFFICE\"}";
            string formattedMsg = "\r\n{\r\n\t\"component\": \"AutoCheckOrder\",\r\n\t\"environment\": \"BACKOFFICE\"\r\n}\r\n";
            var    listener     = new FileListener();

            listener.SetConfigValue("structured", "json");
            var f   = new StructuredMessageFormatter(msg, listener);
            var foo = f.Message();

            Assert.AreEqual(formattedMsg, foo);
        }
Example #10
0
    // Use this for initialization
    protected void Start()
    {
        lmbclicked      = false;
        textToSpeech    = GetComponent <TextToSpeech>();
        scribbler       = GetComponent <Scribbler>();
        highlightPoints = GetComponent <HighlightPoints>();
        //changeColor = GetComponent<ChangeColor>();
        if (character != null)
        {
            trackerClientSimpleRobot = character.GetComponent <TrackerClientSimpleRobot>();
            _rightHand = trackerClientSimpleRobot.getRightArm();
        }
        if (skeletonPlayer != null)
        {
            trackerClientRecorded = skeletonPlayer.GetComponent <TrackerClientRecorded>();
            fileListener          = skeletonPlayer.GetComponent <FileListener>();
        }
        clouds = GameObject.FindObjectsOfType <PointCloud>();

        textToSpeechButtonIsActive    = false;
        scribblerButtonIsActive       = false;
        highlightPointsButtonIsActive = false;
        changeColorButtonIsActive     = false;
        deleteButtonIsActive          = false;

        //Load menu buttons textures
        textToSpeechTextureActive   = Resources.Load("speechToTextActive") as Texture;
        textToSpeechTextureInactive = Resources.Load("speechToText") as Texture;

        scribblerTextureActive   = Resources.Load("scribblerActive") as Texture;
        scribblerTextureInactive = Resources.Load("scribbler") as Texture;

        highlightPointsTextureActive   = Resources.Load("highlightPointsActive") as Texture;
        highlightPointsTextureInactive = Resources.Load("highlightPoints") as Texture;

        changeColorTextureActive   = Resources.Load("changeColorActive") as Texture;
        changeColorTextureInactive = Resources.Load("changeColor") as Texture;

        deleteTextureActive   = Resources.Load("deleteActive") as Texture;
        deleteTextureInactive = Resources.Load("delete") as Texture;

        changeColorGO = GameObject.FindGameObjectWithTag("ColorPicker");
        changeColorGO.SetActive(false);

        duration = 0;

        durationGO = GameObject.FindGameObjectWithTag("Duration");
        durationGO.SetActive(false);
        isWheelActive = false;

        currentExecutionTime = 0.0f;
        currentCloud         = 0;
    }
        public void ChangeExcelPath(string newPath)
        {
            if (_excelDirectoryListener != null)
            {
                _excelDirectoryListener.Stop();
            }

            //  save
            Config.ExcelPath = newPath;
            JsonHelp.SaveFile(GlobalConfigPath, _globalConfig);

            _excelDirectoryListener = FileListener.FetchFileListener(Config.ExcelPath, OnExcelPathChange);

            ReloadExcelPath();
        }
        public GlobalDataManager()
        {
            string configPath = Directory.GetCurrentDirectory() + "/Config";

            if (!Directory.Exists(configPath))
            {
                Directory.CreateDirectory(configPath);
            }
            GlobalConfigPath = configPath + "/global.json";
            CodeKeyDataPath  = configPath + "/codekey.json";
            _templatePath    = configPath + "/Template";


            _excelDirectoryListener  = FileListener.FetchFileListener(Config.ExcelPath, OnExcelPathChange);
            _configDirectoryListener = FileListener.FetchFileListener(configPath, OnConfigPathChange);
        }
        public void ShowExistingFileData()
        {
            var v = new MockViewer();
            var f = createFile();

            File.WriteAllText(f, "some random text");
            var fl = new FileListener(f, 3, "foo", false);
            var s  = new Session(fl, v);

            s.Start();
            Application.DoEvents();
            Thread.Sleep(200);
            Application.DoEvents();
            Assert.IsTrue(v.ReceivedData.Count > 0);

            s.Stop();
        }
Example #14
0
        private void button3_Click(object sender, EventArgs e)
        {
            LoggerConfig.SetCustomVariable("testLol", "NintendoSwitch");

            var manager = LoggerManager.GetLoggerManager();

            var guidx = new FileListener(@"C:\Logs\$$[processname]$$\$$[timestamp=yyyy-MM-dd HH_mm_ss]$$\$$[custom=testLol]$$\custom.txt", "$$[message]$$");

            manager.CreateLogger("CustomTest")
            .AttachListener(LoggingLevel.Trace, guidx);
            var Logger = manager.GetLogger("CustomTest");

            Logger.Info("This is a custom variable test");

            DefaultLogger.Info("button3 clicked");
            Thread.Sleep(500);  // Give the logging service enough time to process the message before logger is actually removed
            manager.RemoveLogger("CustomTest");
        }
Example #15
0
        public void DontShowExistingFileData()
        {
            MockViewer v = new MockViewer();
            string     f = createFile();

            File.WriteAllText(f, "some random text");
            FileListener fl = new FileListener(f, 3, "foo", true);
            Session      s  = new Session(fl, v);

            s.Start();
            System.Windows.Forms.Application.DoEvents();
            Thread.Sleep(200);
            System.Windows.Forms.Application.DoEvents();

            Assert.AreEqual(0, v.ReceivedData.Count);

            s.Stop();
        }
Example #16
0
        static void Main(string[] args)
        {
            // запуск службы
            Console.WriteLine("Starting SCADA-Server...");
            Manager manager = new Manager();
            manager.StartService();

            Console.WriteLine("SCADA-Server is started");
            Console.WriteLine("Press 'x' or create 'serverstop' file to stop SCADA-Server");

            // остановка службы при нажатии 'x' или обнаружении файла остановки
            FileListener stopFileListener = new FileListener("Cmd" + Path.DirectorySeparatorChar + "serverstop");
            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X || stopFileListener.FileFound))
                Thread.Sleep(ScadaUtils.ThreadDelay);
            manager.StopService();
            stopFileListener.DeleteFile();
            stopFileListener.Abort();
            Console.WriteLine("SCADA-Server is stopped");
        }
Example #17
0
    private void LoadSkeletonData()
    {
        Dictionary <string, string> config = ConfigProperties.load(configFile);

        if (_skeletonPlayerGO == null)
        {
            _skeletonPlayerGO = new GameObject("SkeletonPlayer");
            _skeletonPlayerGO.transform.position   = Vector3.zero;
            _skeletonPlayerGO.transform.rotation   = Quaternion.identity;
            _skeletonPlayerGO.transform.localScale = Vector3.one;
            _skeletonPlayer = _skeletonPlayerGO.AddComponent <FileListener>();
        }
        _skeletonFileName = "";
        if (config.ContainsKey("skeletonFileName"))
        {
            _skeletonFileName = config["skeletonFileName"];
        }
        _skeletonPlayer.Initialize(_skeletonFileName);
        Debug.Log("has skele" + _skeletonPlayer.HasSkeleton());
    }
Example #18
0
        public void SerializeTheListener()
        {
            var original = new FileListener(@"c:\finns_inte.foo", 10, "foo", true);
            var xs       = new XmlSerializer(original.GetType());
            var sb       = new StringBuilder();
            var sw       = new StringWriter(sb);

            xs.Serialize(sw, original);

            var sr = new StringReader(sb.ToString());

            var copy = (FileListener)xs.Deserialize(sr);

            Assert.AreEqual(original.FileName, copy.FileName);
            Assert.AreEqual(original.MessagePrefix, copy.MessagePrefix);
            Assert.AreEqual(original.OnlyTail, copy.OnlyTail);
            Assert.AreEqual(original.PollInterval, copy.PollInterval);

            original.Dispose();
            copy.Dispose();
        }
Example #19
0
        public LoggerManager EnableTraceLogger()
        {
            if (!IsLoggerActive("DefaultLogger"))
            {
                GetDefaultLogger();
            }

            if (!defaultTraceLoggerEnabled)
            {
                lock (_padLockDefaultLogger)
                {
                    defaultTraceLoggerEnabled = true;
                    var traceListener = new FileListener(LoggerConfig.DefaultLoggerPath + "trace.txt");

                    var log = GetLogger("DefaultLogger");
                    log.AttachListener(LoggingLevel.Trace, traceListener);
                }
            }

            return(this);
        }
        public void ShowOnlyNewFileData()
        {
            var v = new MockViewer();
            var f = createFile();

            File.WriteAllText(f, "some random text");
            var fl = new FileListener(f, 3, "foo", true);
            var s  = new Session(fl, v);

            s.Start();
            Thread.Sleep(200);
            Application.DoEvents();

            File.AppendAllText(f, "some more random text");
            Thread.Sleep(200);

            Application.DoEvents();

            Assert.AreEqual(1, v.ReceivedData.Count);

            s.Stop();
        }
Example #21
0
        public void Will_process_oldest_files_first()
        {
            var location = @"d:\temp\S37";
            if (Directory.Exists(location))
                Directory.Delete(location, true);
            Directory.CreateDirectory(location);

            var reader = new FileListener(location);
            var range = Enumerable.Range(0, 5);
            foreach (var item in range)
            {
                File.WriteAllText(Path.Combine(location, String.Format("{0}.txt", item)), item.ToString());
                Thread.Sleep(100);
            }

            reader.GetFilesAsObservable()
                .Take(1)
                .Subscribe(first => {
                    Assert.AreEqual("0.txt", first);
                });

            Directory.Delete(location, true);
        }
        public void ShowNewAndOldFileData()
        {
            var v = new MockViewer();
            var f = createFile();

            File.WriteAllText(f, "some random text");
            var fl = new FileListener(f, 3, "foo", false);
            var s  = new Session(fl, v);

            s.Start();

            Application.DoEvents();
            Thread.Sleep(200); //If this is to short the test will fail.
            Application.DoEvents();

            File.AppendAllText(f, "some more random text");
            Thread.Sleep(200); //If this is to short the test will fail.
            Application.DoEvents();

            Assert.AreEqual(2, v.ReceivedData.Count);

            s.Stop();
        }
Example #23
0
        static void Main(string[] args)
        {
            // запуск службы
            Console.WriteLine("Starting SCADA-Server...");
            Manager manager = new Manager();

            manager.StartService();

            Console.WriteLine("SCADA-Server is started");
            Console.WriteLine("Press 'x' or create 'serverstop' file to stop SCADA-Server");

            // остановка службы при нажатии 'x' или обнаружении файла остановки
            FileListener stopFileListener = new FileListener("Cmd" + Path.DirectorySeparatorChar + "serverstop");

            while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X || stopFileListener.FileFound))
            {
                Thread.Sleep(ScadaUtils.ThreadDelay);
            }
            manager.StopService();
            stopFileListener.DeleteFile();
            stopFileListener.Abort();
            Console.WriteLine("SCADA-Server is stopped");
        }
Example #24
0
 public IntegrationService()
 {
     _reader = new FileListener(@"d:\temp\s37");
 }
Example #25
0
 public void Will_read_from_a_specific_location()
 {
     var expected = @"d:\temp";
     var reader = new FileListener(expected);
     Assert.AreEqual(expected, reader.Location);
 }
        public async Task ConcurrentListeners_ProcessFilesCorrectly(int concurrentListenerCount, int inputFileCount)
        {
            // mock out the executor so we can capture function invocations
            Mock <ITriggeredFunctionExecutor> mockExecutor   = new Mock <ITriggeredFunctionExecutor>(MockBehavior.Strict);
            ConcurrentBag <string>            processedFiles = new ConcurrentBag <string>();
            FunctionResult result = new FunctionResult(true);

            mockExecutor.Setup(p => p.TryExecuteAsync(It.IsAny <TriggeredFunctionData>(), It.IsAny <CancellationToken>()))
            .Callback <TriggeredFunctionData, CancellationToken>(async(mockData, mockToken) =>
            {
                await Task.Delay(50);
                FileSystemEventArgs fileEvent = mockData.TriggerValue as FileSystemEventArgs;
                processedFiles.Add(fileEvent.Name);
            })
            .ReturnsAsync(result);

            var options = new FilesOptions()
            {
                RootPath = rootPath
            };
            FileTriggerAttribute attribute = new FileTriggerAttribute(attributeSubPath, changeTypes: WatcherChangeTypes.Created | WatcherChangeTypes.Changed, filter: "*.dat");

            // create a bunch of listeners and start them
            CancellationTokenSource tokenSource          = new CancellationTokenSource();
            CancellationToken       cancellationToken    = tokenSource.Token;
            List <Task>             listenerStartupTasks = new List <Task>();
            List <FileListener>     listeners            = new List <FileListener>();

            for (int i = 0; i < concurrentListenerCount; i++)
            {
                FileListener listener = new FileListener(new OptionsWrapper <FilesOptions>(options), attribute, mockExecutor.Object, new TestLogger("Test"), new DefaultFileProcessorFactory());
                listeners.Add(listener);
                listenerStartupTasks.Add(listener.StartAsync(cancellationToken));
            }
            await Task.WhenAll(listenerStartupTasks);

            // now start creating files
            List <string> expectedFiles = new List <string>();

            for (int i = 0; i < inputFileCount; i++)
            {
                string file = WriteTestFile();
                await Task.Delay(50);

                expectedFiles.Add(Path.GetFileName(file));
            }

            // wait for all files to be processed
            await TestHelpers.Await(() =>
            {
                return(processedFiles.Count >= inputFileCount);
            });

            Assert.Equal(inputFileCount, processedFiles.Count);

            // verify that each file was only processed once
            Assert.True(expectedFiles.OrderBy(p => p).SequenceEqual(processedFiles.OrderBy(p => p)));
            Assert.Equal(expectedFiles.Count * 2, Directory.GetFiles(testFileDir).Length);

            // verify contents of each status file
            FileProcessor processor = listeners[0].Processor;

            foreach (string processedFile in processedFiles)
            {
                string statusFilePath = processor.GetStatusFile(Path.Combine(testFileDir, processedFile));

                string[] statusLines = File.ReadAllLines(statusFilePath);

                Assert.Equal(2, statusLines.Length);
                StatusFileEntry statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[0]);
                Assert.Equal(ProcessingState.Processing, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Created, statusEntry.ChangeType);

                statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[1]);
                Assert.Equal(ProcessingState.Processed, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Created, statusEntry.ChangeType);
            }

            // Now test concurrency handling for updates by updating some files
            // and verifying the updates are only processed once
            string[] filesToUpdate = processedFiles.Take(50).Select(p => Path.Combine(testFileDir, p)).ToArray();
            string   item;

            while (!processedFiles.IsEmpty)
            {
                processedFiles.TryTake(out item);
            }
            await Task.Delay(1000);

            foreach (string fileToUpdate in filesToUpdate)
            {
                await Task.Delay(50);

                File.AppendAllText(fileToUpdate, "update");
            }

            // wait for all files to be processed
            await TestHelpers.Await(() =>
            {
                return(processedFiles.Count >= filesToUpdate.Length);
            });

            Assert.Equal(filesToUpdate.Length, processedFiles.Count);
            Assert.Equal(expectedFiles.Count * 2, Directory.GetFiles(testFileDir).Length);

            // verify the status files are correct for each of the updated files
            foreach (string updatedFile in filesToUpdate)
            {
                string statusFilePath = processor.GetStatusFile(updatedFile);

                string[] statusLines = File.ReadAllLines(statusFilePath);

                Assert.Equal(4, statusLines.Length);
                StatusFileEntry statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[0]);
                Assert.Equal(ProcessingState.Processing, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Created, statusEntry.ChangeType);

                statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[1]);
                Assert.Equal(ProcessingState.Processed, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Created, statusEntry.ChangeType);

                statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[2]);
                Assert.Equal(ProcessingState.Processing, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Changed, statusEntry.ChangeType);

                statusEntry = JsonConvert.DeserializeObject <StatusFileEntry>(statusLines[3]);
                Assert.Equal(ProcessingState.Processed, statusEntry.State);
                Assert.Equal(WatcherChangeTypes.Changed, statusEntry.ChangeType);
            }

            // Now clean up all processed files
            processor.CleanupProcessedFiles();
            Assert.Empty(Directory.GetFiles(testFileDir));

            foreach (FileListener listener in listeners)
            {
                listener.Dispose();
            }
        }