public void GenerateFullManifest()
 {
     ManifestGenerator generator = new ManifestGenerator();
     IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "Somewhere", null);
     IntegrationSummary summary = new IntegrationSummary(IntegrationStatus.Success, "A Label", "Another Label", new DateTime(2009, 1, 1));
     IntegrationResult result = new IntegrationResult("Test project", "Working directory", "Artifact directory", request, summary);
     Modification modification1 = GenerateModification("first file", "Add");
     Modification modification2 = GenerateModification("second file", "Modify");
     result.Modifications = new Modification[] { modification1, modification2 };
     List<string> files = new List<string>();
     files.Add("first file");
     XmlDocument manifest = generator.Generate(result, files.ToArray());
     Assert.IsNotNull(manifest);
     string actualManifest = manifest.OuterXml;
     string expectedManifest = "<manifest>"  +
             "<header project=\"Test project\" label=\"A Label\" build=\"ForceBuild\" status=\"Unknown\">" +
                 "<modification user=\"johnDoe\" changeNumber=\"1\" time=\"2009-01-01T00:00:00\">" +
                     "<comment>A comment</comment>" +
                     "<file name=\"first file\" type=\"Add\" />" +
                     "<file name=\"second file\" type=\"Modify\" />" +
                 "</modification>" +
             "</header>" +
             "<file name=\"first file\" />" +
         "</manifest>";
     Assert.AreEqual(expectedManifest, actualManifest);
 }
Ejemplo n.º 2
0
        public void ShouldThrowExceptionWhenSimulateFailureIsTrue()
        {
            IntegrationResult result = new IntegrationResult();
            task.SimulateFailure = true;
            Assert.That(delegate { task.Run(result); }, Throws.TypeOf<Exception>());

        }
Ejemplo n.º 3
0
		public virtual void SetUp()
		{
			CreateProcessExecutorMock(VaultVersionChecker.DefaultExecutable);
			mockHistoryParser = new DynamicMock(typeof (IHistoryParser));
			vault = new VaultVersionChecker((IHistoryParser) mockHistoryParser.MockInstance, (ProcessExecutor) mockProcessExecutor.MockInstance, VaultVersionChecker.EForcedVaultVersion.Vault3);

			result = IntegrationResultMother.CreateSuccessful("foo");
			result.WorkingDirectory = this.DefaultWorkingDirectory;
		}
Ejemplo n.º 4
0
		public void PublishersShouldBeTasks()
		{
			IMock mock = new DynamicMock(typeof (ITask));
			IntegrationResult result = new IntegrationResult();
			mock.Expect("Run", result);

			ITask publisher = (ITask) mock.MockInstance;
			publisher.Run(result);
		}
		public void PassesThroughLabelSourceControl()
		{
			//// SETUP
			IntegrationResult result = new IntegrationResult();
			_mockSC.Expect("LabelSourceControl", result);

			//// EXECUTE
			_filteredSourceControl.LabelSourceControl(result);
		}
		public void PassesThroughGetSource()
		{
			//// SETUP
			IntegrationResult result = new IntegrationResult();
			_mockSC.Expect("GetSource", result);

			//// EXECUTE
			_filteredSourceControl.GetSource(result);
		}
Ejemplo n.º 7
0
		public void SetUp()
		{
			srcRoot = SystemPath.UniqueTempPath();
			pubRoot = SystemPath.UniqueTempPath();

			publisher = new BuildPublisher();
			publisher.PublishDir = pubRoot.ToString();
			publisher.SourceDir = srcRoot.ToString();
			result = IntegrationResultMother.CreateSuccessful("99");
			labelPubDir = pubRoot.Combine("99");
		}
