Пример #1
0
        public void ChangedEvent_WithFileRenamed_ShouldSendFileToChannel()
        {
            //Arrange
            const string directory     = "C:\\MyFolder";
            var          configuration = new Mock <IConfiguration>();

            configuration.Setup(config => config["directory-path"]).Returns(directory);
            var channel = new Mock <IChannel>();

            var(fileSystem, fileSystemWatcher) = GenerateFileSystemMock(directory, false);

            // Act
            var directoryMonitor = new DirectoryMonitor(configuration.Object, channel.Object, fileSystem.Object);

            directoryMonitor.StartMonitoring();
            fileSystemWatcher.Raise(watcher => watcher.Renamed += null, new RenamedEventArgs(WatcherChangeTypes.Renamed, directory, "b.txt", "a.txt"));

            // Assert
            channel.Verify(chan => chan.AddFile(It.Is <RenameFileModel>(model =>
                                                                        model.RelativePath == "a.txt" &&
                                                                        model.NewFileName == "b.txt" &&
                                                                        model.FileAction == FileAction.Rename)), Times.Once);

            channel.VerifyNoOtherCalls();
        }
Пример #2
0
            protected async override Task ExecuteAsync()
            {
                if (Watch && FromFile != null)
                {
                    var filename = Path.GetFullPath(FromFile);
                    Console.WriteLine($"filename: {filename}");
                    await Root.Connection.ConcurrencyRetryBlock(Handler.SetMetadata);

                    using (var watcher = new DirectoryMonitor(System.IO.Path.GetFileName(filename)))
                    {
                        watcher.Change += (string changedFilePath) =>
                        {
                            Task.Run(async() =>
                            {
                                Console.WriteLine("Updating metadata");
                                await Root.Connection.ConcurrencyRetryBlock(Handler.SetMetadata);
                            });
                        };
                        watcher.Start();

                        while (true)
                        {
                            Console.WriteLine("watching");
                            Console.ReadLine();
                        }
                    }
                }
                else
                {
                    await Root.Connection.ConcurrencyRetryBlock(Handler.SetMetadata);
                }
            }
Пример #3
0
        public static XIMServer CreateXIMServer(ServiceMain service)
        {
            XIMServer s = new XIMServer();

            s._service = service;

            IEntity e = null;

            if (Program.ConfigMgt.Config.InboundFromFile)
            {
                e = new DirectoryMonitor(Program.ConfigMgt.Config.DirectoryConfig, Program.Log);
            }
            else
            {
                e = SocketEntity.Create(Program.ConfigMgt.Config.SocketConfig);
            }

            if (e == null)
            {
                return(null);
            }
            else
            {
                e.OnRequest += new RequestEventHandler(s._entity_OnRequest);
                s._entity    = e;
                return(s);
            }
        }
Пример #4
0
        private void StartMonit_Click(object sender, EventArgs e)
        {
            this.MonitFolder = this.textBox1.Text;
            try
            {
                if (!new DirectoryInfo(this.MonitFolder).Exists)
                {
                    MessageBox.Show("检测文件不存在,请核实");
                }
                else
                {
                    this.notifyIcon1.Text = "文件夹检测中";
                    this.MsgListBox.Items.Add("文件夹监测中......");
                    this.MsgListBox.SetSelected(this.MsgListBox.Items.Count - 1, true);
                    //Form1.watcher.Path = this.MonitFolder;
                    //Form1.watcher.EnableRaisingEvents = true;
                    this.StopMonit.Enabled  = true;
                    this.StartMonit.Enabled = false;
                    this.button1.Enabled    = false;
                    this.textBox1.Enabled   = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message);
            }
            IDirectoryMonitor iDM = new DirectoryMonitor(MonitFolder, textBox2.Text, this);

            iDM.Start();
        }
        void IFileChangeNotificationSystem.StopMonitoring(string filePath, Object state)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }
            if (state == null)
            {
                throw new ArgumentNullException("state");
            }
            FileChangeEventTarget target = state as FileChangeEventTarget;

            if (target == null)
            {
                throw new ArgumentException(R.Invalid_state, "state");
            }
            string           dir    = Path.GetDirectoryName(filePath);
            DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor;

            if (dirMon != null)
            {
                lock (dirMon) {
                    dirMon.Fsw.Changed -= target.ChangedHandler;
                    dirMon.Fsw.Created -= target.ChangedHandler;
                    dirMon.Fsw.Deleted -= target.ChangedHandler;
                    dirMon.Fsw.Error   -= target.ErrorHandler;
                    dirMon.Fsw.Renamed -= target.RenamedHandler;
                }
            }
        }
        public void TestFiltersFilesFromDirectory()
        {
            var monitor   = new DirectoryMonitor(DirectoryName, "*.csv");
            var fileNames = monitor.GetUnprocessedFileNames().OrderBy(s => s).ToList();

            Assert.AreEqual <int>(fileNames.Count, 1);
            Assert.AreEqual <string>(fileNames[0], TestFileName2);
        }
        /// <summary>
        /// The core logic for the application. Maintains a list of users and their interfaces and a/the server
        /// </summary>
        public ChatApplicationMain()
        {
            MessageParserServer.CreateServerDirectory();
            directoryMonitor = new DirectoryMonitor(Configuration.FIFO_FOLDER);
            var messageParserServer = new MessageParserServer(Configuration.BROADCAST_CHANNELNAME);

            serverChannel = new ChatChannel(Configuration.BROADCAST_CHANNELNAME, messageParserServer);
        }
