Exemple #1
0
        public void CanBuildAndClean()
        {
            this.DuplicateTestDataToTestFolder(@"Integration\MsbuildIntegrationTests\SimpleMsi");

            var context = this.TestContext;
            string binPath = Path.Combine(context.TestDirectory, "bin\\");
            string objPath = Path.Combine(context.TestDirectory, "obj\\");

            // Build
            MSBuild msb = new MSBuild();
            msb.Properties.Add("WixToolPath", Settings.WixToolsDirectory);
            msb.Properties.Add("WixTargetsPath", Settings.WixTargetsPath);
            msb.Properties.Add("WixTasksPath", Settings.WixTasksPath);
            msb.ProjectFile = "SimpleMsi.wixproj";
            var result = msb.Run();

            Assert.Contains("Building target \"Compile\" completely.", result.StandardOutput);
            Assert.Contains("Building target \"Link\" completely.", result.StandardOutput);

            var built = Directory.GetFiles(binPath, "*", SearchOption.AllDirectories);
            var intermediate = Directory.GetFiles(objPath, "*", SearchOption.AllDirectories);
            Assert.NotEmpty(built);

            // Clean
            msb.Targets.Add("Clean");
            result = msb.Run();

            var cleanBin = Directory.GetFiles(binPath, "*", SearchOption.AllDirectories);
            var cleanObj = Directory.GetFiles(objPath, "*", SearchOption.AllDirectories);
            Assert.Empty(cleanBin);
            Assert.Empty(cleanObj);

            this.Complete();
        }
Exemple #2
0
        public void CanBuildAndBuildWithoutChanges()
        {
            this.DuplicateTestDataToTestFolder(@"Integration\MsbuildIntegrationTests\SimpleMsi");

            MSBuild msb = new MSBuild();
            msb.Properties.Add("WixToolPath", Settings.WixToolsDirectory);
            msb.Properties.Add("WixTargetsPath", Settings.WixTargetsPath);
            msb.Properties.Add("WixTasksPath", Settings.WixTasksPath);
            msb.ProjectFile = "SimpleMsi.wixproj";

            var result = msb.Run();
            Assert.Contains("Building target \"Compile\" completely.", result.StandardOutput);
            Assert.Contains("Building target \"Link\" completely.", result.StandardOutput);

            var context = this.TestContext;
            var firstPassFiles = Directory.GetFiles(context.TestDirectory, "*", SearchOption.AllDirectories).Select(p => new { Path = p, Hash = this.GetHash(p), Modified = File.GetLastWriteTime(p) }).ToList();

            result = msb.Run();
            Assert.Contains("Skipping target \"Compile\" because all output files are up-to-date with respect to the input files.", result.StandardOutput);
            Assert.Contains("Skipping target \"Link\" because all output files are up-to-date with respect to the input files.", result.StandardOutput);

            var secondPassFiles = Directory.GetFiles(context.TestDirectory, "*", SearchOption.AllDirectories).Select(p => new { Path = p, Hash = this.GetHash(p), Modified = File.GetLastWriteTime(p) }).ToList();
            foreach (var st in secondPassFiles)
            {
                var m = firstPassFiles.Where(f => f.Path == st.Path).SingleOrDefault();
                Assert.NotNull(m);
                Assert.Equal(m.Hash, st.Hash);
            }

            this.Complete();
        }
Exemple #3
0
        public override CommandResult Execute(params string[] args)
        {
            var newArgs = args.ToList();

            newArgs.Insert(0, FullPathProjectFile);

            var command = MSBuild.CreateCommandForTarget("publish", newArgs.ToArray());

            return(command.Execute());
        }
Exemple #4
0
        public PropertiesFrm(IEnvironment env, ITransfer pin)
        {
            InitializeComponent();
            Icon = Resource.Package_32;

            _env             = env;
            _msbuild         = MSBuild.MakeEvaluator(_env);
            _pin             = pin;
            _cacheProperties = new ConcurrentDictionary <string, IEnumerable <PropertyItem> >();
        }