Ejemplo n.º 8
0
 public IIntegrationResult StartNewIntegration()
 {
     currentResult = new IntegrationResult(project.Name, project.WorkingDirectory);
     currentResult.LastIntegrationStatus = LastIntegrationResult.Status;
     currentResult.BuildCondition = DetermineBuildCondition(BuildCondition.NoBuild);
     currentResult.Label = project.Labeller.Generate(LastIntegrationResult);
     currentResult.ArtifactDirectory = project.ArtifactDirectory;
     currentResult.ProjectUrl = project.WebURL;
     currentResult.LastSuccessfulIntegrationLabel = LastIntegrationResult.LastSuccessfulIntegrationLabel;
     return currentResult;
 }
		public void SavingCurrentIntegrationShouldSetItToLastIntegrationResult()
		{
			IIntegrationResult lastResult = new IntegrationResult();
			ExpectToLoadState(lastResult);

			IIntegrationResult expected = manager.StartNewIntegration(ModificationExistRequest());
			Assert.AreEqual(lastResult, manager.LastIntegrationResult);

			mockStateManager.Expect("SaveState", expected);
			manager.FinishIntegration();
			Assert.AreEqual(expected, manager.LastIntegrationResult);
		}
		public void LastIntegrationResultShouldBeLoadedOnlyOnceFromStateManager()
		{
			IntegrationResult expected = new IntegrationResult();
			ExpectToLoadState(expected);

			IIntegrationResult actual = manager.LastIntegrationResult;
			Assert.AreEqual(expected, actual);

			// re-request should not reload integration result
			actual = manager.LastIntegrationResult;
			Assert.AreEqual(expected, actual);
		}
Ejemplo n.º 11
0
        public void VerifyGoToBranchProcessInfoBasic()
        {
            IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "source", null);
            IntegrationSummary lastSummary =
                new IntegrationSummary(IntegrationStatus.Success, "label", "lastlabel", DateTime.Now);
            IntegrationResult result = new IntegrationResult("test", @"c:\workspace", @"c:\artifacts", request, lastSummary);

            PlasticSCM plasticscm = new PlasticSCM();
            NetReflector.Read(PLASTICSCM_XML, plasticscm);
            string expected = @"c:\plastic\client\cm.exe stb br:/main -repository=mainrep";
            ProcessInfo info = plasticscm.GoToBranchProcessInfo(result);
            Assert.AreEqual(expected, info.FileName + " " + info.Arguments);
        }
Ejemplo n.º 12
0
		public static string CreateExpectedBuildXml(IntegrationResult result, string expectedBuildOutput)
		{
			string error = (result.Status == IntegrationStatus.Failure) ? " error=\"true\"" : String.Empty;
			if (expectedBuildOutput == null)
			{
				return string.Format(@"<build date=""{0}"" buildtime=""00:00:00""{1} buildcondition=""{2}"" />", DateUtil.FormatDate(result.StartTime), error, result.BuildCondition);
			}
			else
			{
			    expectedBuildOutput = expectedBuildOutput.Replace("\r", string.Empty);
				return string.Format(@"<build date=""{0}"" buildtime=""00:00:00""{1} buildcondition=""{3}"">{2}</build>", DateUtil.FormatDate(result.StartTime), error, expectedBuildOutput, result.BuildCondition);
			}
		}
Ejemplo n.º 13
0
		public void VerifyNewGetSourceProcessInfoBasic()
		{
            IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "source", null);
		    IntegrationSummary lastSummary =
		        new IntegrationSummary(IntegrationStatus.Success, "label", "lastlabel", DateTime.Now);
		    IntegrationResult result = new IntegrationResult("test", @"c:\workspace", @"c:\artifacts", request, lastSummary);

		    PlasticSCM plasticscm = new PlasticSCM();
		    NetReflector.Read(PLASTICSCM_BASIC_XML, plasticscm);
		    string expected = @"cm update c:\workspace";
		    ProcessInfo info = plasticscm.NewGetSourceProcessInfo(result);
		    Assert.AreEqual(expected, info.FileName + " " + info.Arguments);
		}
        public void ShouldNotEncloseBuilderOutputInCDATAIfNotSingleRootedXml()
        {
            string nantOut = @"NAnt 0.85 (Build 0.85.1714.0; net-1.0.win32; nightly; 10/09/2004)
            Copyright (C) 2001-2004 Gerry Shaw
            http://nant.sourceforge.net

            <buildresults project=""test"" />";

            result = CreateIntegrationResult(IntegrationStatus.Success, false);
            result.AddTaskResult(nantOut);

            Assert.AreEqual(CreateExpectedBuildXml(result, nantOut), GenerateBuildOutput(result));
        }