Пример #8
0
        public FormDirectory()
        {
            InitializeComponent();

            DirectoryMonitorConfig cfg = new DirectoryMonitorConfig();

            _monitor            = new DirectoryMonitor(cfg, Program.Log);
            _monitor.OnRequest += new HYS.XmlAdapter.Common.RequestEventHandler(_monitor_OnRequest);
        }
        public void TestSeeFilesInDirectory()
        {
            var monitor   = new DirectoryMonitor(DirectoryName);
            var fileNames = monitor.GetUnprocessedFileNames().OrderBy(s => s).ToList();

            Assert.AreEqual <int>(fileNames.Count, 2);
            Assert.AreEqual <string>(fileNames[0], TestFileName1);
            Assert.AreEqual <string>(fileNames[1], TestFileName2);
        }
Пример #10
0
        private void CreateMonitor(MonitorConfig monitorConfig)
        {
            STFMonitorType monitorType = EnumUtil.Parse <STFMonitorType>(monitorConfig.MonitorType);

            StfMonitor monitor = null;

            switch (monitorType)
            {
            case STFMonitorType.OutputEmail:
                monitor = new OutputEmailMonitor(monitorConfig);
                break;

            case STFMonitorType.OutputDirectory:
                monitor = new OutputDirectoryMonitor(monitorConfig);
                break;

            case STFMonitorType.SharePoint:
                monitor = new SharePointMonitor(monitorConfig);
                break;

            case STFMonitorType.LANFax:
                monitor = new LANFaxMonitor(monitorConfig);
                break;

            case STFMonitorType.DigitalSendNotification:
                monitor = new DigitalSendNotificationMonitor(monitorConfig);
                break;

            case STFMonitorType.Directory:
                monitor = new DirectoryMonitor(monitorConfig);
                break;

            case STFMonitorType.AutoStore:
                monitor = new AutoStoreMonitor(monitorConfig);
                break;

            case STFMonitorType.DSSServer:
                monitor = new DigitalSendDatabaseMonitor(monitorConfig);
                break;

            case STFMonitorType.Hpcr:
                monitor = new HpcrDatabaseMonitor(monitorConfig);
                break;

            case STFMonitorType.EPrint:
                monitor = new EPrintJobMonitorService(monitorConfig);
                break;

            default:
                TraceFactory.Logger.Debug($"Unknown monitor type: {monitorConfig.MonitorType}");
                return;
            }

            monitor.RegisteredSessions = _registeredSessions;
            _monitors.Add(monitor);
            TraceFactory.Logger.Debug($"Added monitor for '{monitor.MonitorLocation}'.");
        }
        public void TestDoesNotSeeInvalidFiles()
        {
            var monitor = new DirectoryMonitor(DirectoryName);

            monitor.MarkFileNameAsInvalid(TestFileName1);
            var fileNames = monitor.GetUnprocessedFileNames().OrderBy(s => s).ToList();

            Assert.AreEqual <int>(fileNames.Count, 1);
            Assert.AreEqual <string>(fileNames[0], TestFileName2);
        }
Пример #12
0
        public static IApplicationBuilder UseGrpcMonitorProtoFileEnable(this IApplicationBuilder app)
        {
            DirectoryMonitor monitor = new DirectoryMonitor(GrpcServiceMethodFactory.ProtoPath, "*.proto");

            monitor.Change += (string filePath) =>
            {
                InnerLogger.Log(LoggerLevel.Debug, filePath);
                GrpcServiceMethodFactory.ProtoQueue.Enqueue(filePath);
            };
            monitor.Start();
            return(app);
        }