Exemple #5
0
        public async Task Dependency_IsNotBuilt_WhenBuildingInsideVisualStudio(string target)
        {
            var projectPath = Assets.GetScenarioFilePath(
                "Dependency_IsNotBuilt_WhenBuildingInsideVisualStudio",
                @"NuGetPackage\NuGetPackage.nuproj");
            var properties = MSBuild.Properties.Default.AddRange(MSBuild.Properties.BuildingInsideVisualStudio);
            var result     = await MSBuild.ExecuteAsync(projectPath, target, properties);

            result.AssertSuccessfulBuild();
        }
Exemple #6
0
        public async Task Basic_EmptyProjectCannotBuild()
        {
            // This test focuses on a completely empty project.
            nuproj.RemoveItems(nuproj.GetItems("Content"));

            var result = await MSBuild.ExecuteAsync(nuproj.CreateProjectInstance(), this.logger);

            // Verify that the build fails and tells the user why.
            Assert.Equal(BuildResultCode.Failure, result.Result.OverallResult);
            Assert.NotEqual(0, result.ErrorEvents.Count());
        }
Exemple #7
0
        private BuildSystem GetBuildSystem()
        {
#if WIN
            var buildSystem = new MSBuild(projectDirectory, projectName, platform, customSolution);
#elif MAC
            var buildSystem = new MDTool(projectDirectory, projectName, platform, customSolution);
#else
            throw new NotSupportedException();
#endif
            buildSystem.Configuration = ConfigurationName;
            return(buildSystem);
        }
Exemple #8
0
        public async Task Dependency_NoDependencies_Fails()
        {
            var solutionPath = Assets.GetScenarioSolutionPath("Dependency_NoDependencies_Fails");
            var result       = await MSBuild.RebuildAsync(solutionPath);

            var error = result.ErrorEvents.Single();

            var expectedMessage = "Cannot create a package that has no dependencies nor content.";
            var actualMessage   = error.Message;

            Assert.Equal(expectedMessage, actualMessage);
        }
        public override async Task Build(string configuration, CancellationToken cancellationToken)
        {
            var outputPath = OutputDirectory.FullName + Path.DirectorySeparatorChar;
            var props      = new Dictionary <string, string>
            {
                { "OutputPath", outputPath },
                { "Configuration", string.IsNullOrEmpty(configuration) ? "Release" : configuration },
                { "Platform", "iPhoneSimulator" }
            };

            // msbuild ../sample/TestApp.iOS/TestApp.iOS.csproj /p:Platform=iPhoneSimulator /p:Configuration=Release /p:OutputPath=$UITESTPATH/bin/
            await MSBuild.Build(ProjectFile.FullName, OutputDirectory.Parent.Parent.FullName, props, cancellationToken).ConfigureAwait(false);
        }
Exemple #10
0
            public ToolContext(IEnvironment env)
            {
                Log.Trace("Initialization of the clean context for testing.");

                var soba = new Soba(MSBuild.MakeEvaluator(env, uvars), uvars);

                Bootloader._.Configure(soba);

                cloader   = soba;
                inspector = new Inspector(soba);
                script    = soba;
                msbuild   = soba.EvMSBuild;
            }
Exemple #11
0
        public override async Task Build(string configuration, CancellationToken cancellationToken)
        {
            var props = new Dictionary <string, string>
            {
                { "OutputPath", OutputDirectory.FullName },
                { "Configuration", string.IsNullOrEmpty(configuration) ? "Release" : configuration },
                { "AndroidPackageFormat", "apk" },
                { "AndroidSupportedAbis", "x86" }
            };

            // msbuild ../sample/TestApp.Android/TestApp.Android.csproj /p:Configuration=Release /p:AndroidPackageFormat=apk /p:AndroidSupportedAbis=x86 /p:OutputPath=$UITESTPATH/bin/ /t:SignAndroidPackage
            await MSBuild.Build(ProjectFile.FullName, OutputDirectory.Parent.Parent.FullName, props, cancellationToken, "SignAndroidPackage").ConfigureAwait(false);
        }
