public ProjectProcessor(string path)
		{
			using (ProjectCollection pc = new ProjectCollection())
			{
				this.Project = pc.GetLoadedProjects(path).FirstOrDefault();
			}
		}
        public void SetDefaultToolsVersion()
        {
            string oldValue = Environment.GetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION");

            try
            {
                // In the new world of figuring out the ToolsVersion to use, we completely ignore the default
                // ToolsVersion in the ProjectCollection.  However, this test explicitly depends on modifying 
                // that, so we need to turn the new defaulting behavior off in order to verify that this still works.  
                Environment.SetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION", "1");
                InternalUtilities.RefreshInternalEnvironmentValues();

                ProjectCollection collection = new ProjectCollection();
                collection.AddToolset(new Toolset("x", @"c:\y", collection, null));

                collection.DefaultToolsVersion = "x";

                Assert.AreEqual("x", collection.DefaultToolsVersion);

                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Target Name='t'/>
                    </Project>
                ";

                Project project = new Project(XmlReader.Create(new StringReader(content)), null, null, collection);

                Assert.AreEqual(project.ToolsVersion, "x");
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDLEGACYDEFAULTTOOLSVERSION", oldValue);
                InternalUtilities.RefreshInternalEnvironmentValues();
            }
        }
示例#3
0
        private static void BuildProject(string projectFile)
        {
            Console.WriteLine("Building Project [" + projectFile + "]");
            var collection = new ProjectCollection {DefaultToolsVersion = "12.0"};
            collection.LoadProject(projectFile);

            collection.RegisterLoggers(new List<ILogger> { new ConsoleLogger(), new FileLogger {Parameters = projectFile + ".build.log"}});

            try
            {
                foreach (var project in collection.LoadedProjects.Where(x => x.IsBuildEnabled))
                {
                    project.SetProperty("Platform", "x64");
                    if (!project.Build())
                        throw new BuildException(projectFile);

                    project.SetProperty("Configuration", "Release");
                    if (!project.Build())
                        throw new BuildException(projectFile);
                }
            }
            finally
            {
                collection.UnregisterAllLoggers();
            }
        }
    public BuildIntegrationTests(ITestOutputHelper logger)
        : base(logger)
    {
        int seed = (int)DateTime.Now.Ticks;
        this.random = new Random(seed);
        this.Logger.WriteLine("Random seed: {0}", seed);
        this.buildManager = new BuildManager();
        this.projectCollection = new ProjectCollection();
        this.projectDirectory = Path.Combine(this.RepoPath, "projdir");
        Directory.CreateDirectory(this.projectDirectory);
        this.LoadTargetsIntoProjectCollection();
        this.testProject = this.CreateProjectRootElement(this.projectDirectory, "test.proj");
        this.testProjectInRoot = this.CreateProjectRootElement(this.RepoPath, "root.proj");
        this.globalProperties.Add("NerdbankGitVersioningTasksPath", Environment.CurrentDirectory + "\\");

        // Sterilize the test of any environment variables.
        foreach (System.Collections.DictionaryEntry variable in Environment.GetEnvironmentVariables())
        {
            string name = (string)variable.Key;
            if (ToxicEnvironmentVariablePrefixes.Any(toxic => name.StartsWith(toxic, StringComparison.OrdinalIgnoreCase)))
            {
                this.globalProperties[name] = string.Empty;
            }
        }
    }
        public static bool buildProject(this string projectFile, bool redirectToConsole = false)
        {
            try
            {
                var fileLogger = new FileLogger();
                var logFile = projectFile.directoryName().pathCombine(projectFile.fileName() + ".log");
                fileLogger.field("logFileName", logFile);
                if (logFile.fileExists())
                    logFile.file_Delete();

                var projectCollection = new ProjectCollection();
                var project = projectCollection.LoadProject(projectFile);
                if (project.isNull())
                {
                    "could not load project file: {0}".error(projectFile);
                    return false;
                }
                if (redirectToConsole)
                    projectCollection.RegisterLogger(new ConsoleLogger());

                projectCollection.RegisterLogger(fileLogger);
                var result = project.Build();
                fileLogger.Shutdown();
                return result;
            }
            catch(Exception ex)
            {
                ex.log();
                return false;
            }
        }
    internal static async Task<BuildResult> BuildAsync(this BuildManager buildManager, ITestOutputHelper logger, ProjectCollection projectCollection, ProjectRootElement project, string target, IDictionary<string, string> globalProperties = null, LoggerVerbosity logVerbosity = LoggerVerbosity.Detailed, ILogger[] additionalLoggers = null)
    {
        Requires.NotNull(buildManager, nameof(buildManager));
        Requires.NotNull(projectCollection, nameof(projectCollection));
        Requires.NotNull(project, nameof(project));

        globalProperties = globalProperties ?? new Dictionary<string, string>();
        var projectInstance = new ProjectInstance(project, globalProperties, null, projectCollection);
        var brd = new BuildRequestData(projectInstance, new[] { target }, null, BuildRequestDataFlags.ProvideProjectStateAfterBuild);

        var parameters = new BuildParameters(projectCollection);

        var loggers = new List<ILogger>();
        loggers.Add(new ConsoleLogger(logVerbosity, s => logger.WriteLine(s.TrimEnd('\r', '\n')), null, null));
        loggers.AddRange(additionalLoggers);
        parameters.Loggers = loggers.ToArray();

        buildManager.BeginBuild(parameters);

        var result = await buildManager.BuildAsync(brd);

        buildManager.EndBuild();

        return result;
    }
示例#7
0
 private bool BuildSolution_VS()
 {
     if (_SolutionPath == "") return false;
     try
     {
         string projectFilePath = Path.Combine(_SolutionPath);
         _OutputPath = _SolutionPath.Replace(Path.GetFileName(_SolutionPath), "") + "\\bin\\" + BuildInterface_Configuration.Text + "\\";
         ProjectCollection pc = new ProjectCollection();
         Dictionary<string, string> globalProperty = new Dictionary<string, string>();
         globalProperty.Add("OutputPath", _OutputPath);
         BuildParameters bp = new BuildParameters(pc);
         BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0", new string[] { "Build" }, null);
         BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
         if (buildResult.OverallResult == BuildResultCode.Success)
         {
             return true;
         }
         else
         {
             MessageBox.Show("There Are Errors", "Error");
         }
     }
     catch
     {
         MessageBox.Show("Build Failed Unexpectedly", "Error");
     }
     return false;
 }
		public ProjectBuilder (BuildEngine buildEngine, ProjectCollection engine, string file)
		{
			this.file = file;
			this.engine = engine;
			this.buildEngine = buildEngine;
			Refresh ();
		}