Пример #13
0
 /// <summary>
 /// 开启监控
 /// </summary>
 private void MonitorStart()
 {
     if (!Directory.Exists(ProtoPath))
     {
         Directory.CreateDirectory(ProtoPath);
     }
     monitor         = new DirectoryMonitor(ProtoPath, "*.proto");
     monitor.Change += (string filePath) =>
     {
         protoQueue.Enqueue(filePath);
     };
     monitor.Start();
 }
Пример #14
0
 /// <summary>
 /// 开启监控
 /// </summary>
 private void MonitorStart()
 {
     if (!Directory.Exists(PluginPath))
     {
         Directory.CreateDirectory(PluginPath);
     }
     monitor         = new DirectoryMonitor(PluginPath, "*.dll");
     monitor.Change += (string filePath) =>
     {
         LoadAsync(filePath);
     };
     monitor.Start();
 }
Пример #15
0
        void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
        {
            if (filePath is null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }
            if (onChangedCallback is null)
            {
                throw new ArgumentNullException(nameof(onChangedCallback));
            }

            FileInfo         fileInfo = new FileInfo(filePath);
            string           dir      = Path.GetDirectoryName(filePath);
            DirectoryMonitor dirMon   = _dirMonitors[dir] as DirectoryMonitor;

            if (dirMon == null)
            {
                lock (_lock)
                {
                    dirMon = _dirMonitors[dir] as DirectoryMonitor;
                    if (dirMon == null)
                    {
                        dirMon     = new DirectoryMonitor();
                        dirMon.Fsw = new FileSystemWatcher(dir);
                        dirMon.Fsw.NotifyFilter = NotifyFilters.FileName
                                                  | NotifyFilters.DirectoryName
                                                  | NotifyFilters.CreationTime
                                                  | NotifyFilters.Size
                                                  | NotifyFilters.LastWrite
                                                  | NotifyFilters.Security;
                        dirMon.Fsw.EnableRaisingEvents = true;
                    }
                    _dirMonitors[dir] = dirMon;
                }
            }

            FileChangeEventTarget target = new FileChangeEventTarget(fileInfo.Name, onChangedCallback);

            lock (dirMon)
            {
                dirMon.Fsw.Changed += target.ChangedHandler;
                dirMon.Fsw.Created += target.ChangedHandler;
                dirMon.Fsw.Deleted += target.ChangedHandler;
                dirMon.Fsw.Error   += target.ErrorHandler;
                dirMon.Fsw.Renamed += target.RenamedHandler;
            }

            state         = target;
            lastWriteTime = File.GetLastWriteTime(filePath);
            fileSize      = (fileInfo.Exists) ? fileInfo.Length : -1;
        }
Пример #16
0
        public DirectoryMonitorTests()
        {
            var timerFactory = new Func <ITimer>(() =>
            {
                var timer = new Mock <ITimer>();
                timers.Add(timer);
                return(timer.Object);
            });

            monitor = new DirectoryMonitor(watcher.Object, timerFactory)
            {
                FileCreationWaitTimeout = TimeSpan.FromSeconds(2)
            };
        }
Пример #17
0
        private void disposeLogger()
        {
            if (_jsonLogger != null)
            {
                _jsonLogger.Dispose();
                _jsonLogger = null;
            }

            if (_directoryMonitor != null)
            {
                _directoryMonitor.Dispose();
                _directoryMonitor = null;
            }
        }
Пример #18
0
        public void Identifies_changed_services_to_pipeline()
        {
            long   count   = 0;
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;

            using (var manualResetEvent = new ManualResetEvent(false))
                using (var dm = new DirectoryMonitor(".", _coordinator))
                {
                    var myChannel = new ChannelAdapter();
                    dm.Start();

                    myChannel.Connect(sc => sc.AddConsumerOf <ServiceFolderChanged>()
                                      .UsingConsumer(fsc =>
                    {
                        if (fsc.ServiceName.Equals("bottle", StringComparison.OrdinalIgnoreCase))
                        {
                            return;                                                                                             // gotta skip the bottle directory
                        }
                        long localCount = Interlocked.Increment(ref count);
                        //Console.WriteLine(fsc.ShelfName);
                        if (localCount % 2 == 0)
                        {
                            manualResetEvent.Set();
                        }
                    }));

                    //Console.WriteLine(baseDir);
                    //Console.WriteLine("-- Directories");

                    Directory.CreateDirectory(Path.Combine(baseDir, "Service1"));
                    Directory.CreateDirectory(Path.Combine(baseDir, "Service2"));

                    manualResetEvent.WaitOne(15.Seconds());
                    count.ShouldEqual(2);
                    manualResetEvent.Reset();

                    //Console.WriteLine("-- Files");

                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service1", "test.out")), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service2", "test.out")), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service1", "test2.out")), "Testing stuff");

                    manualResetEvent.WaitOne(10.Seconds());

                    //Console.WriteLine("-- Done");

                    count.ShouldEqual(4);
                }
        }