Exemple #12
0
        /// <param name="parser"></param>
        public StepStruct(MSBuild.Parser parser)
            : this()
        {
            try {
                namspace = parser.getProperty("RootNamespace");
            }
            catch(Exception ex) {
                Log.Debug("Wizard-Version: RootNamespace failed - `{0}`", ex.Message);
            }

            if(namspace == MSBuild.Parser.PROP_VALUE_DEFAULT) {
                namspace = "MyNamespace";
            }
        }
        public async Task Extensibility_LoadsDotUserFile()
        {
            var projectPath = Assets.GetScenarioFilePath(
                "Extensibility_LoadsDotUserFile",
                @"NuGetPackage\NuGetPackage.nuproj");
            var properties = MSBuild.Properties.Default;
            var result     = await MSBuild.ExecuteAsync(projectPath, "Rebuild", properties);

            result.AssertSuccessfulBuild();

            var warnings = result.WarningEvents.First();

            Assert.Equal("NuGetPackage.nuproj.user target imported", warnings.Message);
        }
        protected override ICommand CreateCommand(params string[] args)
        {
            var newArgs = new List <string>();

            newArgs.Add(FullPathProjectFile);

            if (_sources.Any())
            {
                newArgs.Add($"/p:RestoreSources={string.Join("%3B", _sources)}");
            }

            newArgs.AddRange(args);

            return(MSBuild.CreateCommandForTarget("restore", newArgs.ToArray()));
        }
Exemple #15
0
        public async Task Dependency_IsNotBuilt_WhenBuildingInsideVisualStudio(string target)
        {
            var properties = MSBuild.Properties.Default.AddRange(MSBuild.Properties.BuildingInsideVisualStudio);

            // we need to build dependency first
            await Scenario.RestoreAndExecuteAsync("ClassLibrary".ToSolutionTarget(target), properties);

            properties = properties.Add("CheckTarget", "true");
            var projectPath = Assets.GetScenarioFilePath(
                "Dependency_IsNotBuilt_WhenBuildingInsideVisualStudio",
                @"NuGetPackage\NuGetPackage.nuproj");
            var result = await MSBuild.ExecuteAsync(projectPath, target, properties);

            result.AssertSuccessfulBuild();
        }
        /// <inheritdoc />
        public Compiler(IAppConfigurator appConfigurator = null, ILogger logger = null) : base(appConfigurator, logger)
        {
            _appConfigurator = appConfigurator;

            Init();

            Nuget = new NuGet(AppConfigurator);
#pragma warning disable CS0618
            MsBuild = new MsBuild(AppConfigurator);
#pragma warning restore CS0618
            MSBuild    = new MSBuild(AppConfigurator);
            TestHelper = new TestHelper(AppConfigurator);

            //_logger = logger ?? AppConfigurator.Of<LogConfiguration>().GetLogger();
        }
Exemple #17
0
        public override CommandResult Execute(params string[] args)
        {
            var newArgs = new List <string>();

            newArgs.Add(FullPathProjectFile);

            if (_sources.Any())
            {
                newArgs.Add($"/p:RestoreSources={string.Join("%3B", _sources)}");
            }

            newArgs.AddRange(args);

            var command = MSBuild.CreateCommandForTarget("restore", newArgs.ToArray());

            return(command.Execute());
        }
Exemple #18
0
        public async Task ShouldBuildAndFindArtifact(bool provideSolutionPath)
        {
            await using var testSolution = await CopyTestAssets("democonsole");

            var projectPath = Path.Join(testSolution.Value, "democonsole");

            var msBuild  = new MSBuild();
            var buildRes = await msBuild.BuildAndGetArtifactPath(projectPath, provideSolutionPath?testSolution.Value : null);

            Assert.Equal(provideSolutionPath, buildRes.Success);

            if (buildRes.Success)
            {
                Assert.Equal($@"{projectPath}\bin\Debug", buildRes.Directory);
                Assert.Equal("democonsole.exe", buildRes.File);
            }
        }