示例#9
0
        public static string[] Build(string solutionFile)
        {
            Console.Error.Write("// Building '{0}'... ", Path.GetFileName(solutionFile));

            var pc = new ProjectCollection();
            var parms = new BuildParameters(pc);
            var globalProperties = new Dictionary<string, string>();
            var request = new BuildRequestData(solutionFile, globalProperties, null, new string[] { "Build" }, null);

            parms.Loggers = new[] {
                new ConsoleLogger(LoggerVerbosity.Quiet)
            };

            var result = BuildManager.DefaultBuildManager.Build(parms, request);
            var resultFiles = new HashSet<string>();

            Console.Error.WriteLine("done.");

            foreach (var kvp in result.ResultsByTarget) {
                var targetResult = kvp.Value;

                if (targetResult.Exception != null)
                    Console.Error.WriteLine("// Compilation failed for target '{0}':\r\n{1}", kvp.Key, targetResult.Exception.Message);
                else {
                    foreach (var filename in targetResult.Items)
                        resultFiles.Add(filename.ItemSpec);
                }
            }

            return resultFiles.ToArray();
        }
示例#10
0
        /// <summary>
        /// 
        /// </summary>
        public static bool ReloadScripts()
        {
            if (SceneManager.GameProject == null) return false;

            string projectFileName = SceneManager.GameProject.ProjectPath + @"\Scripts.csproj";
            string tmpProjectFileName = SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj";
            string hash = string.Empty;

            hash = GibboHelper.EncryptMD5(DateTime.Now.ToString());

            try
            {
                /* Change the assembly Name */
                XmlDocument doc = new XmlDocument();
                doc.Load(projectFileName);
                doc.GetElementsByTagName("Project").Item(0).ChildNodes[0]["AssemblyName"].InnerText = hash;
                doc.Save(tmpProjectFileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            /* Compile project */
            ProjectCollection projectCollection = new ProjectCollection();
            Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();
            GlobalProperty.Add("Configuration", SceneManager.GameProject.Debug ? "Debug" : "Release");
            GlobalProperty.Add("Platform", "x86");

            BuildRequestData buildRequest = new BuildRequestData(tmpProjectFileName, GlobalProperty, null, new string[] { "Build" }, null);
            BuildResult buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection), buildRequest);

            Console.WriteLine(buildResult.OverallResult);

            string cPath = SceneManager.GameProject.ProjectPath + @"\bin\" + (SceneManager.GameProject.Debug ? "Debug" : "Release") + "\\" + hash + ".dll";

            if (File.Exists(cPath))
            {
                /* read assembly to memory without locking the file */
                byte[] readAllBytes = File.ReadAllBytes(cPath);
                SceneManager.ScriptsAssembly = Assembly.Load(readAllBytes);

                if (SceneManager.ActiveScene != null)
                {
                    SceneManager.ActiveScene.SaveComponentValues();
                    SceneManager.ActiveScene.Initialize();
                }

                Console.WriteLine("Path: " + SceneManager.ScriptsAssembly.GetName().Name);
            }
            else
            {
                File.Delete(tmpProjectFileName);
                return false;
            }

            File.Delete(tmpProjectFileName);

            return true;
        }
示例#11
0
		public ProjectInstance (string projectFile, IDictionary<string, string> globalProperties,
				string toolsVersion, ProjectCollection projectCollection)
		{
			InitializeProperties ();
			
			throw new NotImplementedException ();
		}
示例#12
0
 public void CleanWithoutBuild()
 {
     AssertBuildEnviromentIsClean(@"MSBuild\Trivial");
     var proj = new ProjectCollection().LoadProject(@"MSBuild\Trivial\trivial.rsproj");
     AssertBuildsProject(proj, "Clean");
     AssertBuildEnviromentIsClean(@"MSBuild\Trivial");
 }
示例#13
0
        private static void Main()
        {
            try
            {
                // Run this in debug otherwise the files in CreateInstallers will be locked. :)
                const string projectFileName = @"..\..\..\wix-custom-ba-issue.sln";
                var pc = new ProjectCollection();
                var globalProperty = new Dictionary<string, string> {{"Configuration", "Release"}};

                var buildRequestData = new BuildRequestData(projectFileName, globalProperty, null, new[] {"Rebuild"},
                    null);

                var buildParameters = new BuildParameters(pc)
                {
                    DetailedSummary = true,
                    Loggers = new List<ILogger> {new ConsoleLogger()}
                };

                foreach (var version in new List<string> {"0.0.6.0", "1.0.0.0"})
                    BuildExamples(version, buildParameters, buildRequestData);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed!", e);
                Console.WriteLine(e.ToString());
            }
        }
示例#14
0
    static void AddSolutionConfiguration(string projectFile, Dictionary<string, string> properties)
    {
        var collection = new ProjectCollection(properties);
        var toolsVersion = default(string);
        var project = new Project(projectFile, properties, toolsVersion, collection);
        var config = project.GetPropertyValue("Configuration");
        var platform = project.GetPropertyValue("Platform");

        var xml = new XElement("SolutionConfiguration");
        xml.Add(new XElement("ProjectConfiguration",
            new XAttribute("Project", project.GetPropertyValue("ProjectGuid")),
            new XAttribute("AbsolutePath", project.FullPath),
            new XAttribute("BuildProjectInSolution", "true"))
        {
            Value = $"{config}|{platform}"
        });

        foreach (var reference in GetProjectReferences(project))
        {
            xml.Add(new XElement("ProjectConfiguration",
                new XAttribute("Project", reference.GetPropertyValue("ProjectGuid")),
                new XAttribute("AbsolutePath", reference.FullPath),
                new XAttribute("BuildProjectInSolution", "false"))
            {
                Value = $"{config}|{platform}"
            });
        }

        properties["CurrentSolutionConfigurationContents"] = xml.ToString(SaveOptions.None);
    }
示例#15
0
 /// <summary>Initializes a new instance of the <see cref="VsProject" /> class.</summary>
 /// <param name="filePath">The file path.</param>
 /// <param name="projectCollection">The project collection.</param>
 /// <exception cref="InvalidProjectFileException">The project file could not be found.</exception>
 private VsProject(string filePath, ProjectCollection projectCollection)
     : base(filePath)
 {
     Project = projectCollection.LoadProject(filePath);
     Solutions = new ObservableCollection<VsSolution>();
     LoadNuSpecFile(filePath);
 }
示例#16
0
        private void PublishSite(Dictionary<string, string> properties)
        {
            var logFile = Path.GetTempFileName();

            try
            {
                bool success;
                using (var projects = new ProjectCollection(properties))
                {
                    projects.RegisterLogger(new FileLogger { Parameters = @"logfile=" + logFile, Verbosity = LoggerVerbosity.Quiet });
                    projects.OnlyLogCriticalEvents = true;
                    var project = projects.LoadProject(ProjectPath);
                    success = project.Build();
                }

                if (!success)
                {
                    Console.WriteLine(File.ReadAllText(logFile));
                    throw new ApplicationException("Build failed.");
                }
            }
            finally
            {
                if (File.Exists(logFile))
                {
                    File.Delete(logFile);
                }
            }
        }