Пример #19
0
 public void Setup()
 {
     tmpDir = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ());
     Directory.CreateDirectory (tmpDir);
     addedChanged = 0;
     deletedChanged = 0;
     monitor = new DirectoryMonitor (tmpDir);
     monitor.FileChangedEvent += (changeType, path) => {
         if (changeType == FileChangeType.Created) {
             addedChanged++;
         } else if (changeType == FileChangeType.Deleted) {
             deletedChanged++;
         }
     };
 }
Пример #20
0
            protected override Task ExecuteAsync()
            {
                var organizationIdentifier = GetOrganizationIdentifier(Key);

                using (var watcher = new DirectoryMonitor(System.IO.Path.GetDirectoryName(Path)))
                {
                    watcher.Change += Watcher_Change;
                    watcher.Start();

                    while (true)
                    {
                        Console.WriteLine("watching");
                        Console.ReadLine();
                    }
                }
            }
Пример #21
0
        public MainWindow()
        {
            this.InitializeComponent();

            ApplyFormDimensions();
            PopulateTasksToExecute();

            DirMonitor = new DirectoryMonitor(
                ConfigManager.Instance.SettingsConfigurator.ConfigDataDirectory,
                FileSystemWatcher_Changed,
                FileSystemWatcher_Created,
                FileSystemWatcher_Renamed,
                FileSystemWatcher_Deleted);

            DirMonitor.StartMonitoring();
        }
Пример #22
0
        public void Constructor_WithCorrectArguments_ShouldProperlySetupFileSystemWatcher()
        {
            // Arrange
            const string directory     = "C:\\MyFolder";
            var          configuration = new Mock <IConfiguration>();

            configuration.Setup(config => config["directory-path"]).Returns(directory);
            var channel = new Mock <IChannel>();

            var(fileSystem, fileSystemWatcher) = GenerateFileSystemMock(directory, false);

            // Act
            var directoryMonitor = new DirectoryMonitor(configuration.Object, channel.Object, fileSystem.Object);

            // Assert
            fileSystemWatcher.VerifySet(watcher => watcher.IncludeSubdirectories = true);
        }
Пример #23
0
        private void setDirectoryMonitor()
        {
            if (_directoryMonitor != null)
            {
                _directoryMonitor.Dispose();
            }

            createDumperDirectory();

            _directoryMonitor = new DirectoryMonitor(ThisGuiModelData.DumperSettings.DumperDirectory, "*.json")
            {
                OnFileSystemChanged = file =>
                {
                    showFilesList();
                }
            };
        }
Пример #24
0
 public void Setup()
 {
     tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
     Directory.CreateDirectory(tmpDir);
     addedChanged              = 0;
     deletedChanged            = 0;
     monitor                   = new DirectoryMonitor(tmpDir);
     monitor.FileChangedEvent += (changeType, path) => {
         if (changeType == FileChangeType.Created)
         {
             addedChanged++;
         }
         else if (changeType == FileChangeType.Deleted)
         {
             deletedChanged++;
         }
     };
 }
        public void SeesOnlyNewFiles()
        {
            var monitor = new DirectoryMonitor(DirectoryName);

            monitor.MarkFileNameAsProcessed(TestFileName1);
            monitor.MarkFileNameAsInvalid(TestFileName2);
            var fileNames = monitor.GetUnprocessedFileNames().OrderBy(s => s).ToList();

            Assert.AreEqual <int>(fileNames.Count, 0);

            var fs3 = File.Create(TestFileName3);

            fs3.Close();

            fileNames = monitor.GetUnprocessedFileNames().OrderBy(s => s).ToList();
            Assert.AreEqual <int>(fileNames.Count, 1);
            Assert.AreEqual <string>(fileNames[0], TestFileName3);
        }