Exemple #19
0
        public override CommandResult Execute(params string[] args)
        {
            var newArgs = new List <string>(args.Length + 2);

            newArgs.Add(FullPathProjectFile);
            newArgs.Add($"/p:ValueName={_valueName}");
            newArgs.AddRange(args);

            //  Override build target to write out DefineConstants value to a file in the output directory
            Directory.CreateDirectory(GetBaseIntermediateDirectory().FullName);
            string injectTargetPath = Path.Combine(
                GetBaseIntermediateDirectory().FullName,
                Path.GetFileName(ProjectFile) + ".WriteValuesToFile.g.targets");

            string linesAttribute = _valueType == ValueType.Property ?
                                    $"Lines=`$({_valueName})`" :
                                    $"Lines=`@({_valueName})`";

            string injectTargetContents =
                @"<Project ToolsVersion=`14.0` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
  <PropertyGroup>
    <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
  </PropertyGroup>
  <Target Name=`WriteValuesToFile` " + (ShouldCompile ? $"DependsOnTargets=`{DependsOnTargets}`" : "") + $@">
    <WriteLinesToFile
      File=`bin\$(Configuration)\$(TargetFramework)\{_valueName}Values.txt`
      {linesAttribute}
      Overwrite=`true`
      Encoding=`Unicode`
      />
  </Target>
</Project>";

            injectTargetContents = injectTargetContents.Replace('`', '"');

            File.WriteAllText(injectTargetPath, injectTargetContents);

            var outputDirectory = GetOutputDirectory(_targetFramework);

            outputDirectory.Create();

            var command = MSBuild.CreateCommandForTarget("WriteValuesToFile", newArgs.ToArray());

            return(command.Execute());
        }
        /// <param name="type">The type of step.</param>
        /// <returns></returns>
        protected IStep getStep(StepsType type)
        {
            if (steps.ContainsKey(type))
            {
                return(steps[type]);
            }

            switch (type)
            {
            case StepsType.Gen: {
                steps[type] = new StepGen();
                return(steps[type]);
            }

            case StepsType.Struct: {
                steps[type] = new StepStruct(MSBuild.MakeEvaluator(env))
                {
                    fnumber = StepStruct.NumberType.NativeStruct
                };
                return(steps[type]);
            }

            case StepsType.DirectRepl: {
                steps[type] = new StepRepl();
                return(steps[type]);
            }

            case StepsType.CfgData: {
                steps[type] = new StepCfgData();
                return(steps[type]);
            }

            case StepsType.Fields: {
                steps[type] = new StepFields();
                return(steps[type]);
            }

            case StepsType.Final:
            {
                steps[type] = new StepFinal(this);
                return(steps[type]);
            }
            }
            throw new NotSupportedException($"getStep: the type - `{type}` is not found.");
        }
Exemple #21
0
        public async Task IncrementalBuild_NuSpecIsNotUpdated_WhenNothingChanged()
        {
            var solutionPath = Assets.GetScenarioSolutionPath("IncrementalBuild_NuSpecIsNotUpdated");
            var projectPath  = Path.GetDirectoryName(solutionPath);
            var nuspecFile   = Path.Combine(projectPath, @"NuGetPackage\obj\Debug\NuGetPackage.nuspec");

            // Perform first build

            var result1 = await MSBuild.ExecuteAsync(solutionPath, "Build");

            result1.AssertSuccessfulBuild();

            // Get file stamp of the first nuspec file
            //
            // NOTE: We're asserting that the file exists because otherwise if the file doesn't
            //       exist FileInfo will simply return a placeholder value.

            var fileInfo1 = new FileInfo(nuspecFile);

            Assert.True(fileInfo1.Exists);

            var lastWriteTime1 = fileInfo1.LastWriteTimeUtc;

            // Wait for short period

            await Task.Delay(TimeSpan.FromMilliseconds(300));

            // Perform second build

            var result2 = await MSBuild.ExecuteAsync(solutionPath, "Build");

            result2.AssertSuccessfulBuild();

            // Get file stamp of the nuspec file for the second build

            var fileInfo2 = new FileInfo(nuspecFile);

            Assert.True(fileInfo2.Exists);

            var lastWriteTime2 = fileInfo2.LastWriteTimeUtc;

            // The file stamps should match

            Assert.Equal(lastWriteTime1, lastWriteTime2);
        }