示例#17
0
        public static string Start(DotnetBuildParams objBuildParams)
        {
            try
            {
                ProjectCollection pc = new ProjectCollection();

                pc.DefaultToolsVersion = "4.0";
                Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();

                GlobalProperty.Add("Configuration", objBuildParams.Configuration);

                GlobalProperty.Add("Platform", objBuildParams.Platform);

                //Here, we set the property

                GlobalProperty.Add("OutputPath", objBuildParams.OutputPath);

                BuildRequestData BuidlRequest = new BuildRequestData(objBuildParams.projectFileName, GlobalProperty, null, objBuildParams.TargetsToBuild, null);

                BuildResult buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(pc), BuidlRequest);

                return  ((BuildResultCode)buildResult.OverallResult).ToString();

            }
            catch (Exception ex)
            {
                return BuildResultCode.Failure.ToString() ;
            }
            finally
            {

            }
        }
        /// <summary>
        /// Builds the project - based on http://msdn.microsoft.com/en-us/library/microsoft.build.buildengine.engine.aspx.
        /// </summary>
        /// <param name="projectPath">The project (csproj) path</param>
        /// <returns>True if builds okay</returns>
        private static bool BuildProject(string projectPath)
        {
            var logPath = Path.Combine(Path.GetDirectoryName(projectPath), "build.log");

            //.Net 4 Microsoft.Build.Evaluation.Project and ProjectCollection
            var engine = new ProjectCollection();

            // Instantiate a new FileLogger to generate build log
            var logger = new Microsoft.Build.Logging.FileLogger();

            // Set the logfile parameter to indicate the log destination
            logger.Parameters = @"logfile=" + logPath;

            // Register the logger with the engine
            engine.RegisterLogger(logger);

            // Build a project file
            bool success = engine.LoadProject(projectPath).Build();
            //Unregister all loggers to close the log file
            engine.UnregisterAllLoggers();

            //if fails, put the log file into the assert statement
            string txt = "Should have built";
            if (!success && File.Exists(logPath))
                txt = File.ReadAllText(logPath);
            Console.WriteLine(txt);

            return success;
        }
        public void ImportFromExtensionsPathNotFound()
        {
            string extnDir1 = null;
            string mainProjectPath = null;

            try {
                extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
                mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());

                var projColln = new ProjectCollection();
                projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistant")));
                var logger = new MockLogger();
                projColln.RegisterLogger(logger);

                Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));

                logger.AssertLogContains("MSB4226");
            } finally {
                if (mainProjectPath != null)
                {
                    FileUtilities.DeleteNoThrow(mainProjectPath);
                }
                if (extnDir1 != null)
                {
                    FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
                }
            }
        }
示例#20
0
        protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package)
        {
            this.package = package;
            this.site = package;

            // Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters.
            this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site);
        }
 public CachingProjectLoader(IDictionary<string, string> globalMsBuildProperties, IConsole console)
 {
     _globalMsBuildProperties = globalMsBuildProperties;
     _console = console;
     _projectCollection = new ProjectCollection();
     _projectsByGuid = new Dictionary<Guid, IVsProject>();
     _projectLoader = this;
 }
示例#22
0
        public bool BuildProjects(List<IProject> projects)
        {
            var engine = new ProjectCollection();

            return
                projects.Select(project => Path.Combine(project.ProjectPath, project.ProjectName)).Select(
                    fullProjectPath => engine.LoadProject(fullProjectPath).Build()).All(success => success);
        }
示例#23
0
 public void BuildTrivialProject()
 {
     var proj = new ProjectCollection().LoadProject(@"MSBuild\Trivial\trivial.rsproj");
     AssertBuildsProject(proj, "Build");
     Assert.IsTrue(File.Exists(@"MSBuild\Trivial\target\Debug\trivial.exe"));
     Directory.Delete(@"MSBuild\Trivial\obj", true);
     Directory.Delete(@"MSBuild\Trivial\target", true);
 }
示例#24
0
		public ProjectBuilder (BuildEngine buildEngine, ProjectCollection engine, string file)
		{
			this.file = file;
			this.engine = engine;
			this.buildEngine = buildEngine;
			consoleLogger = new ConsoleLogger (LoggerVerbosity.Normal, LogWriteLine, null, null);
			Refresh ();
		}
        public CogaenEditProjectFactory(Microsoft.VisualStudio.Shell.Package package)
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
            this.package = package;
            this.site = package;

            // Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters.
            this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site);
        }
 public BuildResult BuildProject(string directoryPath)
 {
     string projectFileName = Path.Combine(directoryPath, MainClassName + ".csproj");
     var projectCollection = new ProjectCollection();
     var globalProperties = new Dictionary<string, string>();
     var buidlRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
     var buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection), buidlRequest);
     return buildResult;
 }
示例#27
0
		public void Toolsets ()
		{
			var pc = ProjectCollection.GlobalProjectCollection;
			Assert.IsNotNull (pc.Toolsets, "#1-1");
			Assert.IsTrue (pc.Toolsets.Any (), "#1-2");
			pc = new ProjectCollection ();
			Assert.IsNotNull (pc.Toolsets, "#2-1");
			Assert.IsTrue (pc.Toolsets.Any (), "#2-2");
		}
示例#28
0
文件: Project.cs 项目: ngraziano/mono
 public Project (ProjectRootElement xml, IDictionary<string, string> globalProperties,
                 string toolsVersion, ProjectCollection projectCollection,
                 ProjectLoadSettings loadSettings)
 {
         ProjectCollection = projectCollection;
         Xml = xml;
         GlobalProperties = globalProperties;
         ToolsVersion = toolsVersion;
 }
示例#29
0
 public void BuildAndCleanLibraryWithMultipleOutputs()
 {
     var proj = new ProjectCollection().LoadProject(@"MSBuild\multi_lib\multi_lib.rsproj");
     AssertBuildsProject(proj, "Build");
     Assert.IsTrue(File.Exists(@"MSBuild\multi_lib\target\Debug\multi_lib.dll"));
     Assert.IsTrue(File.Exists(@"MSBuild\multi_lib\target\Debug\libmulti_lib.a"));
     Assert.IsTrue(File.Exists(@"MSBuild\multi_lib\target\Debug\libmulti_lib.rlib"));
     AssertBuildsProject(proj, "Clean");
     AssertBuildEnviromentIsClean(@"MSBuild\multi_lib");
 }
示例#30
0
        /// <summary>
        /// Initializes the in memory project. Sets BuildEnabled on the project to true.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project InitializeMsBuildProject(MSBuild.ProjectCollection buildEngine, string fullProjectPath)
        {
            Utilities.ArgumentNotNullOrEmpty(nameof(fullProjectPath), fullProjectPath);

            // Call GetFullPath to expand any relative path passed into this method.
            fullProjectPath = CommonUtils.NormalizePath(fullProjectPath);

            // Check if the project already has been loaded with the fullProjectPath. If yes return the build project associated to it.
            var loadedProject = new List <MSBuild.Project>(buildEngine.GetLoadedProjects(fullProjectPath));
            var buildProject  = loadedProject != null && loadedProject.Count > 0 && loadedProject[0] != null ? loadedProject[0] : null;

            if (buildProject == null)
            {
                buildProject = buildEngine.LoadProject(fullProjectPath);
            }

            return(buildProject);
        }