Пример #26
0
        void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }
            if (onChangedCallback == null)
            {
                throw new ArgumentNullException("onChangedCallback");
            }
            FileInfo         info          = new FileInfo(filePath);
            string           directoryName = Path.GetDirectoryName(filePath);
            DirectoryMonitor monitor       = this._dirMonitors[directoryName] as DirectoryMonitor;

            if (monitor == null)
            {
                lock (this._lock)
                {
                    monitor = this._dirMonitors[directoryName] as DirectoryMonitor;
                    if (monitor == null)
                    {
                        monitor = new DirectoryMonitor {
                            Fsw = new FileSystemWatcher(directoryName)
                        };
                        monitor.Fsw.NotifyFilter        = NotifyFilters.Security | NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.DirectoryName | NotifyFilters.FileName;
                        monitor.Fsw.EnableRaisingEvents = true;
                    }
                    this._dirMonitors[directoryName] = monitor;
                }
            }
            FileChangeEventTarget target = new FileChangeEventTarget(info.Name, onChangedCallback);

            lock (monitor)
            {
                monitor.Fsw.Changed += target.ChangedHandler;
                monitor.Fsw.Created += target.ChangedHandler;
                monitor.Fsw.Deleted += target.ChangedHandler;
                monitor.Fsw.Error   += target.ErrorHandler;
                monitor.Fsw.Renamed += target.RenamedHandler;
            }
            state         = target;
            lastWriteTime = File.GetLastWriteTime(filePath);
            fileSize      = info.Exists ? info.Length : -1L;
        }