Exemple #22
0
        public async Task Basic_SetIntermediateOutputPathProperty()
        {
            var intermediateOutputPath = @"foo\bar\";

            nuproj.CreateMockContentFiles();
            nuproj.SetGlobalProperty("IntermediateOutputPath", intermediateOutputPath);

            var result = await MSBuild.ExecuteAsync(nuproj.CreateProjectInstance(), this.logger);

            result.AssertSuccessfulBuild();

            var expectedNuSpecFileName = string.Format(CultureInfo.InvariantCulture, "{0}.nuspec", nuproj.GetPropertyValue("Id"));
            var nuprojFileName         = Path.GetFileNameWithoutExtension(nuproj.FullPath);
            var expectedNuSpecPath     = Path.Combine(intermediateOutputPath, expectedNuSpecFileName);
            var actualNuSpecPath       = await nuproj.GetNuSpecPathAsync();

            Assert.Equal(expectedNuSpecPath, actualNuSpecPath, StringComparer.InvariantCultureIgnoreCase);
        }
        public async Task PackageIdentity_GetPackageIdentity_ResturnsCorrectValue(string scenarioName, string projectToBuild, string identity)
        {
            const string target = "GetPackageIdentity";

            // Arange
            // by convention, all scenarios should be in directory
            var solutionDir = Assets.GetScenarioDirectory(scenarioName);

            var projectPath = Path.Combine(solutionDir, projectToBuild);

            // Act
            var result = await MSBuild.ExecuteAsync(projectPath, target);

            // Assert
            result.AssertSuccessfulBuild();
            Assert.Single(result.Result.ResultsByTarget[target].Items);
            Assert.Equal(result.Result.ResultsByTarget[target].Items[0].ItemSpec, identity);
        }
Exemple #24
0
        public async Task Basic_SetOutDirProperty()
        {
            var outDir = @"foo\bar\";

            nuproj.CreateMockContentFiles();
            nuproj.SetGlobalProperty("OutDir", outDir);

            var result = await MSBuild.ExecuteAsync(nuproj.CreateProjectInstance(), this.logger);

            result.AssertSuccessfulBuild();

            var expectedNuPkgFileName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.nupkg", nuproj.GetPropertyValue("Id"), nuproj.GetPropertyValue("Version"));
            var nuprojDirectoryName   = Path.GetDirectoryName(nuproj.FullPath);
            var nuprojFileName        = Path.GetFileNameWithoutExtension(nuproj.FullPath);
            var expectedNuPkgPath     = Path.Combine(nuprojDirectoryName, outDir, expectedNuPkgFileName);
            var actualNuPkgPath       = await nuproj.GetNuPkgPathAsync();

            Assert.Equal(expectedNuPkgPath, actualNuPkgPath, StringComparer.InvariantCultureIgnoreCase);
        }
Exemple #25
0
        private List <PropertyItem> getMSBProperties(string project)
        {
            string key = project;

            if (String.IsNullOrEmpty(key))
            {
                key = "default";
            }

            if (!pcache.ContainsKey(key))
            {
                if (MSBuild == null)
                {
                    return(new List <PropertyItem>());
                }
                pcache[key] = MSBuild.listProperties(project);
                Log.Debug("Properties has been saved in cache ['{0}']", key);
            }
            return(pcache[key]);
        }
Exemple #26
0
        public void Build()
        {
            if (!BuildAfterCodeGenerationIsCompleted)
            {
                return;
            }

            foreach (var data in Queue)
            {
                var fileName = Path.GetFileName(data.ProjectFilePath);

                Trace("Compile started." + fileName);
                MSBuild.Build(data);
                if (data.BuildError == null)
                {
                    Trace($"Compile successfully finished. {fileName}");
                }
                else
                {
                    OnError(data.BuildError);
                }
            }
        }