示例#31
0
        /// <summary>
        /// Loads a project file for the file. If the build project exists and it was loaded with a different file then it is unloaded first.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <param name="exitingBuildProject">An Existing build project that will be reloaded.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project ReinitializeMsBuildProject(MSBuild.ProjectCollection buildEngine, string fullProjectPath, MSBuild.Project exitingBuildProject)
        {
            // If we have a build project that has been loaded with another file unload it.
            try
            {
                if (exitingBuildProject != null && exitingBuildProject.ProjectCollection != null && !NativeMethods.IsSamePath(exitingBuildProject.FullPath, fullProjectPath))
                {
                    buildEngine.UnloadProject(exitingBuildProject);
                }
            }
            // We  catch Invalid operation exception because if the project was unloaded while we touch the ParentEngine the msbuild API throws.
            // Is there a way to figure out that a project was unloaded?
            catch (InvalidOperationException)
            {
            }

            return(Utilities.InitializeMsBuildProject(buildEngine, fullProjectPath));
        }
示例#32
0
        public static async Task <DependencyGraphSpec> GenerateRestoreGraphFile(ILogger logger, string projectPath)
        {
            DependencyGraphSpec spec = null;

            using (var restoreGraphResult = new TemporaryFile())
            {
                await Task.Run(() =>
                {
                    var pc = new Microsoft.Build.Evaluation.ProjectCollection();

                    try
                    {
                        var parameters = new BuildParameters(pc)
                        {
                            Loggers = new[] { new LoggerRedirect(logger, true) } //Instance of ILogger instantiated earlier
                        };

                        // Run a MSBuild /t:Restore <projectfile>
                        var request = new BuildRequestData(projectPath, new Dictionary <string, string> {
                            { "RestoreGraphOutputPath", restoreGraphResult.Path }, { "RestoreRecursive", "false" }
                        }, null, new[] { "GenerateRestoreGraphFile" }, null, BuildRequestDataFlags.None);

                        mainBuildManager.Build(parameters, request);
                    }
                    finally
                    {
                        pc.UnloadAllProjects();
                        pc.Dispose();
                    }
                });

                if (File.Exists(restoreGraphResult.Path) && new FileInfo(restoreGraphResult.Path).Length != 0)
                {
                    spec = DependencyGraphSpec.Load(restoreGraphResult.Path);
                    File.Delete(restoreGraphResult.Path);
                }
                else
                {
                    spec = new DependencyGraphSpec();
                }
            }

            return(spec);
        }
        public static Microsoft.Build.Evaluation.Project LoadProject(string fullProjectLocation, string configuration = "Debug", string platform = "AnyCPU", Dictionary <string, string> extraProperties = null)
        {
            configuration = configuration ?? "Debug";
            platform      = platform ?? "AnyCPU";

            var globalProperties = new Dictionary <string, string>();

            globalProperties["Configuration"] = configuration;
            globalProperties["Platform"]      = platform;

            if (extraProperties != null)
            {
                foreach (var extraProperty in extraProperties)
                {
                    globalProperties[extraProperty.Key] = extraProperty.Value;
                }
            }

            var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection(globalProperties);

            projectCollection.LoadProject(fullProjectLocation);
            var project = projectCollection.LoadedProjects.First();

            // Support for cross-targeting (TargetFrameworks)
            var assemblyPath     = project.GetPropertyValue("TargetPath");
            var targetFramework  = project.GetPropertyValue("TargetFramework");
            var targetFrameworks = project.GetPropertyValue("TargetFrameworks");

            if (string.IsNullOrWhiteSpace(assemblyPath) && string.IsNullOrWhiteSpace(targetFramework) && !string.IsNullOrWhiteSpace(targetFrameworks))
            {
                // We might be in a cross-targeting scenario
                // Reload project with first target framework
                project.ProjectCollection.UnloadAllProjects();
                project.ProjectCollection.Dispose();

                globalProperties.Add("TargetFramework", targetFrameworks.Split(';').First());
                projectCollection = new Microsoft.Build.Evaluation.ProjectCollection(globalProperties);
                projectCollection.LoadProject(fullProjectLocation);
                project = projectCollection.LoadedProjects.First();
            }

            return(project);
        }
示例#34
0
        private static async Task CleanIntermediateAsset(DTE2 dte, Project project)
        {
            if (project.FileName == null || Path.GetExtension(project.FileName) != ".csproj")
            {
                return;
            }

            // Find current project active configuration
            var configManager = project.ConfigurationManager;
            var activeConfig  = configManager.ActiveConfiguration;

            // Get global parameters for Configuration and Platform
            var globalProperties = new Dictionary <string, string>();

            globalProperties["Configuration"] = activeConfig.ConfigurationName;
            globalProperties["Platform"]      = activeConfig.PlatformName == "Any CPU" ? "AnyCPU" : activeConfig.PlatformName;

            // Check if project has a SiliconStudioCurrentPackagePath
            var projectInstance     = new ProjectInstance(project.FileName, globalProperties, null);
            var packagePathProperty = projectInstance.Properties.FirstOrDefault(x => x.Name == "SiliconStudioCurrentPackagePath");

            if (packagePathProperty == null)
            {
                return;
            }

            // Prepare build request
            var request         = new BuildRequestData(project.FileName, globalProperties, null, new[] { "SiliconStudioCleanAsset" }, null);
            var pc              = new Microsoft.Build.Evaluation.ProjectCollection();
            var buildParameters = new BuildParameters(pc);
            var buildLogger     = new IDEBuildLogger(GetOutputPane(), new TaskProvider(ServiceProvider), VsHelper.ToHierarchy(project));

            buildParameters.Loggers = new[] { buildLogger };

            // Trigger async build
            buildLogger.OutputWindowPane.OutputStringThreadSafe(string.Format("Cleaning assets for project {0}...\r\n", project.Name));
            BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
            var         submission  = BuildManager.DefaultBuildManager.PendBuildRequest(request);
            BuildResult buildResult = await submission.ExecuteAsync();

            BuildManager.DefaultBuildManager.EndBuild();
            buildLogger.OutputWindowPane.OutputStringThreadSafe("Done\r\n");
        }
示例#35
0
        public string GetCurrentTest(string filePath, int line, int lineCharOffset)
        {
            var project = PathToProject(filePath);

            if (project != null && _discoverer.IsProjectKnown(project))
            {
                var    buildEngine = new MSBuild.ProjectCollection();
                string projectPath;
                if (project.TryGetProjectPath(out projectPath))
                {
                    var proj = buildEngine.LoadProject(projectPath);
#if FALSE
                    var provider = new MSBuildProjectInterpreterFactoryProvider(_interpreterService, proj);
                    try {
                        provider.DiscoverInterpreters();
                    } catch (InvalidDataException) {
                        // This exception can be safely ignored here.
                    }
                    var factory = provider.ActiveInterpreter;

                    var parser = Parser.CreateParser(
                        new StreamReader(filePath),
                        factory.GetLanguageVersion()
                        );
                    var ast    = parser.ParseFile();
                    var walker = new FunctionFinder(ast, line, lineCharOffset);
                    ast.Walk(walker);
                    var projHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, proj.GetPropertyValue(PythonConstants.ProjectHomeSetting) ?? "."));

                    if (walker.ClassName != null && walker.FunctionName != null)
                    {
                        return(TestAnalyzer.MakeFullyQualifiedTestName(
                                   CommonUtils.CreateFriendlyFilePath(projHome, filePath),
                                   walker.ClassName,
                                   walker.FunctionName
                                   ));
                    }
#endif
                }
            }
            return(null);
        }