Пример #27
0
        public void SetUp()
        {
            _monitor = new DirectoryMonitor(@"C:\temp");

            System.IO.FileStream stream = null;
            try
            {
                stream = System.IO.File.Create(@"C:\temp\testing.json");
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            System.Threading.Thread.Sleep(250);
        }
Пример #28
0
        public static bool SaveToFile(XIMOutboundConfig config, string content)
        {
            if (config == null || content == null)
            {
                return(false);
            }

            try
            {
                string pathData  = ConfigHelper.GetFullPath(config.TargetPath + "\\" + DataFolder);
                string pathIndex = ConfigHelper.GetFullPath(config.TargetPath + "\\" + IndexFolder);
                if (!Directory.Exists(pathData))
                {
                    Directory.CreateDirectory(pathData);
                }
                if (!Directory.Exists(pathIndex))
                {
                    Directory.CreateDirectory(pathIndex);
                }

                string fileName = config.FileNamePrefix + DirectoryMonitor.GetRandomString();

                string fnData = pathData + "\\" + fileName + config.FileNameSuffix;
                Program.Log.Write("Write to file: " + fnData);
                using (StreamWriter sw = File.CreateText(fnData))
                {
                    sw.Write(content);
                }

                string fnIndex = pathIndex + "\\" + fileName + IndexFileExtension;
                Program.Log.Write("Write to file: " + fnIndex);
                using (StreamWriter sw = File.CreateText(fnIndex))
                {
                }

                return(true);
            }
            catch (Exception err)
            {
                Program.Log.Write(err);
                return(false);
            }
        }
 void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
 {
     if (filePath == null)
     {
         throw new ArgumentNullException("filePath");
     }
     if (onChangedCallback == null)
     {
         throw new ArgumentNullException("onChangedCallback");
     }
     FileInfo info = new FileInfo(filePath);
     string directoryName = Path.GetDirectoryName(filePath);
     DirectoryMonitor monitor = this._dirMonitors[directoryName] as DirectoryMonitor;
     if (monitor == null)
     {
         lock (this._lock)
         {
             monitor = this._dirMonitors[directoryName] as DirectoryMonitor;
             if (monitor == null)
             {
                 monitor = new DirectoryMonitor {
                     Fsw = new FileSystemWatcher(directoryName)
                 };
                 monitor.Fsw.NotifyFilter = NotifyFilters.Security | NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.DirectoryName | NotifyFilters.FileName;
                 monitor.Fsw.EnableRaisingEvents = true;
             }
             this._dirMonitors[directoryName] = monitor;
         }
     }
     FileChangeEventTarget target = new FileChangeEventTarget(info.Name, onChangedCallback);
     lock (monitor)
     {
         monitor.Fsw.Changed += target.ChangedHandler;
         monitor.Fsw.Created += target.ChangedHandler;
         monitor.Fsw.Deleted += target.ChangedHandler;
         monitor.Fsw.Error += target.ErrorHandler;
         monitor.Fsw.Renamed += target.RenamedHandler;
     }
     state = target;
     lastWriteTime = File.GetLastWriteTime(filePath);
     fileSize = info.Exists ? info.Length : -1L;
 }
Пример #30
0
        internal static IMonitor CreateMonitor(MonitorType type, Options options, Action <string> outputFunction, CancellationToken token)
        {
            IMonitor monitor;

            switch (type)
            {
            case MonitorType.Timer:
                monitor = new TimerMonitor(options, outputFunction, token);
                break;

            case MonitorType.FileSystemWatcher:
                monitor = new DirectoryMonitor(options, outputFunction, token);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            return(monitor);
        }
Пример #31
0
        public void StartMonitoring_WithNonEmptyDirectory_ShouldSendAllFilesToChannel()
        {
            //Arrange
            const string directory     = "C:\\MyFolder";
            var          configuration = new Mock <IConfiguration>();

            configuration.Setup(config => config["directory-path"]).Returns(directory);
            var channel = new Mock <IChannel>();

            var(fileSystem, fileSystemWatcher) = GenerateFileSystemMock(directory, true);

            // Act
            var directoryMonitor = new DirectoryMonitor(configuration.Object, channel.Object, fileSystem.Object);

            directoryMonitor.StartMonitoring();

            //Assert
            fileSystemWatcher.VerifySet(watcher => watcher.EnableRaisingEvents = true);

            channel.Verify(chan => chan.AddFile(It.Is <FileModel>(model =>
                                                                  model.FullPath == "C:\\MyFolder\\a" &&
                                                                  model.RelativePath == "a" &&
                                                                  model.FileAction == FileAction.Create)), Times.Once);

            channel.Verify(chan => chan.AddFile(It.Is <FileModel>(model =>
                                                                  model.FullPath == "C:\\MyFolder\\b" &&
                                                                  model.RelativePath == "b" &&
                                                                  model.FileAction == FileAction.Create)), Times.Once);

            channel.Verify(chan => chan.AddFile(It.Is <FileModel>(model =>
                                                                  model.FullPath == "C:\\MyFolder\\a\\1.txt" &&
                                                                  model.RelativePath == "a\\1.txt" &&
                                                                  model.FileAction == FileAction.Change)), Times.Once);

            channel.Verify(chan => chan.AddFile(It.Is <FileModel>(model =>
                                                                  model.FullPath == "C:\\MyFolder\\2.mov" &&
                                                                  model.RelativePath == "2.mov" &&
                                                                  model.FileAction == FileAction.Change)), Times.Once);

            channel.VerifyNoOtherCalls();
        }
Пример #32
0
        public bool TryInit()
        {
            if (this.m_bInited)
                return true;

            this.m_bInited = true;

            ComparerRegister.Init();
            ComputerRegister.Init();

            Workspace.Instance.RegisterStuff();

            Config.LogInfo();

            if (string.IsNullOrEmpty(this.FilePath))
            {
                behaviac.Debug.LogError("No FilePath file is specified!");
                behaviac.Debug.Check(false);

                return false;
            }

            Debug.Log(string.Format("FilePath: {0}\n", this.FilePath));

            Debug.Check(!this.FilePath.EndsWith("\\"), "use '/' instead of '\\'");

            m_frameSinceStartup = -1;

#if !BEHAVIAC_RELEASE
            this.m_workspaceExportPathAbs = Path.GetFullPath(this.FilePath).Replace('\\', '/');
            if (!this.m_workspaceExportPathAbs.EndsWith("/"))
            {
                this.m_workspaceExportPathAbs += '/';
            }

#if BEHAVIAC_HOTRELOAD
            // set the file watcher
            if (Config.IsDesktop && behaviac.Config.IsHotReload)
            {
                if (this.FileFormat != EFileFormat.EFF_cs)
                {
                    if (m_DirectoryMonitor == null)
                    {
                        m_DirectoryMonitor = new DirectoryMonitor();
                        m_DirectoryMonitor.Changed += new DirectoryMonitor.FileSystemEvent(OnFileChanged);
                    }

                    string filter = "*.*";

                    if (this.FileFormat == EFileFormat.EFF_xml)
                    {
                        filter = "*.xml";
                    }
                    else if (this.FileFormat == EFileFormat.EFF_bson)
                    {
                        filter = "*.bson.bytes";
                    }

                    m_DirectoryMonitor.Start(this.FilePath, filter);
                }
            }

#endif//BEHAVIAC_HOTRELOAD

            //LogWorkspaceInfo();
#endif
            if (Config.IsSocketing)
            {
                bool isBlockSocket = Config.IsSocketBlocking;
                ushort port = Config.SocketPort;
                behaviac.SocketUtils.SetupConnection(isBlockSocket, port);
            }

            return true;
        }
Пример #33
0
        public void Identifies_changed_services_to_pipeline()
        {
            long count = 0;
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            using (var manualResetEvent = new ManualResetEvent(false))
            using (var dm = new DirectoryMonitor("."))
            {
                var myChannel = new ChannelAdapter();
                using (AddressRegistry.GetInboundServiceCoordinatorChannel(x => { }))
                {
                    dm.Start();

                    myChannel.Connect(sc => sc.AddConsumerOf<ServiceFolderChanged>()
                                                .UsingConsumer(fsc =>
                                                    {
                                                        if (fsc.ServiceName.Equals("bottle", StringComparison.OrdinalIgnoreCase))
                                                            return; // gotta skip the bottle directory

                                                        long localCount = Interlocked.Increment(ref count);
                                                        //Console.WriteLine(fsc.ShelfName);
                                                        if (localCount % 2 == 0)
                                                            manualResetEvent.Set();
                                                    }));

                    //Console.WriteLine(baseDir);
                    //Console.WriteLine("-- Directories");

                    Directory.CreateDirectory(Path.Combine(baseDir, "Service1"));
                    Directory.CreateDirectory(Path.Combine(baseDir, "Service2"));

                    manualResetEvent.WaitOne(15.Seconds());
                    count.ShouldEqual(2);
                    manualResetEvent.Reset();

                    //Console.WriteLine("-- Files");

                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service1", "test.out")), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service2", "test.out")), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, Path.Combine("Service1", "test2.out")), "Testing stuff");

                    manualResetEvent.WaitOne(10.Seconds());

                    //Console.WriteLine("-- Done");

                    count.ShouldEqual(4);
                }
            }
        }