Exemple #27
0
        public void CanBuildAndClean()
        {
            this.DuplicateTestDataToTestFolder(@"Integration\MsbuildIntegrationTests\SimpleMsi");

            var    context = this.TestContext;
            string binPath = Path.Combine(context.TestDirectory, "bin\\");
            string objPath = Path.Combine(context.TestDirectory, "obj\\");

            // Build
            MSBuild msb = new MSBuild();

            msb.Properties.Add("WixToolPath", Settings.WixToolsDirectory);
            msb.Properties.Add("WixTargetsPath", Settings.WixTargetsPath);
            msb.Properties.Add("WixTasksPath", Settings.WixTasksPath);
            msb.ProjectFile = "SimpleMsi.wixproj";
            var result = msb.Run();

            Assert.Contains("Building target \"Compile\" completely.", result.StandardOutput);
            Assert.Contains("Building target \"Link\" completely.", result.StandardOutput);

            var built        = Directory.GetFiles(binPath, "*", SearchOption.AllDirectories);
            var intermediate = Directory.GetFiles(objPath, "*", SearchOption.AllDirectories);

            Assert.NotEmpty(built);

            // Clean
            msb.Targets.Add("Clean");
            result = msb.Run();

            var cleanBin = Directory.GetFiles(binPath, "*", SearchOption.AllDirectories);
            var cleanObj = Directory.GetFiles(objPath, "*", SearchOption.AllDirectories);

            Assert.Empty(cleanBin);
            Assert.Empty(cleanObj);

            this.Complete();
        }
Exemple #28
0
        public void JustCompile(string fileName)
        {
            var project = FromRootDirectory($"Data\\Source\\{fileName}");
            var target = FromRootDirectory($"Data\\Target\\{MethodBase.GetCurrentMethod().Name}");

            ZipFile.ExtractToDirectory(project, target);

            var solution =
                FromRootDirectory(
                    $"Data\\Target\\{MethodBase.GetCurrentMethod().Name}\\{Path.GetFileNameWithoutExtension(fileName)}{".sln"}");

            var build = new MSBuild()
            {
                ProjectFile = solution
            };

            var app = new WorkflowTestApplication(build);

            var result = app.Run(_designerOptionsExtensions);

            Debug.WriteLine(result.Outputs["Result"]);

            Assert.IsTrue(result.Exception == null, "The execution an exception occured");
        }
        public void CompileAllCommitAndCopy()
        {
            _git.FetchAll();

            var commitList = GetCommitList().Reverse().ToList();

            for (var i = 0; i < commitList.Count; i++)
            {
                var commit = commitList[i];
                try
                {
                    Log($"开始 {commit} 二分,本次任务第{i + 1}次构建,总共{commitList.Count}次构建");

                    if (!CheckNeedCompile(commit))
                    {
                        Log($"已构建过 {commit} 无须再次运行,跳过此构建");
                        continue;
                    }

                    CleanDirectory(commit);

                    // 如果没有指定使用 bat 脚本构建,那么执行通用构建

                    var compilerBatFile = BinaryChopCompileConfiguration.CompilerBatFile;
                    if (string.IsNullOrEmpty(compilerBatFile) || !File.Exists(compilerBatFile))
                    {
                        Log($"找不到指定的 bat 构建脚本文件 {compilerBatFile} 将使用默认的方式构建");

                        // 这里是代码里面自己带的构建配置文件
                        var appConfigurator = GetCurrentBuildConfiguration();

                        var currentBuildLogFile = GetCurrentBuildLogFile(appConfigurator);

                        // 填充一下文件路径
                        var fileSniff = new FileSniff(appConfigurator);
                        fileSniff.Sniff();

                        var msbuildConfiguration = AppConfigurator.Of <MsbuildConfiguration>();

                        var msBuildCompiler = new MSBuild(appConfigurator);
                        msBuildCompiler.Build(new MSBuildCommandOptions()
                        {
                            ShouldRestore = msbuildConfiguration.ShouldRestore,
                            MaxCpuCount   = msbuildConfiguration.MaxCpuCount,
                        });

                        MoveFile(commit, currentBuildLogFile);
                    }
                    else
                    {
                        Log($"开始执行 {compilerBatFile} 构建脚本文件");

                        var(success, output) = ProcessCommand.ExecuteCommand(compilerBatFile, null);
                        // 将输出写入到文件里面
                        var logFile = Path.GetTempFileName();
                        File.WriteAllText(logFile, output);
                        MoveFile(commit, new FileInfo(logFile));
                    }

                    LastCommit = commit;

                    Log($"构建 {commit} 完成,休息一下。休息 {BinaryChopCompileConfiguration.SecondTimeToRest} 秒中");
                    // 构建完成,休息一下
                    // 同步的等待,这里是调度任务,不需要使用异步
                    Task.Delay(TimeSpan.FromSeconds(BinaryChopCompileConfiguration.SecondTimeToRest)).Wait();
                }
                catch (Exception e)
                {
                    Log(e.ToString());
                }
            }
        }