Ejemplo n.º 15
0
		protected void SetUpFixtureData()
		{
			lastBuild = IntegrationResultMother.CreateSuccessful(CreateDateTime(12, 01, 00));
			thisBuild = IntegrationResultMother.CreateSuccessful(CreateDateTime(12, 02, 00));

			mods = new Modification[] { CreateModificationAtTime(12, 01, 30) };

			mockSourceControl = new DynamicMock(typeof (ISourceControl));
			mockSourceControl.Strict = true;
			mockDateTimeProvider = new DynamicMock(typeof (DateTimeProvider));
			mockDateTimeProvider.Strict = true;
			quietPeriod = new QuietPeriod((DateTimeProvider) mockDateTimeProvider.MockInstance);
		}
		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>());
		}
Ejemplo n.º 17
0
        public void VerifyCreateLabelProcessInfoWithAttributes()
        {
            IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "source", null);
            IntegrationSummary lastSummary = new IntegrationSummary(IntegrationStatus.Success, "label", "lastlabel", DateTime.Now);
            IntegrationResult result = new IntegrationResult("test", @"c:\workspace", @"c:\artifacts", request, lastSummary);
            result.Label = "1";

            //check with attributes
            PlasticSCM plasticscm = new PlasticSCM();
            NetReflector.Read(PLASTICSCM_XML, plasticscm);
            string expected = @"c:\plastic\client\cm.exe mklb BL1";
            ProcessInfo info = plasticscm.CreateLabelProcessInfo(result);
            Assert.AreEqual (expected, info.FileName + " " + info.Arguments);
        }
		private static void AddModifications(IntegrationResult result)
		{
			result.Modifications = new Modification[3];
			result.Modifications[0] = ModificationMother.CreateModification("fileName", "folderName",
																			new DateTime(2009, 1, 1), "userName",
																			"comment", "10", "email@address",
																			"http://url");
			result.Modifications[1] = ModificationMother.CreateModification("fileName", "folderName",
																			new DateTime(2009, 1, 3), "userName",
																			"comment", "30", "email@address",
																			"http://url");
			result.Modifications[2] = ModificationMother.CreateModification("fileName", "folderName",
																			new DateTime(2009, 1, 2), "userName",
																			"comment", "20", "email@address",
																			"http://url");
		}
        public void ShouldReadModificationFile()
        {
            // integration with modifications
            result = CreateSuccessfulWithModifications(DateTime.Now);
            writerTask.Run(result);


            // new integration without modifications, 
            // modifications to be read from the saved file
            result = CreateSuccessful(DateTime.Now.AddHours(1));
            Assert.AreEqual(0, result.Modifications.Length);

            // read the saved modifications into the current integration result
            readerTask.Run(result);

            Assert.AreEqual(2, result.Modifications.Length);

        }
        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);
        }
			public void SetUp()
			{
				publisher = new MyStatisticsPublisher();
				publisher.FileName = "buildstatistics.xml";
				processor = new BuildStatisticsProcessor();

				integrationTime = new TimeSpan(0, 3, 0);
				failedBuild = IntegrationResultMother.Create(false, now.Add(-integrationTime));
				failedBuild.ProjectName = "Statistics Publisher";
				failedBuild.EndTime = now;
				failedBuild.Label = failedLabel;

				successfulBuild = IntegrationResultMother.Create(true, now.Add(-integrationTime));
				successfulBuild.ArtifactDirectory = artifactDirectory;
				successfulBuild.ProjectName = "Statistics Publisher";
				successfulBuild.EndTime = now;
				successfulBuild.Label = successfulLabel;
			}
        public void ImportAbsoluteBasedManifest()
        {
            string sourceFile = Path.Combine(Path.GetTempPath(), "ImportManifest.xml");
            string expectedManifest = "<manifest>" +
                    "From a file" +
                "</manifest>";
            if (File.Exists(sourceFile)) File.Delete(sourceFile);
            File.WriteAllText(sourceFile, expectedManifest);

            ManifestImporter generator = new ManifestImporter();
            generator.FileName = sourceFile;
            IntegrationRequest request = new IntegrationRequest(BuildCondition.ForceBuild, "Somewhere", null);
            IntegrationSummary summary = new IntegrationSummary(IntegrationStatus.Success, "A Label", "Another Label", new DateTime(2009, 1, 1));
            IntegrationResult result = new IntegrationResult("Test project", "Working directory", "Artifact directory", request, summary);
            List<string> files = new List<string>();
            XmlDocument manifest = generator.Generate(result, files.ToArray());

            Assert.IsNotNull(manifest);
            string actualManifest = manifest.OuterXml;
            Assert.AreEqual(expectedManifest, actualManifest);
        }
        public void ShouldReadMultipleModificationFile()
        {

            // 1st integration with modifications
            result = CreateSuccessfulWithModifications(DateTime.Now);
            writerTask.Run(result);


            // 2nd integration with modifications
            result = CreateSuccessfulWithModifications(DateTime.Now.AddHours(1));
            writerTask.Run(result);


            // new integrationresult that should get the saved mods
            result = CreateSuccessful(DateTime.Now.AddHours(2));

            Assert.AreEqual(0, result.Modifications.Length);

            readerTask.Run(result);

            Assert.AreEqual(4, result.Modifications.Length);
        }
 public IIntegrationResult LoadState(string project)
 {
     var path = this.GeneratePath(project);
     using (var reader = new StreamReader(
         this.fileSystem.OpenInputStream(path)))
     {
         var status = (IntegrationStatus)
             Enum.Parse(typeof(IntegrationStatus), reader.ReadLine());
         var lastSummary = new IntegrationSummary(
             status,
             reader.ReadLine(),
             reader.ReadLine(),
             DateTime.Parse(reader.ReadLine()));
         var result = new IntegrationResult(
             project,
             reader.ReadLine(),
             reader.ReadLine(),
             null,
             lastSummary);
         return result;
     }
 }
		public void PassesThroughLabelSourceControl()
		{
			//// SETUP
			IntegrationResult result = new IntegrationResult();

			DynamicMock mockSC1 = new DynamicMock(typeof (ISourceControl));
			mockSC1.Expect("LabelSourceControl", result);

			DynamicMock mockSC2 = new DynamicMock(typeof (ISourceControl));
			mockSC2.Expect("LabelSourceControl", result);

			ISourceControl[] sourceControls = new ISourceControl[] {(ISourceControl) mockSC1.MockInstance, (ISourceControl) mockSC2.MockInstance};

			MultiSourceControl multiSourceControl = new MultiSourceControl();
			multiSourceControl.SourceControls = sourceControls;

			//// EXECUTE
			multiSourceControl.LabelSourceControl(result);

			//// VERIFY
			mockSC1.Verify();
			mockSC2.Verify();
		}
		public void ShouldGetSourceIfAutoGetSourceTrue()
		{
			DynamicMock executor = new DynamicMock(typeof(ProcessExecutor));
            ExternalSourceControl externalSC = new ExternalSourceControl((ProcessExecutor)executor.MockInstance);
            externalSC.AutoGetSource = true;
		    externalSC.Executable = "banana.bat";
		    externalSC.ArgString = @"arg1 ""arg2 is longer"" arg3";

		    IntegrationResult intResult = new IntegrationResult();
            intResult.StartTime = new DateTime(1959,9,11,7,53,0);
		    intResult.WorkingDirectory = @"C:\SomeDir\Or\Other";
            intResult.ProjectName = "MyProject";

			ProcessInfo expectedProcessRequest = new ProcessInfo(
                "banana.bat", 
                @"GETSOURCE ""C:\SomeDir\Or\Other"" ""1959-09-11 07:53:00"" arg1 ""arg2 is longer"" arg3",
                @"C:\SomeDir\Or\Other"
                );
			expectedProcessRequest.TimeOut = Timeout.DefaultTimeout.Millis;

			executor.ExpectAndReturn("Execute", new ProcessResult("foo", null, 0, false), expectedProcessRequest);
            externalSC.GetSource(intResult);
			executor.Verify();
		}