Пример #34
0
		/**
		set the workspace settings
		
		'workspaceRootPath_' specifies the file path of of the exported path of the workspace file which is configured in the workspace file(.workspace.xml), 
		it can be either an absolute path or relative to the current path.
		'format' specify the format to use, xml or bson, 
		
		the default format is xml.

		@return false if 'path' is not a valid path holding valid data
		*/
        public static bool SetWorkspaceSettings(string workspaceExportPath, EFileFormat format)
        {
            Debug.Check(!workspaceExportPath.EndsWith("\\"), "use '/' instead of '\\'");

			bool bFirstTime = string.IsNullOrEmpty(ms_workspaceExportPath);

            ms_workspaceExportPath = workspaceExportPath;

            if (!ms_workspaceExportPath.EndsWith("/"))
            {
                ms_workspaceExportPath += '/';
            }

            fileFormat_ = format;

            if (string.IsNullOrEmpty(ms_workspaceExportPath))
            {
                behaviac.Debug.LogError("No workspace file is specified!");
                behaviac.Debug.Check(false);

                return false;
            }

            LoadWorkspaceAbsolutePath();

            ms_deltaFrames = 1;

            //////////////////////////////////////////////////////////
			//only register metas and others at the 1st time
			if (bFirstTime)
			{
				behaviac.Details.RegisterCompareValue();
	            behaviac.Details.RegisterComputeValue();
	            behaviac.Workspace.RegisterBehaviorNode();
	            behaviac.Workspace.RegisterMetas();
			}

#if !BEHAVIAC_RELEASE
#if BEHAVIAC_HOTRELOAD
            // set the file watcher
            if (Config.IsDesktop)
            {
                if (FileFormat != EFileFormat.EFF_cs)
                {
                    if (ms_DirectoryMonitor == null)
                    {
                        ms_DirectoryMonitor = new DirectoryMonitor();
                        ms_DirectoryMonitor.Changed += new DirectoryMonitor.FileSystemEvent(OnFileChanged);
                    }

                    string filter = "*.*";
                    if (FileFormat == EFileFormat.EFF_xml)
                    {
                        filter = "*.xml";
                    }
                    else if (FileFormat == EFileFormat.EFF_bson)
                    {
                        filter = "*.bson.bytes";
                    }

                    ms_DirectoryMonitor.Start(workspaceExportPath, filter);
                }
            }
#endif//BEHAVIAC_HOTRELOAD

			
			SocketUtils.SendWorkspaceSettings();
#endif

            return true;
        }
        void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out Object state, out DateTimeOffset lastWriteTime, out long fileSize) {
            if (filePath == null) {
                throw new ArgumentNullException("filePath");
            }
            if (onChangedCallback == null) {
                throw new ArgumentNullException("onChangedCallback");
            }
            FileInfo fileInfo = new FileInfo(filePath);
            string dir = Path.GetDirectoryName(filePath);
            DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor;
            if (dirMon == null) {
                lock (_lock) {
                    dirMon = _dirMonitors[dir] as DirectoryMonitor;
                    if (dirMon == null) {
                        dirMon = new DirectoryMonitor();
                        dirMon.Fsw = new FileSystemWatcher(dir);
                        dirMon.Fsw.NotifyFilter = NotifyFilters.FileName 
                                                  | NotifyFilters.DirectoryName 
                                                  | NotifyFilters.CreationTime 
                                                  | NotifyFilters.Size 
                                                  | NotifyFilters.LastWrite 
                                                  | NotifyFilters.Security;
                        dirMon.Fsw.EnableRaisingEvents = true;
                    }
                    _dirMonitors[dir] = dirMon;
                }
            }
            
            FileChangeEventTarget target = new FileChangeEventTarget(fileInfo.Name, onChangedCallback);

            lock (dirMon) {
                dirMon.Fsw.Changed += target.ChangedHandler;
                dirMon.Fsw.Created += target.ChangedHandler;
                dirMon.Fsw.Deleted += target.ChangedHandler;
                dirMon.Fsw.Error += target.ErrorHandler;
                dirMon.Fsw.Renamed += target.RenamedHandler;
            }

            state = target;
            lastWriteTime = File.GetLastWriteTime(filePath);
            fileSize = (fileInfo.Exists) ? fileInfo.Length : -1;
        }