Exemple #30
0
 public IISHost(IDictionary <string, string> environmentVariables)
 {
     ExtractTyeEnvironmentVariables(environmentVariables);
     _msBuild = new MSBuild();
 }
        /// <summary>
        /// Constructor to Wrap an existing MSBuild.ProjectItem
        /// Only have internal constructors as the only one who should be creating
        /// such object is the project itself (see Project.CreateFileNode()).
        /// </summary>
        /// <param name="project">Project that owns this item</param>
        /// <param name="existingItem">an MSBuild.ProjectItem; can be null if virtualFolder is true</param>
        /// <param name="virtualFolder">Is this item virtual (such as reference folder)</param>
        internal CogaenEditProjectElement(CogaenEditProject project, MSBuild.ProjectItem existingItem, bool virtualFolder)
        {
            if(project == null)
                throw new ArgumentNullException("project");
            if(!virtualFolder && existingItem == null)
                throw new ArgumentNullException("existingItem");

            // Keep a reference to project and item
            this.itemProject = project;
            this.item = existingItem;
            this.isVirtual = virtualFolder;

            if(this.isVirtual)
                this.virtualProperties = new Dictionary<string, string>();
        }
Exemple #32
0
        public async Task ShouldRestartUponRebuild(bool noRestart)
        {
            await using var testSolution = await CopyTestAssets("democonsole");

            var projectPath = Path.Join(testSolution.Value, "democonsole");

            var msBuild = new MSBuild();

            await using var dnfHost = new DNFHost();
            using var cancel        = new CancellationTokenSource();

            var finishedBuild     = new TaskCompletionSource <int>();
            var newMessageArrived = new TaskCompletionSource <int>();

            int originalPid = 0;
            Action <bool, string> capture = (error, message) =>
            {
                if (!error && message.Contains("Started at PID"))
                {
                    originalPid = int.Parse(message.Split(" ").Last());
                }
                else if (!error && message == "Message A")
                {
                    var projectCs = Path.Join(projectPath, "Program.cs");
                    File.WriteAllText(projectCs, File.ReadAllText(projectCs).Replace("Message A", "Message B"));
                    msBuild.BuildAndGetArtifactPath(projectPath, testSolution.Value)
                    .ContinueWith(res =>
                    {
                        if (!res.Result.Success)
                        {
                            _console.Error.WriteLine(res.Result.Error);
                        }

                        finishedBuild.TrySetResult(0);
                    });
                }
                else if (!error && message == "Message B")
                {
                    newMessageArrived.TrySetResult(0);
                }
            };
            var run = dnfHost.Run(new MultiplexerConsole(new[] { _console, new CaptureConsole(capture) }), new CommandArguments
            {
                Path         = new DirectoryInfo(projectPath),
                SolutionPath = new DirectoryInfo(testSolution.Value),
                NoRestart    = noRestart
            }, cancel.Token);

            try
            {
                await finishedBuild.Task;

                if (!noRestart)
                {
                    await WaitOrTimeout(newMessageArrived.Task);
                }
                else
                {
                    await ShouldTimeout(newMessageArrived.Task);
                }
            }
            finally
            {
                cancel.Cancel();
                await run;
            }
        }
        static void Main(string[] args)
        {
            var msBuild = new MSBuild(AppConfigurator.GetAppConfigurator());

            msBuild.Build();
        }
Exemple #34
0
 public DNFHost()
 {
     _watcher = new ArtifactsWatcher();
     _msBuild = new MSBuild();
 }