public void PopulateFromReflector()
        {
            string xml = @"<state><directory>c:\temp</directory></state>";

            state = (FileStateManager)NetReflector.Read(xml);
            Assert.AreEqual(@"c:\temp", state.StateFileDirectory);
        }
        public void LoadStateFileWithValid144Data()
        {
            var data = @"<?xml version=""1.0"" encoding=""utf-8""?>
<IntegrationResult xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <ProjectName>ccnetlive</ProjectName>
  <ProjectUrl>http://CRAIG-PC/ccnet</ProjectUrl>
  <BuildCondition>ForceBuild</BuildCondition>
  <Label>7</Label>
  <Parameters />
  <WorkingDirectory>e:\sourcecontrols\sourceforge\ccnetlive</WorkingDirectory>
  <ArtifactDirectory>e:\download-area\CCNetLive-Builds</ArtifactDirectory>
  <Status>Success</Status>
  <StartTime>2009-06-17T13:28:35.7652391+12:00</StartTime>
  <EndTime>2009-06-17T13:29:13.7824391+12:00</EndTime>
  <LastIntegrationStatus>Success</LastIntegrationStatus>
  <LastSuccessfulIntegrationLabel>7</LastSuccessfulIntegrationLabel>
  <FailureUsers />
  <FailureTasks />
</IntegrationResult>";

            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(fileSystem.Load(null)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(new StringReader(data));
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.LoadState(ProjectName);
        }
        public void LoadStateFileWithValid144Data()
        {
            var data = @"<?xml version=""1.0"" encoding=""utf-8""?>
<IntegrationResult xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <ProjectName>ccnetlive</ProjectName>
  <ProjectUrl>http://CRAIG-PC/ccnet</ProjectUrl>
  <BuildCondition>ForceBuild</BuildCondition>
  <Label>7</Label>
  <Parameters />
  <WorkingDirectory>e:\sourcecontrols\sourceforge\ccnetlive</WorkingDirectory>
  <ArtifactDirectory>e:\download-area\CCNetLive-Builds</ArtifactDirectory>
  <Status>Success</Status>
  <StartTime>2009-06-17T13:28:35.7652391+12:00</StartTime>
  <EndTime>2009-06-17T13:29:13.7824391+12:00</EndTime>
  <LastIntegrationStatus>Success</LastIntegrationStatus>
  <LastSuccessfulIntegrationLabel>7</LastSuccessfulIntegrationLabel>
  <FailureUsers />
  <FailureTasks />
</IntegrationResult>";

            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.Load(It.IsNotNull <string>())).Returns(new StringReader(data)).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.LoadState(ProjectName);
        }
        public void HasPreviousStateIsTrueIfStateFileExists()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.FileExists(It.IsNotNull <String>())).Returns(true).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);
            Assert.IsTrue(state.HasPreviousState(ProjectName));
        }
        public void HasPreviousStateIsTrueIfStateFileExists()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(fileSystem.FileExists(null)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(true);
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);
            Assert.IsTrue(state.HasPreviousState(ProjectName));
        }
        public void HandleExceptionLoadingStateFile()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.Load(It.IsNotNull <string>())).Throws(new CruiseControlException()).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);

            Assert.That(delegate { state.LoadState(ProjectName); }, Throws.TypeOf <CruiseControlException>());
        }
        public void HandleExceptionSavingStateFile()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(() => fileSystem.AtomicSave(string.Empty, string.Empty)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull(), Rhino.Mocks.Constraints.Is.Anything()).Throw(new CruiseControlException());
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);

            Assert.That(delegate { state.SaveState(result); }, Throws.TypeOf <CruiseControlException>());
        }
        public void HandleExceptionLoadingStateFile()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(fileSystem.Load(null)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Throw(new CruiseControlException());
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);

            Assert.That(delegate { state.LoadState(ProjectName); }, Throws.TypeOf <CruiseControlException>());
        }
        public void ShouldWriteXmlUsingUTF8Encoding()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(() => fileSystem.AtomicSave(string.Empty, string.Empty)).Constraints(Rhino.Mocks.Constraints.Is.NotNull(), new StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
            mocks.ReplayAll();

            result = IntegrationResultMother.CreateSuccessful();
            result.ArtifactDirectory = "artifactDir";
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void SaveWithInvalidDirectory()
        {
            string foldername = @"c:\CCNet_remove_invalid";

            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(delegate { fileSystem.EnsureFolderExists(foldername); });
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.StateFileDirectory = foldername;
        }
        public void SaveProjectWithManySpacesInName()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.AtomicSave(It.IsNotNull <string>(), It.IsAny <string>())).Verifiable();

            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = "my    project     with   many    spaces";
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void LoadStateThrowsAnExceptionWithInvalidData()
        {
            var data = @"<?xml version=""1.0"" encoding=""utf-8""?><garbage />";

            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(fileSystem.Load(null)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(new StringReader(data));
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);

            Assert.That(delegate { state.LoadState(ProjectName); }, Throws.TypeOf <CruiseControlException>());
        }
        public void LoadStateThrowsAnExceptionWithInvalidData()
        {
            var data = @"<?xml version=""1.0"" encoding=""utf-8""?><garbage />";

            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.Load(It.IsNotNull <string>())).Returns(new StringReader(data)).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);

            Assert.That(delegate { state.LoadState(ProjectName); }, Throws.TypeOf <CruiseControlException>());
        }
        public void AttemptToSaveWithInvalidXml()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(delegate { fileSystem.AtomicSave(string.Empty, string.Empty); }).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull(), Rhino.Mocks.Constraints.Is.Anything());
            mocks.ReplayAll();

            result       = IntegrationResultMother.CreateSuccessful();
            result.Label = "<&/<>";
            result.AddTaskResult("<badxml>>");
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void AttemptToSaveWithInvalidXml()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.AtomicSave(It.IsNotNull <string>(), It.IsAny <string>())).Verifiable();

            result       = IntegrationResultMother.CreateSuccessful();
            result.Label = "<&/<>";
            result.AddTaskResult("<badxml>>");
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void ShouldWriteXmlUsingUTF8Encoding()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.AtomicSave(It.IsNotNull <string>(), It.Is <string>(_content => _content.StartsWith("<?xml version=\"1.0\" encoding=\"utf-8\"?>"))))
            .Verifiable();

            result = IntegrationResultMother.CreateSuccessful();
            result.ArtifactDirectory = "artifactDir";
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void LoadShouldThrowExceptionIfStateFileDoesNotExist()
        {
            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.Load(It.IsNotNull <string>())).Throws(new FileNotFoundException()).Verifiable();

            state              = new FileStateManager(fileSystem, executionEnvironment);
            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = ProjectName;

            Assert.That(delegate { state.LoadState(ProjectName); },
                        Throws.TypeOf <CruiseControlException>().With.Property("InnerException").TypeOf <FileNotFoundException>());
        }
        public void SaveProjectWithManySpacesInName()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().
            Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(delegate { fileSystem.AtomicSave(string.Empty, string.Empty); }).IgnoreArguments().Constraints(
                Rhino.Mocks.Constraints.Is.NotNull(), Rhino.Mocks.Constraints.Is.Anything());
            mocks.ReplayAll();

            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = "my    project     with   many    spaces";
            state = new FileStateManager(fileSystem, executionEnvironment);
            state.SaveState(result);
        }
        public void LoadShouldThrowExceptionIfStateFileDoesNotExist()
        {
            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureFolderExists(applicationDataPath); });
            Expect.Call(fileSystem.Load(null)).IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Throw(new FileNotFoundException());
            mocks.ReplayAll();

            state              = new FileStateManager(fileSystem, executionEnvironment);
            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = ProjectName;

            Assert.That(delegate { state.LoadState(ProjectName); },
                        Throws.TypeOf <CruiseControlException>().With.Property("InnerException").TypeOf <FileNotFoundException>());
        }
        public void SaveWithInvalidDirectory()
        {
            string foldername = @"c:\CCNet_remove_invalid";

            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureFolderExists(applicationDataPath)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureGivenFolderExists(foldername)).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.StateFileDirectory = foldername;

            // get the value so that the folder is created
            foldername = state.StateFileDirectory;
        }
        public void SaveToNonExistingFolder()
        {
            string newDirectory = Directory.GetCurrentDirectory() + "\\NewDirectory";

            Assert.IsFalse(Directory.Exists(newDirectory), "The test directory should not exist");

            Mock.Get(executionEnvironment).Setup(_executionEnvironment => _executionEnvironment.GetDefaultProgramDataFolder(It.IsNotNull <ApplicationType>()))
            .Returns(applicationDataPath).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.EnsureGivenFolderExists(newDirectory)).Verifiable();
            Mock.Get(fileSystem).Setup(_fileSystem => _fileSystem.AtomicSave(It.IsNotNull <string>(), It.IsAny <string>())).Verifiable();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.StateFileDirectory = newDirectory;
            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = "my project";
            state.SaveState(result);
        }
        public void SaveToNonExistingFolder()
        {
            string newDirectory = Directory.GetCurrentDirectory() + "\\NewDirectory";

            Assert.IsFalse(Directory.Exists(newDirectory), "The test directory should not exist");

            Expect.Call(executionEnvironment.GetDefaultProgramDataFolder(ApplicationType.Server)).IgnoreArguments().
            Constraints(Rhino.Mocks.Constraints.Is.NotNull()).Return(applicationDataPath);
            Expect.Call(delegate { fileSystem.EnsureGivenFolderExists(newDirectory); });
            Expect.Call(delegate { fileSystem.AtomicSave(string.Empty, string.Empty); }).IgnoreArguments().Constraints(
                Rhino.Mocks.Constraints.Is.NotNull(), Rhino.Mocks.Constraints.Is.Anything());
            mocks.ReplayAll();

            state = new FileStateManager(fileSystem, executionEnvironment);
            state.StateFileDirectory = newDirectory;
            result             = IntegrationResultMother.CreateSuccessful();
            result.ProjectName = "my project";
            state.SaveState(result);
        }
        private void Init(FileSystemWatcher watcher, IEnumerable<FileInfo> files, int bufferTime, int intervalTime, Predicate<FileInfo> inactive)
        {
            this.states = new FileStateManager(files, inactive);

            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size;

            watcher.Created += this.OnObjectChanged;
            watcher.Renamed += this.OnObjectRenamed;
            watcher.Deleted += this.OnObjectChanged;

            IObservable<FileSystemEventArgs> listener = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(
                handler => (sender, e) => { handler(e); },
                h => watcher.Changed += h,
                h => watcher.Changed -= h);

            var triggerInterval = TimeSpan.FromMilliseconds(intervalTime);

            IObservable<IList<FileSystemEventArgs>> listener2 = Observable.Interval(triggerInterval)
                // .Debug(() => "Interval listener triggered {0}.".FormatWith(DateTime.Now.ToLongTimeString()))
                .SelectMany(l => this.states.Files)
                .Where(this.SizeChanged)
                .Select(file => new FileSystemEventArgs(WatcherChangeTypes.Changed, file.DirectoryName, file.Name))
                .Buffer(triggerInterval);

            this.subscription = listener
                .Buffer(TimeSpan.FromMilliseconds(bufferTime))
                .Merge(listener2)
                .Subscribe(OnObjectChanged);

            watcher.EnableRaisingEvents = true;

            this.watcher = watcher;

            Debug.WriteLine("Initialized \"{0}\" with {1} active files.".FormatWith(watcher.Path, this.states.Files.Count));
        }