Пример #36
0
 public SettingsWindowEventArgs(DirectoryMonitor directoryMonitor)
 {
     DirectoryMonitor = directoryMonitor;
 }
Пример #37
0
        public void Identifies_changed_services_to_pipeline()
        {
            long count = 0;
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            using (var manualResetEvent = new ManualResetEvent(false))
            using (var dm = new DirectoryMonitor("."))
            {
                var myChannel = new ChannelAdapter();
                using (WellknownAddresses.GetHostHost(myChannel))
                {
                    dm.Start();

                    myChannel.Connect(sc => sc.AddConsumerOf<FileSystemChange>()
                                                .UsingConsumer(fsc =>
                                                    {
                                                        long localCount = Interlocked.Increment(ref count);
                                                        Console.WriteLine(fsc.ShelfName);
                                                        if (localCount%2 == 0)
                                                            manualResetEvent.Set();
                                                    }));

                    Console.WriteLine(baseDir);
                    Console.WriteLine("-- Directories");

                    Directory.CreateDirectory(Path.Combine(baseDir, "Service1"));
                    Directory.CreateDirectory(Path.Combine(baseDir, "Service2"));

                    manualResetEvent.WaitOne(15.Seconds());
                    count.ShouldEqual(2);
                    manualResetEvent.Reset();

                    Console.WriteLine("-- Files");

                    File.AppendAllText(Path.Combine(baseDir, "Service1", "test.out"), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, "Service2", "test.out"), "Testing stuff");
                    File.AppendAllText(Path.Combine(baseDir, "Service1", "test2.out"), "Testing stuff");

                    manualResetEvent.WaitOne(10.Seconds());

                    Console.WriteLine("-- Done");

                    count.ShouldEqual(4);
                }
            }
        }
Пример #38
0
        private bool TryInit()
        {
            if (this.m_bInited)
            {
                return true;
            }

            this.m_bInited = true;

            if (string.IsNullOrEmpty(this.FilePath))
            {
                behaviac.Debug.LogError("No FilePath file is specified!");
                behaviac.Debug.Check(false);

                return false;
            }

            Debug.Log(string.Format("FilePath: {0}\n", this.FilePath));

            Debug.Check(!this.FilePath.EndsWith("\\"), "use '/' instead of '\\'");

            LoadWorkspaceAbsolutePath();

            m_frameSinceStartup = -1;

            //////////////////////////////////////////////////////////
            this.RegisterStuff();

            AgentProperties.RegisterTypes();
            AgentProperties.Load();

#if !BEHAVIAC_RELEASE
#if BEHAVIAC_HOTRELOAD
            // set the file watcher
            if (Config.IsDesktop && behaviac.Config.IsHotReload)
            {
                if (this.FileFormat != EFileFormat.EFF_cs)
                {
                    if (m_DirectoryMonitor == null)
                    {
                        m_DirectoryMonitor = new DirectoryMonitor();
                        m_DirectoryMonitor.Changed += new DirectoryMonitor.FileSystemEvent(OnFileChanged);
                    }

                    string filter = "*.*";

                    if (this.FileFormat == EFileFormat.EFF_xml)
                    {
                        filter = "*.xml";
                    }
                    else if (this.FileFormat == EFileFormat.EFF_bson)
                    {
                        filter = "*.bson.bytes";
                    }

                    m_DirectoryMonitor.Start(this.FilePath, filter);
                }
            }

#endif//BEHAVIAC_HOTRELOAD

            //LogWorkspaceInfo();
#endif
            if (Config.IsSocketing)
            {
                bool isBlockSocket = Config.IsSocketBlocking;
                ushort port = Config.SocketPort;
                behaviac.SocketUtils.SetupConnection(isBlockSocket, port);
            }

            return true;
        }