示例#36
0
        public void LoadCommonTargets()
        {
            ProjectCollection projectCollection = new ProjectCollection();
            string            toolsPath         = projectCollection.Toolsets.Where(toolset => (String.Compare(toolset.ToolsVersion, "4.0", StringComparison.OrdinalIgnoreCase) == 0)).First().ToolsPath;

            string[] targets = new string[] { "microsoft.common.targets", "microsoft.csharp.targets", "microsoft.visualbasic.targets" };

            foreach (string target in targets)
            {
                string             path    = Path.Combine(toolsPath, target);
                ProjectRootElement project = ProjectRootElement.Open(path);
                Console.WriteLine(@"Loaded target: {0}", target);
                Console.WriteLine(@"Children: {0}", Helpers.Count(project.Children));
                Console.WriteLine(@"Targets: {0}", Helpers.MakeList(project.Targets).Count);
                Console.WriteLine(@"Root ItemGroups: {0}", Helpers.MakeList(project.ItemGroups).Count);
                Console.WriteLine(@"Root PropertyGroups: {0}", Helpers.MakeList(project.PropertyGroups).Count);
                Console.WriteLine(@"UsingTasks: {0}", Helpers.MakeList(project.UsingTasks).Count);
                Console.WriteLine(@"ItemDefinitionGroups: {0}", Helpers.MakeList(project.ItemDefinitionGroups).Count);
            }
        }
        public string GetCurrentTest(string filePath, int line, int lineCharOffset)
        {
            var project = PathToProject(filePath);

            if (project != null && this.discoverer.IsProjectKnown(project))
            {
                var buildEngine = new MSBuild.ProjectCollection();
                if (project.TryGetProjectPath(out var projectPath))
                {
                    var proj = buildEngine.LoadProject(projectPath);

                    //TODO - Find the matching function

                    /*
                     * Need identify which method is executing.
                     */
                }
            }
            return(null);
        }
示例#38
0
        public override bool Execute()
        {
            bool result = true;

            string file = Path.Combine(m_stubsPath, m_name + ".featureproj");

            try
            {
                _EVAL.Project proj = new _EVAL.Project();

                Microsoft.Build.Evaluation.ProjectCollection projCol = proj.ProjectCollection;

                ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();
                bpg.AddProperty("FeatureName", m_name);
                bpg.AddProperty("Guid", System.Guid.NewGuid().ToString("B"));
                bpg.AddProperty("Description", "<Add Feature Description Here>");
                bpg.AddProperty("Groups", "");
                bpg.AddProperty(m_name.ToUpper().Replace(".", "_") + "_FEATUREPROJ", "True");

                ProjectItemGroupElement big = proj.Xml.AddItemGroup();
                big.AddItem("InteropFeature", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_'));
                big.AddItem("DriverLibs", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_') + ".$(LIB_EXT)");
                big.AddItem("MMP_DAT_CreateDatabase", "$(BUILD_TREE_CLIENT)\\pe\\$(ENDIANNESS)\\" + m_assemblyName);
                big.AddItem("RequiredProjects", Path.Combine(m_stubsPath, m_nativeProjectFile));


                proj.Save(file);

                // after save, unload the project, so that if rebuilds it is able to regenerate the project file.
                ProjectRootElement pre = proj.Xml;
                projCol.UnloadProject(proj);
                projCol.UnloadProject(pre);
            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create feature project file \"" + file + "\": " + e.Message);
                result = false;
            }

            return(result);
        }
示例#39
0
        private void LoadSolution(string solutionFilePath, Build.ProjectCollection projects)
        {
            if (!File.Exists(solutionFilePath))
            {
                return;
            }

            string[] lines = File.ReadAllLines(solutionFilePath);
            for (int i = 0; i < lines.Length; i++)
            {
                string line = (lines[i] ?? "").TrimStart();
                if (!line.StartsWith("Project"))
                {
                    continue;
                }

                int startIndex = line.IndexOf(", \"");
                if (startIndex < 0)
                {
                    continue;
                }

                startIndex += 3;

                int endIndex = line.IndexOf('"', startIndex);
                if (endIndex < 0)
                {
                    continue;
                }

                string projectFilePath = line.Substring(startIndex, endIndex - startIndex);
                projectFilePath = Path.Combine(Path.GetDirectoryName(solutionFilePath), projectFilePath);

                if (!File.Exists(projectFilePath))
                {
                    continue;
                }

                LoadProject(projectFilePath, projects);
            }
        }
示例#40
0
        /// <summary>
        /// Initializes the in memory project. Sets BuildEnabled on the project to true.
        /// </summary>
        /// <param name="engine">The build engine to use to create a build project.</param>
        /// <param name="fullProjectPath">The full path of the project.</param>
        /// <returns>A loaded msbuild project.</returns>
        internal static MSBuild.Project InitializeMsBuildProject(MSBuild.ProjectCollection buildEngine, string fullProjectPath)
        {
            if (String.IsNullOrEmpty(fullProjectPath))
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "fullProjectPath");
            }

            // Call GetFullPath to expand any relative path passed into this method.
            fullProjectPath = Path.GetFullPath(fullProjectPath);


            // Check if the project already has been loaded with the fullProjectPath. If yes return the build project associated to it.
            List <MSBuild.Project> loadedProject = new List <MSBuild.Project>(buildEngine.GetLoadedProjects(fullProjectPath));

            MSBuild.Project buildProject = loadedProject != null && loadedProject.Count > 0 && loadedProject[0] != null ? loadedProject[0] : null;

            if (buildProject == null)
            {
                buildProject = buildEngine.LoadProject(fullProjectPath);
            }

            return(buildProject);
        }
        /// <summary>
        /// ITestDiscover, Given a list of test sources this method pulls out the test cases
        /// </summary>
        /// <param name="sources">List of test sources passed from client (Client can be VS or command line)</param>
        /// <param name="logger">Used to relay messages to registered loggers</param>
        /// <param name="discoverySink">Callback used to notify client upon discovery of test cases</param>
        private void DiscoverTestsCore(IEnumerable <string> sources, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, nameof(sources));
            ValidateArg.NotNull(discoverySink, nameof(discoverySink));
            ValidateArg.NotNull(logger, nameof(logger));

            var env  = new Dictionary <string, string>();
            var root = Environment.GetEnvironmentVariable("VSINSTALLDIR");

#if DEBUG
            logger.SendMessage(TestMessageLevel.Informational, $"VSINSTALLDIR: {root}");