Ejemplo n.º 27
0
        public void ShouldNotCopyFilesIfBuildBrokenAndAlwaysCopyIsSetToFalse()
        {
            SystemPath subRoot = srcRoot.CreateSubDirectory("SubDir");
            SystemPath subSubRoot = subRoot.CreateSubDirectory("SubSubDir");
            srcRoot.CreateTextFile(fileName, fileContents);
            subRoot.CreateTextFile(fileName, fileContents);
            subSubRoot.CreateTextFile(fileName, fileContents);

            result = IntegrationResultMother.CreateFailed("99");

            publisher.Run(result);

            Assert.IsFalse(labelPubDir.Combine(fileName).Exists(), "File found in build number directory");
            SystemPath subPubDir = labelPubDir.Combine("SubDir");
            Assert.IsFalse(subPubDir.Combine(fileName).Exists(), "File found in sub directory");
            Assert.IsFalse(subPubDir.Combine("SubSubDir").Combine(fileName).Exists(), "File found in sub sub directory");
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Integrates the specified request.	
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public IIntegrationResult Integrate(IntegrationRequest request)
        {
            Log.Trace();

            

            this.target.InitialiseForBuild(request);
            var result = this.StartNewIntegration(request);

            IIntegrationResult lastResult = resultManager.LastIntegrationResult;
            CreateDirectoryIfItDoesntExist(result.WorkingDirectory);
            CreateDirectoryIfItDoesntExist(result.ArtifactDirectory);

            Log.Trace("Getting Modifications for project {0}", result.ProjectName);
            try
            {
                result.Modifications = GetModifications(lastResult, result);
            }
            catch (Exception error)
            {
                result.SourceControlError = error;
                result.LastBuildStatus = lastResult.HasSourceControlError ? lastResult.LastBuildStatus : lastResult.Status;
                Log.Warning(string.Format(System.Globalization.CultureInfo.CurrentCulture,"Source control failure (GetModifications): {0}", error.Message));
                if (request.PublishOnSourceControlException)
                {
                    result.ExceptionResult = error;
                    CompleteIntegration(result);
                }
            }

            var runBuild = false;
            try
            {
                // Check whether a build should be performed
                runBuild = (result.SourceControlError == null) && result.ShouldRunBuild();

                if (runBuild)
                {
                    Log.Info("Building: " + request);

                    target.ClearNotNeededMessages();


                    // hack : otherwise all labellers(CCnet and custom) should be altered, better do this in 1 place
                    // labelers only increase version if PREVIOUS result was ok
                    // they should also increase version if previous was exception, and the new
                    // build got past the getmodifications

                    Log.Trace("Creating Label for project {0}", result.ProjectName);

                    if (result.LastIntegrationStatus == IntegrationStatus.Exception)
                    {
                        IntegrationSummary isExceptionFix = new IntegrationSummary(IntegrationStatus.Success, result.LastIntegration.Label, result.LastIntegration.LastSuccessfulIntegrationLabel, result.LastIntegration.StartTime);
                        IIntegrationResult irExceptionFix = new IntegrationResult(result.ProjectName, result.WorkingDirectory, result.ArtifactDirectory, result.IntegrationRequest, isExceptionFix);
                        irExceptionFix.Modifications = result.Modifications;

                        target.CreateLabel(irExceptionFix);
                        result.Label = irExceptionFix.Label;
                    }
                    else
                    {
                        target.CreateLabel(result);
                    }

                    Log.Trace("Running tasks of project {0}", result.ProjectName);
                    this.GenerateSystemParameterValues(result); 
                    Build(result);
                }
                else if (lastResult.HasSourceControlError)
                {
                    // Reset to the last valid status
                    result.Status = lastResult.LastBuildStatus;
                    resultManager.FinishIntegration();
                }
            }
            catch (Exception ex)
            {
                Log.Debug("Exception caught: " + ex.Message);
                result.ExceptionResult = ex;
            }
            finally
            {
                if (runBuild)
                {
                    CompleteIntegration(result);
                }
            }

            this.target.Activity = ProjectActivity.Sleeping;
            return result;
        }
Ejemplo n.º 29
0
		private IIntegrationResult IntegrationResult(string commit)
		{
			IntegrationResult r = new IntegrationResult();
			r.SourceControlData.Add(new NameValuePair(GIT_COMMIT_KEY, commit));
			return r;
		}
Ejemplo n.º 30
0
        private void Integrate()
        {
            while (integrationQueue.IsBlocked)
                Thread.Sleep(200);

            IntegrationRequest ir = integrationQueue.GetNextRequest(project);
            if (ir != null)
            {
                IDisposable queueLock;
                if (!integrationQueue.TryLock(out queueLock))
                    return;

                using (queueLock)
                {
                    // Check to see if this integration request should proceed - Extension point
                    IntegrationStartedEventArgs.EventResult eventResult = FireIntegrationStarted(ir);
                    switch (eventResult)
                    {
                        case IntegrationStartedEventArgs.EventResult.Continue:
                            Log.Info(string.Format("Project: '{0}' is first in queue: '{1}' and shall start integration.",
                                                   project.Name, project.QueueName));

                            IntegrationStatus status = IntegrationStatus.Unknown;
                            IIntegrationResult result = new IntegrationResult();

                            try
                            {
                                ir.PublishOnSourceControlException = (AmountOfSourceControlExceptions == project.MaxSourceControlRetries)
                                                                      || (project.SourceControlErrorHandling == ThoughtWorks.CruiseControl.Core.Sourcecontrol.Common.SourceControlErrorHandlingPolicy.ReportEveryFailure);
                                result = project.Integrate(ir);
                                if (result != null) status = result.Status;
                            }
                            catch
                            {
                                status = IntegrationStatus.Exception;
                                throw;
                            }
                            finally
                            {
                                RemoveCompletedRequestFromQueue();

                                // Tell any extensions that an integration has completed
                                FireIntegrationCompleted(ir, status);

                                // handle post build : check what to do if source control errors occured
                                if (result != null)
                                {
                                    if (result.SourceControlError != null)
                                    {
                                        AmountOfSourceControlExceptions++;
                                    }
                                    else
                                    {
                                        AmountOfSourceControlExceptions = 0;
                                    }
                                }

                                if ((AmountOfSourceControlExceptions > project.MaxSourceControlRetries)
                                    && (project.SourceControlErrorHandling == ThoughtWorks.CruiseControl.Core.Sourcecontrol.Common.SourceControlErrorHandlingPolicy.ReportOnEveryRetryAmount))
                                {
                                    AmountOfSourceControlExceptions = 0;
                                }

                                if ((AmountOfSourceControlExceptions > project.MaxSourceControlRetries)
                                    && project.stopProjectOnReachingMaxSourceControlRetries)
                                {
                                    Stopped();
                                }
                            }
                            break;
                        case IntegrationStartedEventArgs.EventResult.Delay:
                            // Log that the request has been cancelled and delay until the request is cleared - otherwise
                            // stuck in an endless loop until the extensions allow the request through
                            Log.Info(string.Format("An external extension has delayed an integration - project '{0}' on queue '{1}'",
                                project.Name,
                                project.QueueName));
                            while (FireIntegrationStarted(ir) == IntegrationStartedEventArgs.EventResult.Delay)
                            {
                                Thread.Sleep(1000);
                            }
                            break;
                        case IntegrationStartedEventArgs.EventResult.Cancel:
                            Log.Info(string.Format("An external extension has cancelled an integration - project '{0}' on queue '{1}'",
                                project.Name,
                                project.QueueName));
                            RemoveCompletedRequestFromQueue();
                            FireIntegrationCompleted(ir, IntegrationStatus.Cancelled);
                            break;
                    }
                }
            }
            else
            {
                PollTriggers();
                // If a build is queued for this project we need to hang around until either:
                // - the build gets started by reaching it's turn on the queue
                // - the build gets cancelled from the queue
                // - the thread gets killed
                // However, if the queue is blocked, do not hang around - we need to exit, so that we can come back to the queue
                // after the lock has been released (otherwise we could get stuck here forever
                while (IsRunning && integrationQueue.HasItemPendingOnQueue(project) && !integrationQueue.IsBlocked)
                {
                    Thread.Sleep(200);
                }
            }
        }
        /// <summary>
        /// Integrates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public IIntegrationResult Integrate(IntegrationRequest request)
        {
            Log.Trace();



            this.target.InitialiseForBuild(request);
            var result = this.StartNewIntegration(request);

            IIntegrationResult lastResult = resultManager.LastIntegrationResult;

            CreateDirectoryIfItDoesntExist(result.WorkingDirectory);
            CreateDirectoryIfItDoesntExist(result.ArtifactDirectory);

            Log.Trace("Getting Modifications for project {0}", result.ProjectName);
            try
            {
                result.Modifications = GetModifications(lastResult, result);
            }
            catch (Exception error)
            {
                result.SourceControlError = error;
                result.LastBuildStatus    = lastResult.HasSourceControlError ? lastResult.LastBuildStatus : lastResult.Status;
                Log.Warning(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Source control failure (GetModifications): {0}", error.Message));
                if (request.PublishOnSourceControlException)
                {
                    result.ExceptionResult = error;
                    CompleteIntegration(result);
                }
            }

            var runBuild = false;

            try
            {
                // Check whether a build should be performed
                runBuild = (result.SourceControlError == null) && result.ShouldRunBuild();

                if (runBuild)
                {
                    Log.Info("Building: " + request);

                    target.ClearNotNeededMessages();


                    // hack : otherwise all labellers(CCnet and custom) should be altered, better do this in 1 place
                    // labelers only increase version if PREVIOUS result was ok
                    // they should also increase version if previous was exception, and the new
                    // build got past the getmodifications

                    Log.Trace("Creating Label for project {0}", result.ProjectName);

                    if (result.LastIntegrationStatus == IntegrationStatus.Exception)
                    {
                        IntegrationSummary isExceptionFix = new IntegrationSummary(IntegrationStatus.Success, result.LastIntegration.Label, result.LastIntegration.LastSuccessfulIntegrationLabel, result.LastIntegration.StartTime);
                        IIntegrationResult irExceptionFix = new IntegrationResult(result.ProjectName, result.WorkingDirectory, result.ArtifactDirectory, result.IntegrationRequest, isExceptionFix);
                        irExceptionFix.Modifications = result.Modifications;

                        target.CreateLabel(irExceptionFix);
                        result.Label = irExceptionFix.Label;
                    }
                    else
                    {
                        target.CreateLabel(result);
                    }

                    Log.Trace("Running tasks of project {0}", result.ProjectName);
                    this.GenerateSystemParameterValues(result);
                    Build(result);
                }
                else if (lastResult.HasSourceControlError)
                {
                    // Reset to the last valid status
                    result.Status = lastResult.LastBuildStatus;
                    resultManager.FinishIntegration();
                }
            }
            catch (Exception ex)
            {
                Log.Debug("Exception caught: " + ex.Message);
                result.ExceptionResult = ex;
            }
            finally
            {
                if (runBuild)
                {
                    CompleteIntegration(result);
                }
            }

            this.target.Activity = ProjectActivity.Sleeping;
            return(result);
        }
        private bool Integrate()
        {
            bool ran = false;

            while (integrationQueue.IsBlocked)
            {
                Thread.Sleep(200);
            }

            IntegrationRequest ir = integrationQueue.GetNextRequest(project);

            if (ir != null && IsRunning)
            {
                IDisposable queueLock;
                if (!integrationQueue.TryLock(out queueLock))
                {
                    return(false);
                }

                using (queueLock)
                {
                    // Check to see if this integration request should proceed - Extension point
                    IntegrationStartedEventArgs.EventResult eventResult = FireIntegrationStarted(ir);
                    switch (eventResult)
                    {
                    case IntegrationStartedEventArgs.EventResult.Continue:
                        Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Project: '{0}' is first in queue: '{1}' and shall start integration.",
                                               project.Name, project.QueueName));

                        IntegrationStatus  status = IntegrationStatus.Unknown;
                        IIntegrationResult result = new IntegrationResult();
                        ran = true;

                        try
                        {
                            ir.PublishOnSourceControlException = (AmountOfSourceControlExceptions == project.MaxSourceControlRetries) ||
                                                                 (project.SourceControlErrorHandling == ThoughtWorks.CruiseControl.Core.Sourcecontrol.Common.SourceControlErrorHandlingPolicy.ReportEveryFailure);
                            result = project.Integrate(ir);
                            if (result != null)
                            {
                                status = result.Status;
                            }
                        }
                        catch
                        {
                            status = IntegrationStatus.Exception;
                            throw;
                        }
                        finally
                        {
                            RemoveCompletedRequestFromQueue();

                            // Tell any extensions that an integration has completed
                            FireIntegrationCompleted(ir, status);

                            // handle post build : check what to do if source control errors occured
                            if (result != null)
                            {
                                if (result.SourceControlError != null)
                                {
                                    AmountOfSourceControlExceptions++;
                                }
                                else
                                {
                                    AmountOfSourceControlExceptions = 0;
                                }
                            }

                            if ((AmountOfSourceControlExceptions > project.MaxSourceControlRetries) &&
                                (project.SourceControlErrorHandling == ThoughtWorks.CruiseControl.Core.Sourcecontrol.Common.SourceControlErrorHandlingPolicy.ReportOnEveryRetryAmount))
                            {
                                AmountOfSourceControlExceptions = 0;
                            }


                            if ((AmountOfSourceControlExceptions > project.MaxSourceControlRetries) &&
                                project.StopProjectOnReachingMaxSourceControlRetries)
                            {
                                Stopped();
                            }
                        }
                        break;

                    case IntegrationStartedEventArgs.EventResult.Delay:
                        // Log that the request has been cancelled and delay until the request is cleared - otherwise
                        // stuck in an endless loop until the extensions allow the request through
                        Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture, "An external extension has delayed an integration - project '{0}' on queue '{1}'",
                                               project.Name,
                                               project.QueueName));
                        while (FireIntegrationStarted(ir) == IntegrationStartedEventArgs.EventResult.Delay)
                        {
                            Thread.Sleep(1000);
                        }
                        break;

                    case IntegrationStartedEventArgs.EventResult.Cancel:
                        Log.Info(string.Format(System.Globalization.CultureInfo.CurrentCulture, "An external extension has cancelled an integration - project '{0}' on queue '{1}'",
                                               project.Name,
                                               project.QueueName));
                        RemoveCompletedRequestFromQueue();
                        FireIntegrationCompleted(ir, IntegrationStatus.Cancelled);
                        break;
                    }
                }
            }
            else
            {
                PollTriggers();
                // If a build is queued for this project we need to hang around until either:
                // - the build gets started by reaching it's turn on the queue
                // - the build gets cancelled from the queue
                // - the thread gets killed
                // However, if the queue is blocked, do not hang around - we need to exit, so that we can come back to the queue
                // after the lock has been released (otherwise we could get stuck here forever
                while (IsRunning && integrationQueue.HasItemPendingOnQueue(project) && !integrationQueue.IsBlocked)
                {
                    Thread.Sleep(200);
                }
            }

            return(ran);
        }