#endif

            if (!string.IsNullOrEmpty(root))
            {
                env["VsInstallRoot"]           = root;
                env["MSBuildExtensionsPath32"] = Path.Combine(root, "MSBuild");
            }

            using (var buildEngine = new MSBuild.ProjectCollection(env))
            {
                try
                {
                    // Load all the test containers passed in (.njsproj msbuild files)
                    foreach (var source in sources)
                    {
                        var cleanPath = source.Trim('\'', '"');
                        buildEngine.LoadProject(cleanPath);
                    }

                    FrameworkDiscoverer frameworkDiscoverer = null;
                    foreach (var proj in buildEngine.LoadedProjects)
                    {
                        var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, "."));

                        var testItems = TestFrameworkFactory.GetTestItems(projectHome, proj);

                        if (testItems.Any())
                        {
                            frameworkDiscoverer = frameworkDiscoverer ?? new FrameworkDiscoverer();

                            var nodeExePath = Nodejs.GetAbsoluteNodeExePath(projectHome, proj.GetPropertyValue(NodeProjectProperty.NodeExePath));
                            if (string.IsNullOrEmpty(nodeExePath))
                            {
                                // if nothing specified in the project fallback to environment
                                nodeExePath = Nodejs.GetPathToNodeExecutableFromEnvironment();
                            }

                            this.DiscoverTests(testItems, frameworkDiscoverer, discoverySink, logger, nodeExePath, proj.FullPath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.SendMessage(TestMessageLevel.Error, ex.Message);
                    throw;
                }
                finally
                {
                    // Disposing buildEngine does not clear the document cache in
                    // VS 2013, so manually unload all projects before disposing.
                    buildEngine.UnloadAllProjects();
                }
            }
        }
示例#42
0
 public Toolset(string toolsVersion, string toolsPath,
                ProjectCollection projectCollection, string msbuildOverrideTasksPath)
     : this(toolsVersion, toolsPath, null, projectCollection, msbuildOverrideTasksPath)
 {
 }
示例#43
0
        public void ConcurrentProjectOpenAndCloseThroughProject()
        {
            int iterations = 500;

            string[] paths = ObjectModelHelpers.GetTempFiles(iterations);

            try
            {
                Project[] projects = new Project[iterations];

                for (int i = 0; i < iterations; i++)
                {
                    CreatePREWithSubstantialContent().Save(paths[i]);
                }

                var collection = new ProjectCollection();
                int counter    = 0;
                int remaining  = iterations;
                var done       = new ManualResetEvent(false);

                for (int i = 0; i < iterations; i++)
                {
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        var current = Interlocked.Increment(ref counter) - 1;

                        projects[current] = collection.LoadProject(paths[current]);

                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            done.Set();
                        }
                    });
                }

                done.WaitOne();

                Assert.AreEqual(iterations, collection.LoadedProjects.Count);

                counter   = 0;
                remaining = iterations;
                done.Reset();

                for (int i = 0; i < iterations; i++)
                {
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        var current = Interlocked.Increment(ref counter) - 1;

                        var pre = projects[current].Xml;
                        collection.UnloadProject(projects[current]);
                        collection.UnloadProject(pre);

                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            done.Set();
                        }
                    });
                }

                done.WaitOne();

                Assert.AreEqual(0, collection.LoadedProjects.Count);
            }
            finally
            {
                for (int i = 0; i < iterations; i++)
                {
                    File.Delete(paths[i]);
                }
            }
        }
示例#44
0
 public static string GetEvaluatedItemIncludeEscaped(ProjectItem item)
 {
     return(ProjectCollection.Escape(item.EvaluatedInclude));
 }
示例#45
0
 internal IEnumerable <T> GetAllItems <T> (string include, string exclude, Func <string, T> creator, Func <string, ITaskItem> taskItemCreator, Func <string, bool> itemTypeCheck, Action <T, string> assignRecurse)
 {
     return(ProjectCollection.GetAllItems <T> (ExpandString, include, exclude, creator, taskItemCreator, DirectoryPath, assignRecurse,
                                               t => all_evaluated_items.Any(i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck(i.ItemType))));
 }
示例#46
0
 public Project(ProjectRootElement xml, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection)
     : this(xml, globalProperties, toolsVersion, projectCollection, ProjectLoadSettings.Default)
 {
 }
示例#47
0
 public Project(string projectFile, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection,
                ProjectLoadSettings loadSettings)
     : this(ProjectRootElement.Create(projectFile), globalProperties, toolsVersion, projectCollection, loadSettings)
 {
 }
示例#48
0
 public Toolset(string toolsVersion, string toolsPath,
                IDictionary <string, string> buildProperties, ProjectCollection projectCollection,
                string msbuildOverrideTasksPath)
     : this(toolsVersion, toolsPath, buildProperties, projectCollection, null, msbuildOverrideTasksPath)
 {
 }
 public MSBuild.Project Save(MSBuild.ProjectCollection collection, string location)
 {
     Directory.CreateDirectory(Path.Combine(location, _name));
     return(null);
 }
示例#50
0
        /// <summary>
        /// ITestDiscover, Given a list of test sources this method pulls out the test cases
        /// </summary>
        /// <param name="sources">List of test sources passed from client (Client can be VS or command line)</param>
        /// <param name="logger">Used to relay messages to registered loggers</param>
        /// <param name="discoverySink">Callback used to notify client upon discovery of test cases</param>
        private void DiscoverTestsCore(IEnumerable <string> sources, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, nameof(sources));
            ValidateArg.NotNull(discoverySink, nameof(discoverySink));
            ValidateArg.NotNull(logger, nameof(logger));

            var env  = new Dictionary <string, string>();
            var root = Environment.GetEnvironmentVariable("VSINSTALLDIR");

#if DEBUG
            logger.SendMessage(TestMessageLevel.Informational, $"VSINSTALLDIR: {root}");
#endif

            if (!string.IsNullOrEmpty(root))
            {
                env["VsInstallRoot"]           = root;
                env["MSBuildExtensionsPath32"] = Path.Combine(root, "MSBuild");
            }

            using (var buildEngine = new MSBuild.ProjectCollection(env))
            {
                try
                {
                    // Load all the test containers passed in (.njsproj msbuild files)
                    foreach (var source in sources)
                    {
                        var cleanPath = source.Trim('\'', '"');
                        buildEngine.LoadProject(cleanPath);
                    }

                    FrameworkDiscoverer frameworkDiscoverer = null;

                    foreach (var proj in buildEngine.LoadedProjects)
                    {
                        var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, "."));

                        var testItems = new Dictionary <string, HashSet <string> >(StringComparer.OrdinalIgnoreCase);

                        var testRoot      = proj.GetProperty(NodeProjectProperty.TestRoot)?.EvaluatedValue;
                        var testFramework = proj.GetProperty(NodeProjectProperty.TestFramework)?.EvaluatedValue;

                        if (!string.IsNullOrEmpty(testRoot) && string.IsNullOrEmpty(testFramework))
                        {
                            logger.SendMessage(TestMessageLevel.Warning, $"TestRoot specified for '{Path.GetFileName(proj.FullPath)}' but no TestFramework.");
                        }

                        // Provide all files to the test analyzer
                        foreach (var item in proj.Items)
                        {
                            string testFrameworkName;
                            string fileAbsolutePath;
                            if (!string.IsNullOrEmpty(testRoot) && !string.IsNullOrEmpty(testFramework))
                            {
                                testFrameworkName = testFramework;
                                var testRootPath = Path.GetFullPath(Path.Combine(proj.DirectoryPath, testRoot));

                                try
                                {
                                    fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                                }
                                catch (ArgumentException)
                                {
                                    // .Net core projects include invalid paths, ignore them and continue checking the items.
                                    continue;
                                }

                                if (!fileAbsolutePath.StartsWith(testRootPath, StringComparison.OrdinalIgnoreCase))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                //Check to see if this is a TestCase
                                testFrameworkName = item.GetMetadataValue("TestFramework");
                                if (!TestFramework.IsValidTestFramework(testFrameworkName))
                                {
                                    continue;
                                }
                                fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                            }

                            var typeScriptTest = TypeScript.TypeScriptHelpers.IsTypeScriptFile(fileAbsolutePath);
                            if (typeScriptTest)
                            {
                                fileAbsolutePath = TypeScript.TypeScriptHelpers.GetTypeScriptBackedJavaScriptFile(proj, fileAbsolutePath);
                            }
                            else if (!StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(fileAbsolutePath), ".js"))
                            {
                                continue;
                            }

                            if (!testItems.TryGetValue(testFrameworkName, out var fileList))
                            {
                                fileList = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                                testItems.Add(testFrameworkName, fileList);
                            }
                            fileList.Add(fileAbsolutePath);
                        }

                        if (testItems.Any())
                        {
                            frameworkDiscoverer = frameworkDiscoverer ?? new FrameworkDiscoverer();

                            var nodeExePath = Nodejs.GetAbsoluteNodeExePath(projectHome, proj.GetPropertyValue(NodeProjectProperty.NodeExePath));
                            if (string.IsNullOrEmpty(nodeExePath))
                            {
                                // if nothing specified in the project fallback to environment
                                nodeExePath = Nodejs.GetPathToNodeExecutableFromEnvironment();
                            }

                            this.DiscoverTests(testItems, frameworkDiscoverer, discoverySink, logger, nodeExePath, proj.FullPath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.SendMessage(TestMessageLevel.Error, ex.Message);
                    throw;
                }
                finally
                {
                    // Disposing buildEngine does not clear the document cache in
                    // VS 2013, so manually unload all projects before disposing.
                    buildEngine.UnloadAllProjects();
                }
            }
        }
示例#51
0
文件: Toolset.cs 项目: raj581/Marvin
 public Toolset(string toolsVersion, string toolsPath,
                IDictionary <string, string> buildProperties, ProjectCollection projectCollection,
                string msbuildOverrideTasksPath)
 {
     throw new NotImplementedException();
 }
示例#52
0
文件: Toolset.cs 项目: raj581/Marvin
 public Toolset(string toolsVersion, string toolsPath,
                ProjectCollection projectCollection, string msbuildOverrideTasksPath)
 {
     throw new NotImplementedException();
 }
示例#53
0
 public static string GetMetadataValueEscaped(ProjectMetadata metadatum)
 {
     return(ProjectCollection.Escape(metadatum.EvaluatedValue));
 }
示例#54
0
        /// <summary>
        /// ITestDiscover, Given a list of test sources this method pulls out the test cases
        /// </summary>
        /// <param name="sources">List of test sources passed from client (Client can be VS or command line)</param>
        /// <param name="discoveryContext">Context and runSettings for current run.  Discoverer pulls out the tests based on current context</param>
        /// <param name="logger">Used to relay messages to registered loggers</param>
        /// <param name="discoverySink">Callback used to notify client upon discovery of test cases</param>
        public void DiscoverTests(IEnumerable <string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, "sources");
            ValidateArg.NotNull(discoverySink, "discoverySink");
            ValidateArg.NotNull(logger, "logger");

            var env  = new Dictionary <string, string>();
            var root = Environment.GetEnvironmentVariable(NodejsConstants.NodeToolsVsInstallRootEnvironmentVariable);

            if (!string.IsNullOrEmpty(root))
            {
                env["VsInstallRoot"]           = root;
                env["MSBuildExtensionsPath32"] = Path.Combine(root, "MSBuild");
            }

            using (var buildEngine = new MSBuild.ProjectCollection(env))
            {
                try
                {
                    // Load all the test containers passed in (.njsproj msbuild files)
                    foreach (var source in sources)
                    {
                        buildEngine.LoadProject(source);
                    }

                    foreach (var proj in buildEngine.LoadedProjects)
                    {
                        var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, "."));

                        var testItems = new Dictionary <string, List <TestFileEntry> >(StringComparer.OrdinalIgnoreCase);
                        // Provide all files to the test analyzer
                        foreach (var item in proj.Items.Where(item => item.ItemType == "Compile" || item.ItemType == "TypeScriptCompile"))
                        {
                            //Check to see if this is a TestCase
                            var value = item.GetMetadataValue("TestFramework");
                            if (!TestContainerDiscoverer.IsValidTestFramework(value))
                            {
                                continue;
                            }
                            var fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                            var typeScriptTest   = TypeScript.TypeScriptHelpers.IsTypeScriptFile(fileAbsolutePath);
                            if (typeScriptTest)
                            {
                                fileAbsolutePath = TypeScript.TypeScriptHelpers.GetTypeScriptBackedJavaScriptFile(proj, fileAbsolutePath);
                            }
                            else if (!Path.GetExtension(fileAbsolutePath).Equals(".js", StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                            List <TestFileEntry> fileList;
                            if (!testItems.TryGetValue(value, out fileList))
                            {
                                fileList = new List <TestFileEntry>();
                                testItems.Add(value, fileList);
                            }
                            fileList.Add(new TestFileEntry(fileAbsolutePath, typeScriptTest));
                        }

                        DiscoverTests(testItems, proj, discoverySink, logger);
                    }
                }
                catch (Exception ex)
                {
                    logger.SendMessage(TestMessageLevel.Error, ex.Message);
                    throw;
                }
                finally
                {
                    // Disposing buildEngine does not clear the document cache in
                    // VS 2013, so manually unload all projects before disposing.
                    buildEngine.UnloadAllProjects();
                }
            }
        }
示例#55
0
 public Project(string projectFile, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection)
     : this(projectFile, globalProperties, toolsVersion, projectCollection, ProjectLoadSettings.Default)
 {
 }
示例#56
0
        public static string GetMetadataValueEscaped(ProjectItemDefinition item, string name)
        {
            var md = item.Metadata.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            return(md != null?ProjectCollection.Escape(md.EvaluatedValue) : null);
        }
示例#57
0
 public Project(XmlReader xml, IDictionary <string, string> globalProperties,
                string toolsVersion, ProjectCollection projectCollection,
                ProjectLoadSettings loadSettings)
     : this(ProjectRootElement.Create(xml), globalProperties, toolsVersion, projectCollection, loadSettings)
 {
 }
示例#58
0
        public void DiscoverTests(IEnumerable <string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, "sources");
            ValidateArg.NotNull(discoverySink, "discoverySink");

            var buildEngine = new MSBuild.ProjectCollection();

            try {
                // Load all the test containers passed in (.pyproj msbuild files)
                foreach (string source in sources)
                {
                    buildEngine.LoadProject(source);
                }

                foreach (var proj in buildEngine.LoadedProjects)
                {
                    using (var provider = new MSBuildProjectInterpreterFactoryProvider(_interpreterService, proj)) {
                        try {
                            provider.DiscoverInterpreters();
                        } catch (InvalidDataException) {
                            // This exception can be safely ignored here.
                        }
                        var factory = provider.ActiveInterpreter;
                        if (factory == _interpreterService.NoInterpretersValue)
                        {
                            if (logger != null)
                            {
                                logger.SendMessage(TestMessageLevel.Warning, "No interpreters available for project " + proj.FullPath);
                            }
                            continue;
                        }

                        var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, proj.GetPropertyValue(PythonConstants.ProjectHomeSetting) ?? "."));

                        // Do the analysis even if the database is not up to date. At
                        // worst, we'll get no results.
                        using (var analyzer = new TestAnalyzer(
                                   factory,
                                   proj.FullPath,
                                   projectHome,
                                   TestExecutor.ExecutorUri
                                   )) {
                            // Provide all files to the test analyzer
                            foreach (var item in proj.GetItems("Compile"))
                            {
                                string fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                                string fullName;

                                try {
                                    fullName = ModulePath.FromFullPath(fileAbsolutePath).ModuleName;
                                } catch (ArgumentException) {
                                    if (logger != null)
                                    {
                                        logger.SendMessage(TestMessageLevel.Warning, "File has an invalid module name: " + fileAbsolutePath);
                                    }
                                    continue;
                                }

                                try {
                                    using (var reader = new StreamReader(fileAbsolutePath)) {
                                        analyzer.AddModule(fullName, fileAbsolutePath, reader);
                                    }
                                } catch (FileNotFoundException) {
                                    // user deleted file, we send the test update, but the project
                                    // isn't saved.
#if DEBUG
                                } catch (Exception ex) {
                                    if (logger != null)
                                    {
                                        logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                        logger.SendMessage(TestMessageLevel.Informational, ex.ToString());
                                    }
                                }
#else
                                } catch (Exception) {
                                    if (logger != null)
                                    {
                                        logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                    }
                                }
#endif
                            }
示例#59
0
        /// <summary>
        /// Generates the solution file with the specified amount of space remaining relative
        /// to MAX_PATH.
        /// </summary>
        /// <param name="solutionName">The solution name to be created</param>
        /// <param name="pathSpaceRemaining">The amount of path space remaining, or -1 to generate normally</param>
        /// <param name="toGenerate">The projects to be incldued in the generated solution</param>
        /// <returns></returns>
        public static SolutionFile Generate(string solutionName, int pathSpaceRemaining, params ISolutionElement[] toGenerate)
        {
            List <MSBuild.Project> projects = new List <MSBuild.Project>();
            var location = TestData.GetTempPath(randomSubPath: true);

            if (pathSpaceRemaining >= 0)
            {
                int targetPathLength = 260 - pathSpaceRemaining;
                location = location + new string('X', targetPathLength - location.Length);
            }
            System.IO.Directory.CreateDirectory(location);

            MSBuild.ProjectCollection collection = new MSBuild.ProjectCollection();
            // VisualStudioVersion property may not be set in mock tests
            collection.SetGlobalProperty("VisualStudioVersion", AssemblyVersionInfo.VSVersion);
            foreach (var project in toGenerate)
            {
                projects.Add(project.Save(collection, location));
            }

#if DEV10
            StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 11.00\r\n\u0023 Visual Studio 2010\r\n");
#elif DEV11
            StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2012\r\n");
#elif DEV12
            StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 2013\r\nVisualStudioVersion = 12.0.20827.3\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#elif DEV14
            StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 14\r\nVisualStudioVersion = 14.0.25123.0\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#elif DEV15
            StringBuilder slnFile = new StringBuilder("\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n\u0023 Visual Studio 15\r\nVisualStudioVersion = 15.0.25424.0\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\n");
#else
#error Unsupported VS version
#endif
            for (int i = 0; i < projects.Count; i++)
            {
                if (toGenerate[i].Flags.HasFlag(SolutionElementFlags.ExcludeFromSolution))
                {
                    continue;
                }

                var project         = projects[i];
                var projectTypeGuid = toGenerate[i].TypeGuid;

                slnFile.AppendFormat(@"Project(""{0}"") = ""{1}"", ""{2}"", ""{3}""
EndProject
", projectTypeGuid.ToString("B").ToUpperInvariant(),
                                     project != null ? Path.GetFileNameWithoutExtension(project.FullPath) : toGenerate[i].Name,
                                     project != null ? CommonUtils.GetRelativeFilePath(location, project.FullPath): toGenerate[i].Name,
                                     (project != null ? Guid.Parse(project.GetProperty("ProjectGuid").EvaluatedValue) : Guid.NewGuid()).ToString("B").ToUpperInvariant()
                                     );
            }
            slnFile.Append(@"Global
\tGlobalSection(SolutionConfigurationPlatforms) = preSolution
\t\tDebug|Any CPU = Debug|Any CPU
\t\tRelease|Any CPU = Release|Any CPU
\tEndGlobalSection
\tGlobalSection(ProjectConfigurationPlatforms) = postSolution
");
            for (int i = 0; i < projects.Count; i++)
            {
                if (toGenerate[i].Flags.HasFlag(SolutionElementFlags.ExcludeFromConfiguration))
                {
                    continue;
                }

                var project = projects[i];
                slnFile.AppendFormat(@"\t\t{0:B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
\t\t{0}.Debug|Any CPU.Build.0 = Debug|Any CPU
\t\t{0}.Release|Any CPU.ActiveCfg = Release|Any CPU
\t\t{0}.Release|Any CPU.Build.0 = Release|Any CPU
", Guid.Parse(project.GetProperty("ProjectGuid").EvaluatedValue).ToString("B").ToUpperInvariant());
            }

            slnFile.Append(@"\tEndGlobalSection
\tGlobalSection(SolutionProperties) = preSolution
\t\tHideSolutionNode = FALSE
\tEndGlobalSection
EndGlobal
");

            collection.UnloadAllProjects();
            collection.Dispose();

            var slnFilename = Path.Combine(location, solutionName + ".sln");
            File.WriteAllText(slnFilename, slnFile.ToString().Replace("\\t", "\t"), Encoding.UTF8);
            return(new SolutionFile(slnFilename, toGenerate));
        }
示例#60
-1
        public void Test_1()
        {
            var projectFileName = TestDirectory + @"GlueTestProject\GlueTestProject\GlueTestProject\GlueTestProject.csproj";

            //Start up Glue
            AutoGlue.Start();
            ProjectLoader.Self.LoadProject(projectFileName);

            //Build Project
            var pc = new ProjectCollection();

            var fileLogger = new OutputLogger();
            pc.RegisterLogger(fileLogger);

            var p = pc.LoadProject(projectFileName);
            p.SetProperty("Configuration", "UnitTests");
            Assert.AreEqual(true, p.Build(), "Failed to build project.");

            //Run Project
            var proc = new Process
                           {
                               StartInfo =
                                   {
                                       UseShellExecute = false,
                                       FileName =
                                           TestDirectory +
                                           @"GlueTestProject\GlueTestProject\GlueTestProject\bin\x86\Debug\GlueTestProject.exe",
                                       RedirectStandardError = true
                                   }
                           };
            proc.Start();
            proc.WaitForExit();
            Trace.Write(proc.StandardError.ReadToEnd());
            Assert.AreEqual(0, proc.ExitCode);
        }