Пример #1
1
		public CSharpProject(Solution solution, string title, string fileName)
		{
			this.Solution = solution;
			this.Title = title;
			this.FileName = fileName;
			
			var p = new Microsoft.Build.Evaluation.Project(fileName);
			this.AssemblyName = p.GetPropertyValue("AssemblyName");
			this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false;
			this.CompilerSettings.CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false;
			foreach (string symbol in p.GetPropertyValue("DefineConstants").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
				this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
			}
			foreach (var item in p.GetItems("Compile")) {
				Files.Add(new CSharpFile(this, Path.Combine(p.DirectoryPath, item.EvaluatedInclude)));
			}
			List<IAssemblyReference> references = new List<IAssemblyReference>();
			string mscorlib = FindAssembly(Program.AssemblySearchPaths, "mscorlib");
			if (mscorlib != null) {
				references.Add(Program.LoadAssembly(mscorlib));
			} else {
				Console.WriteLine("Could not find mscorlib");
			}
			bool hasSystemCore = false;
			foreach (var item in p.GetItems("Reference")) {
				string assemblyFileName = null;
				if (item.HasMetadata("HintPath")) {
					assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath"));
					if (!File.Exists(assemblyFileName))
						assemblyFileName = null;
				}
				if (assemblyFileName == null) {
					assemblyFileName = FindAssembly(Program.AssemblySearchPaths, item.EvaluatedInclude);
				}
				if (assemblyFileName != null) {
					if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
						hasSystemCore = true;
					references.Add(Program.LoadAssembly(assemblyFileName));
				} else {
					Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
				}
			}
			if (!hasSystemCore && FindAssembly(Program.AssemblySearchPaths, "System.Core") != null)
				references.Add(Program.LoadAssembly(FindAssembly(Program.AssemblySearchPaths, "System.Core")));
			foreach (var item in p.GetItems("ProjectReference")) {
				references.Add(new ProjectReference(solution, item.GetMetadataValue("Name")));
			}
			this.ProjectContent = new CSharpProjectContent()
				.SetAssemblyName(this.AssemblyName)
				.SetCompilerSettings(this.CompilerSettings)
				.AddAssemblyReferences(references)
				.UpdateProjectContent(null, Files.Select(f => f.ParsedFile));
		}
        private static void AddEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
        {
            // get the target
            var targetElement = buildProject.Xml.Targets.FirstOrDefault(
                target => target.Name.Equals(targetName, StringComparison.OrdinalIgnoreCase));

            // if the target does not exist, create the target
            if (targetElement == null)
            {
                targetElement = buildProject.Xml.AddTarget(targetName);

                // PrepareForBuild is used here because BeforeBuild does not work for VC++ projects.
                targetElement.BeforeTargets = "PrepareForBuild";

                var propertyGroup = targetElement.AddPropertyGroup();
                propertyGroup.AddProperty("ErrorText", CommonResources.EnsureImportedMessage);
            }

            var errorTask = targetElement.AddTask("Error");
            errorTask.Condition = "!Exists('" + targetsPath + "')";
            var errorText = string.Format(
                CultureInfo.InvariantCulture,
                @"$([System.String]::Format('$(ErrorText)', '{0}'))",
                targetsPath);
            errorTask.SetParameter("Text", errorText);
        }
Пример #3
0
 public BasicTests(ITestOutputHelper logger)
 {
     this.logger = logger;
     this.nuproj = Assets.FromTemplate()
                         .AssignNuProjDirectory()
                         .ToProject();
 }
        public static ActionsModule CreateFromProject(string projectFile, string outputFile, LightningDevelopmentHandle lightningDevelopmentHandle)
        {
            var engine = new Microsoft.Build.Evaluation.Project(projectFile);
            engine.Build();

            return CreateFromDll(outputFile, lightningDevelopmentHandle);
        }
        public void AddNewErrorWarningMessageElement()
        {
            MockLogger logger = new MockLogger();

            /**
             * <Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
             *   <Target Name=`Build`>
             *   </Target>
             * </Project
             */

            ProjectRootElement projectXml = ProjectRootElement.Create();
            ProjectTargetElement target = projectXml.AddTarget("Build");
            projectXml.DefaultTargets = "Build";
            projectXml.ToolsVersion = ObjectModelHelpers.MSBuildDefaultToolsVersion;

            SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.message, true, "SolutionVenusProjectNoClean");
            SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.warning, true, "SolutionParseUnknownProjectType", "proj1.csproj");
            SolutionProjectGenerator.AddErrorWarningMessageElement(target, XMakeElements.error, true, "SolutionInvalidSolutionConfiguration");

            Project project = new Project(projectXml);

            project.Build(logger);

            string code = null;
            string keyword = null;
            string text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionParseUnknownProjectType", "proj1.csproj");

            // check the error event
            Assert.AreEqual(1, logger.Warnings.Count);
            BuildWarningEventArgs warning = logger.Warnings[0];

            Assert.AreEqual(text, warning.Message);
            Assert.AreEqual(code, warning.Code);
            Assert.AreEqual(keyword, warning.HelpKeyword);

            code = null;
            keyword = null;
            text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionInvalidSolutionConfiguration");

            // check the warning event
            Assert.AreEqual(1, logger.Errors.Count);
            BuildErrorEventArgs error = logger.Errors[0];

            Assert.AreEqual(text, error.Message);
            Assert.AreEqual(code, error.Code);
            Assert.AreEqual(keyword, error.HelpKeyword);

            code = null;
            keyword = null;
            text = ResourceUtilities.FormatResourceString(out code, out keyword, "SolutionVenusProjectNoClean");

            // check the message event
            Assert.IsTrue(logger.FullLog.Contains(text), "Log should contain the regular message");
        }
Пример #6
0
 private static void AddFeatureFileLinkToIntelliSenseProject(string featureFilePath, string featureDir, string pathToIntelliSenseProject)
 {
     _csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);
     featureFilePath = MakeLinkRelativeToIntelliSenseProject(featureFilePath, featureDir);
     var featureFileLink = featureFilePath.Replace(@"..\", string.Empty);
     if (!_csProj.Items.Any(item => item.GetMetadataValue("Link") == featureFileLink))
     {
         _csProj.AddItem("None", featureFilePath, new Dictionary<string, string> { { "Link", featureFileLink } });
         _isDirtyCsProj = true;
     }
 }
Пример #7
0
 /// <summary>
 /// Builds this project, using the default targets and the given loggers.
 /// </summary>
 /// <param name="loggers">An enumerator over all loggers to be used during the build.</param>
 /// <returns>
 /// Returns true on success; false otherwise.
 /// </returns>
 public bool Build(IEnumerable<ILogger> loggers)
 {
     var result = false;
     this.SwapMSBuildTasks();
     using (var reader = this.Document.CreateReader())
     {
         reader.MoveToContent();
         var innerProject = new Microsoft.Build.Evaluation.Project(reader);
         result = innerProject.Build(loggers.Prepend(this.Logger));
         reader.Close();
     }
     return result;
 }
Пример #8
0
        private static void AddFilesToCppProject(string pathToFile, string featureDir, string pathToCppProject)
        {
            _cppProj = _cppProj ?? GetUnloadedProject(pathToCppProject);

            pathToFile = MakeFeatureDirRelativeToCppProject(pathToFile, featureDir);

            string type = CppFileType(pathToFile);

            if (!_cppProj.GetItems(type).Any(item => item.UnevaluatedInclude == pathToFile))
            {
                _cppProj.AddItem(type, pathToFile);
                _isDirtyCppProj = true;
            }
        }
Пример #9
0
        /// <summary>
        /// Toes the hierarchy.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <returns></returns>
        public static IVsHierarchy ToHierarchy(EnvDTE.Project project)
        {
            if (project == null) throw new ArgumentNullException("project");

            // DTE does not expose the project GUID that exists at in the msbuild project file.
            Microsoft.Build.Evaluation.Project msproject = new Microsoft.Build.Evaluation.Project();
            msproject.FullPath = project.FileName;
            
            string guid = msproject.GetPropertyValue("ProjectGuid");

            IServiceProvider serviceProvider = new ServiceProvider(project.DTE as
                Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

            return VsShellUtilities.GetHierarchy(serviceProvider, new Guid(guid));
        }
        /// <summary>
        /// Removes the Import element from the project file.
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        public static void RemoveImportStatement(MsBuildProject project, string targetsPath)
        {
            if (project.Xml.Imports != null)
            {
                // search for this import statement and remove it
                var importElement = project.Xml.Imports.FirstOrDefault(
                    import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));

                if (importElement != null)
                {
                    importElement.Parent.RemoveChild(importElement);
                    NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(project, targetsPath);
                    project.ReevaluateIfNecessary();
                }
            }
        }
Пример #11
0
        private static void ConfigProjectImport(Project project, string targetRelativePath, string configTransformTargetFile)
        {
            // clear out any existing value
            var importPathMSBuildProperty = "ConfigTransformTargetPath";
            var msbuildProp = project.Xml.Properties.Where(x => x.Name == importPathMSBuildProperty).ToArray();
            msbuildProp.Delete();

            // creates a property to store the target file path
            var importPath = $"$({importPathMSBuildProperty})\\{configTransformTargetFile}";
            project.Xml.AddProperty(importPathMSBuildProperty, targetRelativePath);

            // create import element with exists condition and add as last project import
            var importXmlElement = project.Xml.CreateImportElement(importPath);
            importXmlElement.Condition = $"Exists('{importPath}')";
            project.Xml.InsertAfterChild(importXmlElement, project.Xml.Imports.Last());
        }
Пример #12
0
		public CSharpProject(Solution solution, string title, string fileName)
		{
			// Normalize the file name
			fileName = Path.GetFullPath(fileName);
			
			this.Solution = solution;
			this.Title = title;
			this.FileName = fileName;
			
			// Use MSBuild to open the .csproj
			var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
			// Figure out some compiler settings
			this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
			this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
			this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
			string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
			foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
				this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
			
			// Initialize the unresolved type system
			IProjectContent pc = new CSharpProjectContent();
			pc = pc.SetAssemblyName(this.AssemblyName);
			pc = pc.SetProjectFileName(fileName);
			pc = pc.SetCompilerSettings(this.CompilerSettings);
			// Parse the C# code files
			foreach (var item in msbuildProject.GetItems("Compile")) {
				var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
				Files.Add(file);
			}
			// Add parsed files to the type system
			pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));
			
			// Add referenced assemblies:
			foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) {
				IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
				pc = pc.AddAssemblyReferences(new [] { assembly });
			}
			
			// Add project references:
			foreach (var item in msbuildProject.GetItems("ProjectReference")) {
				string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
				// Normalize the path; this is required to match the name with the referenced project's file name
				referencedFileName = Path.GetFullPath(referencedFileName);
				pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
			}
			this.ProjectContent = pc;
		}
        /// <summary>
        /// Adds an Import element to this project file if it doesn't already exist.            
        /// </summary>
        /// <param name="project">The project file.</param>
        /// <param name="targetsPath">The path to the imported file.</param>
        /// <param name="location">The location where the Import is added.</param>
        public static void AddImportStatement(MsBuildProject project, string targetsPath, ProjectImportLocation location)
        {
            if (project.Xml.Imports == null ||
                project.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
            {
                ProjectImportElement pie = project.Xml.AddImport(targetsPath);
                pie.Condition = "Exists('" + targetsPath + "')";
                if (location == ProjectImportLocation.Top)
                {
                    // There's no public constructor to create a ProjectImportElement directly.
                    // So we have to cheat by adding Import at the end, then remove it and insert at the beginning
                    pie.Parent.RemoveChild(pie);
                    project.Xml.InsertBeforeChild(pie, project.Xml.FirstChild);
                }

                NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(project, targetsPath);
                project.ReevaluateIfNecessary();
            }
        }
        public void GetProject(string ProjectPath)
        {
            try
            {
                if (Project == null)
                {
                    if (string.IsNullOrEmpty(ProjectPath))
                    {
                        throw new ArgumentNullException("Project Path is not defined");
                    }

                    Project = new Microsoft.Build.Evaluation.Project(ProjectPath, null, "14.0");
                    var zz = Project.ToolsVersion;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #15
0
        private void StyleCopCoreAddSettingsPages(object sender, AddSettingsPagesEventArgs e)
        {
            Param.Ignore(sender);
            Param.AssertNotNull(e, "e");

            Project project  = ProjectUtilities.GetActiveProject();
            string  fullName = ProjectUtilities.GetProjectFullName(project);

            if (string.IsNullOrEmpty(fullName))
            {
                return;
            }

            project.Save();

            var proj = new Microsoft.Build.Evaluation.Project(
                project.FullName, null, null, new Microsoft.Build.Evaluation.ProjectCollection());

            e.Add(new BuildIntegrationOptions(proj));
        }
Пример #16
0
        //---------------------------------------------------------------------------

        public bool AddFile(string source, string destination)
        {
            try
            {
                if (!string.IsNullOrEmpty(source) && !source.Equals(destination))
                {
                    File.Copy(source, Path.Combine(RootPath, destination));
                }

                string path    = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\", "EvershockGame/EvershockGame.csproj"));
                var    project = new Microsoft.Build.Evaluation.Project(@path);
                project.AddItem("Content", string.Format(@"Content\{0}", destination.Replace('/', '\\')), new List <KeyValuePair <string, string> > {
                    new KeyValuePair <string, string>("CopyToOutputDirectory", "PreserveNewest")
                });
                project.Save();
                return(true);
            }
            catch (Exception e) { }
            return(false);
        }
Пример #17
0
        public static bool UpgradeGeneratedItems(Microsoft.Build.Evaluation.Project project, string outputDir, string ext, string itemType)
        {
            string projectDir = Path.GetDirectoryName(project.FullPath);
            bool   modified   = false;
            var    sliceItems = project.AllEvaluatedItems.Where(item => item.ItemType.Equals("SliceCompile"));

            foreach (var sliceItem in sliceItems)
            {
                var generatedPath = FileUtil.RelativePath(projectDir,
                                                          Path.Combine(outputDir, string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(sliceItem.EvaluatedInclude), ext)));
                var generated = project.AllEvaluatedItems.FirstOrDefault(
                    item => item.ItemType.Equals(itemType) && item.EvaluatedInclude.Equals(generatedPath));
                if (generated != null)
                {
                    generated.SetMetadataValue("SliceCompileSource", sliceItem.EvaluatedInclude);
                    modified = true;
                }
            }
            return(modified);
        }
        private void AddFileToProjest(string projectPath, string filePath)
        {
            Project pr;

            if (OpenProjectsMap.ContainsKey(projectPath))
            {
                pr = OpenProjectsMap[projectPath];
            }
            else
            {
                pr = new Project(projectPath);
                OpenProjectsMap.Add(projectPath, pr);
            }

            pr.ReevaluateIfNecessary();
            pr.DisableMarkDirty = true;

            pr.AddItem("Compile", filePath);
            pr.Save();
        }
Пример #19
0
        public void IncludeProject()
        {
            var projFile = new Microsoft.Build.Evaluation.Project(ProjFile);

            foreach (string file in System.IO.Directory.GetFiles(Directory, "*.feature", SearchOption.AllDirectories))
            {
                var fileName         = Path.GetFileName(file);
                var relativeFilePath = MakeRelative(file, ProjFile).Replace("/", "\\");
                var projectItem      = projFile.Items.FirstOrDefault(i => i.EvaluatedInclude == relativeFilePath);
                if (projectItem == null)
                {
                    projFile.AddItem("None", relativeFilePath, new[]
                    {
                        new KeyValuePair <string, string>("Generator", "SpecFlowSingleFileGenerator"),
                        new KeyValuePair <string, string>("LastGenOutput", $"{fileName}.cs")
                    });
                }
            }
            projFile.Save();
        }
Пример #20
0
        private static void SetTargetFrameworkIfNeeded(MSB.Evaluation.Project evaluatedProject)
        {
            var targetFramework  = evaluatedProject.GetPropertyValue(PropertyNames.TargetFramework);
            var targetFrameworks = PropertyConverter.SplitList(evaluatedProject.GetPropertyValue(PropertyNames.TargetFrameworks), ';');

            // If the project supports multiple target frameworks and specific framework isn't
            // selected, we must pick one before execution. Otherwise, the ResolveReferences
            // target might not be available to us.
            if (string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length > 0)
            {
                // For now, we'll just pick the first target framework. Eventually, we'll need to
                // do better and potentially allow OmniSharp hosts to select a target framework.
                targetFramework = targetFrameworks[0];
                evaluatedProject.SetProperty(PropertyNames.TargetFramework, targetFramework);
            }
            else if (!string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length == 0)
            {
                targetFrameworks = ImmutableArray.Create(targetFramework);
            }
        }
Пример #21
0
        private void AddSolutionDirProperty(MsBuildProject buildProject)
        {
            const string solutiondir = "SolutionDir";

            if (buildProject.Xml.Properties == null ||
                buildProject.Xml.Properties.All(p => p.Name != solutiondir))
            {
                string relativeSolutionPath = PathUtility.GetRelativePath(
                    buildProject.FullPath,
                    PathUtility.EnsureTrailingSlash(_solutionManager.SolutionDirectory));
                relativeSolutionPath = PathUtility.EnsureTrailingSlash(relativeSolutionPath);

                var solutionDirProperty = buildProject.Xml.AddProperty(solutiondir, relativeSolutionPath);
                solutionDirProperty.Condition =
                    String.Format(
                        CultureInfo.InvariantCulture,
                        @"$({0}) == '' Or $({0}) == '*Undefined*'",
                        solutiondir);
            }
        }
Пример #22
0
        private void EnablePackageRestore(Project project)
        {
            if (project.IsWebSite())
            {
                // Can't do anything with Website
                // Also, the Javascript Metro project system has some weird bugs
                // that cause havoc with the package restore mechanism
                return;
            }

            if (project.IsJavaScriptProject())
            {
                EnablePackageRestoreForJavaScriptProject(project);
            }
            else
            {
                MsBuildProject buildProject = project.AsMSBuildProject();
                EnablePackageRestore(project, buildProject, saveProjectWhenDone: true);
            }
        }
        public void ExecuteWithoutHost()
        {
            ScannerTask target = new ScannerTask();

            // Create the term tables and target files.
            string termFile1 = Utilities.CreateTempFile(CreateTermTableXml("countries", 2, "Geopolitical", "comment"));
            string termFile2 = Utilities.CreateTempFile(CreateTermTableXml("shoot", 3, "Profanity", "comment"));

            string scanFile1 = Utilities.CreateTempTxtFile("the word 'countries' should produce a hit");
            string scanFile2 = Utilities.CreateTempTxtFile("the word 'shoot' should produce a hit");

            // Create the project that will execute the task.
            Microsoft.Build.Evaluation.Project project = Utilities.SetupMSBuildProject(new string[] { scanFile1, scanFile2 }, new string[] { termFile1, termFile2 });

            // Set up a custom logger to capture the output.
            MockLogger logger = new MockLogger();

            project.ProjectCollection.RegisterLogger(logger);
            int errors   = 0;
            int warnings = 0;
            int messages = 0;

            logger.OnError += delegate(object sender, BuildErrorEventArgs args)
            {
                ++errors;
            };
            logger.OnWarning += delegate(object sender, BuildWarningEventArgs args)
            {
                ++warnings;
            };
            logger.OnMessage += delegate(object sender, BuildMessageEventArgs args)
            {
                ++messages;
            };

            project.Build("AfterBuild");

            Assert.AreEqual(0, errors, "Build did not log expected number of errors.");
            Assert.AreEqual(2, warnings, "Build did not log expected number of warnings.");
            Assert.AreEqual(2, messages, "Build did not log expected number of messages.");
        }
Пример #24
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Microsoft.Build.Evaluation.Project buildProject = buildProjectInfo.GetValue(testEnv.Project, new object[0]) as Microsoft.Build.Evaluation.Project;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                MethodInfo itemMapGetter           = typeof(VisualStudio.Project.ProjectNode).GetProperty("ItemIdMap", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true);
                Microsoft.VisualStudio.Shell.EventSinkCollection itemMap = (Microsoft.VisualStudio.Shell.EventSinkCollection)itemMapGetter.Invoke(testEnv.Project, new object[0]);
                uint itemID = itemMap.Add(node);

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Пример #25
0
        static bool?GetBoolProperty(Microsoft.Build.Evaluation.Project p, string propertyName)
        {
            if (FixUtil.Instance.NeedFix("CSharpProject.GetBoolProperty"))
            {
                string strParameter = string.Format("CSharpProject,GetBoolProperty,{0},{1},{2}", typeof(object), typeof(Microsoft.Build.Evaluation.Project), typeof(string));
                FixUtil.Instance.Fix(strParameter, null, p, propertyName);
                return;
            }

            string val = p.GetPropertyValue(propertyName);
            bool   result;

            if (bool.TryParse(val, out result))
            {
                return(result);
            }
            else
            {
                return(null);
            }
        }
Пример #26
0
        /// <summary>
        /// The resolved type system for this project.
        /// This field is initialized once all projects have been loaded (in Solution constructor).
        /// </summary>
        public CSharpProject(Solution solution, string title, string fileName)
        {
            // Normalize the file name
            fileName = Path.GetFullPath(fileName);

            this.Solution = solution;
            this.Title = title;
            this.FileName = fileName;

            // Use MSBuild to open the .csproj
            var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
            // Figure out some compiler settings
            this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");

            // Parse the C# code files
            foreach (var item in msbuildProject.GetItems("Compile"))
            {
                var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
                Files.Add(file);
            }
        }
Пример #27
0
        private void EnsureImport(Microsoft.Build.Evaluation.Project project, string importProjectPath)
        {
            // Ensure import is present, replace existing if found.
            var fileName       = Path.GetFileName(importProjectPath);
            var existingImport = project.Xml.Imports.Cast <ProjectImportElement>().FirstOrDefault(i => i.Project.EndsWith(fileName));

            if (existingImport != null)
            {
                _Logger.LogInfo(string.Format("The existing import will be upgraded for: {0}", fileName));
                project.Xml.RemoveChild(existingImport);
            }

            var projectUri    = new Uri(string.Format("file://{0}", project.FullPath));
            var importFileUri = new Uri(string.Format("file://{0}", importProjectPath));

            var relativeImportFile = projectUri.MakeRelativeUri(importFileUri).ToString().Replace('/', '\\');

            project.Xml.AddImport(relativeImportFile);

            _Logger.LogInfo(string.Format("Successfully imported: {0}", relativeImportFile));
        }
Пример #28
0
        void SetCompilerSettings(Microsoft.Build.Evaluation.Project p)
        {
            CompilerSettings = new CompilerSettings
            {
                AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false,
                CheckForOverflow  = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false
            };
            string[] defines = p.GetPropertyValue("DefineConstants")
                               .Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string define in defines)
            {
                CompilerSettings.ConditionalSymbols.Add(define);
            }

            var config = ConfigurationLoader.Config;

            foreach (var define in config.Defines)
            {
                CompilerSettings.ConditionalSymbols.Add(define);
            }
        }
Пример #29
0
        private static async Task DoWorkInWriterLockInternal(Project project, IVsHierarchy hierarchy, Action <MsBuildProject> action)
        {
            UnconfiguredProject unconfiguredProject = GetUnconfiguredProject((IVsProject)hierarchy);

            if (unconfiguredProject != null)
            {
                var service = unconfiguredProject.ProjectService.Services.ProjectLockService;
                if (service != null)
                {
                    // WriteLockAsync will move us to a background thread.
                    using (ProjectWriteLockReleaser x = await service.WriteLockAsync())
                    {
                        await x.CheckoutAsync(unconfiguredProject.FullPath);

                        ConfiguredProject configuredProject = await unconfiguredProject.GetSuggestedConfiguredProjectAsync();

                        MsBuildProject buildProject = await x.GetProjectAsync(configuredProject);

                        if (buildProject != null)
                        {
                            action(buildProject);
                        }

                        await x.ReleaseAsync();
                    }

                    // perform the save synchronously
                    await Task.Run(() =>
                    {
                        // move to the UI thread for the rest of this method
                        unconfiguredProject.ProjectService.Services.ThreadingPolicy.SwitchToUIThread();

                        var fileSystem = new PhysicalFileSystem(@"c:\");
                        fileSystem.MakeFileWritable(project.FullName);
                        project.Save();
                    }
                                   );
                }
            }
        }
Пример #30
0
        public virtual void RunFinished()
        {
            try {
                var proj = item.ContainingProject;
                var dte  = item.DTE;

                //foreach (var x in proj.Properties.OfType<Property>()) System.Diagnostics.Debugger.Log(1, "Debug", x.Name + "\n");

                CopyBin();
                ConfigureProject(proj);
                CopyDemo();
                proj.Save();

                dte.ExecuteCommand("File.SaveAll", string.Empty);

                var filename = proj.FullName;
                var bproj    = new Microsoft.Build.Evaluation.Project(filename);

                var imppath = Path.Combine(MSBuildExtensionsPath, target);

                if (bproj.Imports.Any(imp => imp.ImportedProject.FullPath == imppath))
                {
                    return;                                                                                    // import is already there, so no need to modify project any further.
                }
                ModifyWebConfig();

                // select project
                string solutionName = Path.GetFileNameWithoutExtension(dte.Solution.FullName);
                dte.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate();
                ((EnvDTE80.DTE2)dte).ToolWindows.SolutionExplorer.GetItem(solutionName + @"\" + proj.Name).Select(vsUISelectionType.vsUISelectionTypeSelect);

                //Because modify the open *.csproj file outside of the IDE will pop up a window to let you reload the file.
                //IExecute Command to unload the project before modifying the *.csproj file. And reload after the *.csproj has already updated.
                bproj.Xml.AddImport(imppath);
                dte.ExecuteCommand("Project.UnloadProject", string.Empty);
                bproj.Save();
                dte.ExecuteCommand("Project.ReloadProject", string.Empty);
            } catch (Exception ex) {
            }
        }
Пример #31
0
            public static ProjectData Create(MSB.Evaluation.Project project)
            {
                var guid                   = PropertyConverter.ToGuid(project.GetPropertyValue(PropertyNames.ProjectGuid));
                var name                   = project.GetPropertyValue(PropertyNames.ProjectName);
                var assemblyName           = project.GetPropertyValue(PropertyNames.AssemblyName);
                var targetPath             = project.GetPropertyValue(PropertyNames.TargetPath);
                var outputPath             = project.GetPropertyValue(PropertyNames.OutputPath);
                var intermediateOutputPath = project.GetPropertyValue(PropertyNames.IntermediateOutputPath);
                var projectAssetsFile      = project.GetPropertyValue(PropertyNames.ProjectAssetsFile);
                var configuration          = project.GetPropertyValue(PropertyNames.Configuration);
                var platform               = project.GetPropertyValue(PropertyNames.Platform);
                var defaultNamespace       = project.GetPropertyValue(PropertyNames.RootNamespace);

                var targetFramework = new FrameworkName(project.GetPropertyValue(PropertyNames.TargetFrameworkMoniker));

                var targetFrameworkValue = project.GetPropertyValue(PropertyNames.TargetFramework);
                var targetFrameworks     = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.TargetFrameworks), ';');

                if (!string.IsNullOrWhiteSpace(targetFrameworkValue) && targetFrameworks.Length == 0)
                {
                    targetFrameworks = ImmutableArray.Create(targetFrameworkValue);
                }

                var languageVersion           = PropertyConverter.ToLanguageVersion(project.GetPropertyValue(PropertyNames.LangVersion));
                var allowUnsafeCode           = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.AllowUnsafeBlocks), defaultValue: false);
                var checkForOverflowUnderflow = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.CheckForOverflowUnderflow), defaultValue: false);
                var outputKind                = PropertyConverter.ToOutputKind(project.GetPropertyValue(PropertyNames.OutputType));
                var nullableContextOptions    = PropertyConverter.ToNullableContextOptions(project.GetPropertyValue(PropertyNames.Nullable));
                var documentationFile         = project.GetPropertyValue(PropertyNames.DocumentationFile);
                var preprocessorSymbolNames   = PropertyConverter.ToPreprocessorSymbolNames(project.GetPropertyValue(PropertyNames.DefineConstants));
                var suppressedDiagnosticIds   = PropertyConverter.ToSuppressedDiagnosticIds(project.GetPropertyValue(PropertyNames.NoWarn));
                var signAssembly              = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.SignAssembly), defaultValue: false);
                var assemblyOriginatorKeyFile = project.GetPropertyValue(PropertyNames.AssemblyOriginatorKeyFile);
                var treatWarningsAsErrors     = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.TreatWarningsAsErrors), defaultValue: false);

                return(new ProjectData(
                           guid, name, assemblyName, targetPath, outputPath, intermediateOutputPath, projectAssetsFile,
                           configuration, platform, targetFramework, targetFrameworks, outputKind, languageVersion, nullableContextOptions, allowUnsafeCode, checkForOverflowUnderflow,
                           documentationFile, preprocessorSymbolNames, suppressedDiagnosticIds, signAssembly, assemblyOriginatorKeyFile, treatWarningsAsErrors, defaultNamespace, ruleset: null));
            }
Пример #32
0
        private static CompilationOptions CreateCompilationOptions(Microsoft.Build.Evaluation.Project project, string languageName)
        {
            var        outputType = project.GetPropertyValue("OutputType");
            OutputKind?kind       = null;

            switch (outputType)
            {
            case "Library":
                kind = OutputKind.DynamicallyLinkedLibrary;
                break;

            case "Exe":
                kind = OutputKind.ConsoleApplication;
                break;

            case "Module":
                kind = OutputKind.NetModule;
                break;

            case "Winexe":
                kind = OutputKind.WindowsApplication;
                break;
            }

            if (kind.HasValue)
            {
                if (languageName == LanguageNames.CSharp)
                {
                    return(new CSharpCompilationOptions(kind.Value));
                }

                if (languageName == LanguageNames.VisualBasic)
                {
                    return(new VisualBasicCompilationOptions(kind.Value));
                }
            }

            return(null);
        }
Пример #33
0
        internal static void Build(string Proj)
        {
#if(FRAMEWORK40)
            var prj = new Microsoft.Build.Evaluation.Project(Proj);
            try
            {
#else
            Microsoft.Build.BuildEngine.Project prj = new Microsoft.Build.BuildEngine.Project();
            prj.Load(Proj);
#endif

                prj.SetProperty("DefaultTargets", "Build");
                prj.SetProperty("Configuration", "Debug");
                if (!prj.Build()) throw new Exception("Error building project: " + Proj + "\n");
#if(FRAMEWORK40)
            }
            finally
            {
                Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.UnloadProject(prj);
            }
#endif
        }
        private Configuration ImportConfiguration(Microsoft.Build.Evaluation.Project msbuildProject)
        {
            Configuration config = new Configuration()
            {
                Name = "Release"
            };

            var files = msbuildProject.GetItems("ClCompile");

            config.Defines  = ImportMetaData("PreprocessorDefinitions", files);
            config.Includes = ImportMetaData("AdditionalIncludeDirectories", files).ConvertAll(i => i);

            foreach (var file in files)
            {
                if (file.DirectMetadata.FirstOrDefault(m => m.Name == "PrecompiledHeader") != null)
                {
                    config.PrecompiledHeader = Path.GetFullPath(Path.Combine(msbuildProject.DirectoryPath, file.EvaluatedInclude));
                }
            }

            return(config);
        }
        private static void MigrateRuntimes(PackageSpec packageSpec, Microsoft.Build.Evaluation.Project buildProject)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            var runtimes           = packageSpec.RuntimeGraph.Runtimes;
            var supports           = packageSpec.RuntimeGraph.Supports;
            var runtimeIdentifiers = new List <string>();
            var runtimeSupports    = new List <string>();

            if (runtimes != null && runtimes.Count > 0)
            {
                runtimeIdentifiers.AddRange(runtimes.Keys);
            }

            if (supports != null && supports.Count > 0)
            {
                runtimeSupports.AddRange(supports.Keys);
            }

            var union = string.Join(";", runtimeIdentifiers.Union(runtimeSupports));

            buildProject.SetProperty("RuntimeIdentifiers", union);
        }
Пример #36
0
 private IList <string> LoadConfigurationsWithMicrosoftBuild()
 {
     Microsoft.Build.Evaluation.Project p = null;
     try {
         p = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.LoadProject(_filepath);
         var configurations = p.ConditionedProperties["Configuration"];
         var platforms      = p.ConditionedProperties["Platform"];
         return(configurations.SelectMany(configuration => platforms.Select(platform => configuration + "|" + platform)).ToList());
     } catch (Exception ex) {
         _errors.Add(ex.Message);
         return(new string[0]);
     } finally {
         if (p != null)
         {
             try {
                 Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.UnloadProject(p);
                 // ReSharper disable once EmptyGeneralCatchClause
             } catch {
             }
         }
     }
 }
Пример #37
0
        void AddProjectReferences(Microsoft.Build.Evaluation.Project p)
        {
            foreach (Microsoft.Build.Evaluation.ProjectItem item in p.GetItems("ProjectReference"))
            {
                var projectName = item.HasMetadata("Name")
                    ? item.GetMetadataValue("Name")
                    : Path.GetFileNameWithoutExtension(item.EvaluatedInclude);

                var projVal = item.GetMetadataValue("Project");
                if (projVal == null)
                {
                    continue;
                }
                var referenceGuid = Guid.Parse(projVal);
                if (referenceGuid == null)
                {
                    continue;
                }
                _logger.Debug("Adding project reference {0}, {1}", projectName, referenceGuid);
                AddReference(new ProjectReference(_solution, projectName, referenceGuid));
            }
        }
Пример #38
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                Microsoft.Build.Evaluation.Project buildProject = testEnv.Project.BuildProject;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                uint itemID = node.Id;

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Пример #39
0
        public ArrayList GetReferences(string name)
        {
            ArrayList L = new ArrayList();

            Microsoft.Build.Evaluation.Project pc = null;

            try
            {
                pc = new Microsoft.Build.Evaluation.Project(FileName);
            }
            catch (Exception e) {  }
            if (pc == null)
            {
                return(L);
            }

            string folder = Path.GetDirectoryName(FileName);

            ICollection <Microsoft.Build.Evaluation.ProjectItem> s = pc.GetItems(name);



            foreach (Microsoft.Build.Evaluation.ProjectItem p in s)
            {
                string file = Path.GetFullPath(folder + "\\" + p.EvaluatedInclude);

                string project = Path.GetFileNameWithoutExtension(file);


                file = p.EvaluatedInclude;

                L.Add(file);
            }

            pc.ProjectCollection.UnloadAllProjects();

            return(L);
        }
        static bool TryLoadProjectFromCsproj(string csprojFullPath, out Microsoft.Build.Evaluation.Project project, out string projectName, out Context.ProjectType projectType, out Context.ProjectOutputType projectOutputType)
        {
            try
            {
                Microsoft.Build.Evaluation.ProjectCollection collection = new Microsoft.Build.Evaluation.ProjectCollection();
                collection.DefaultToolsVersion = "4.0";
                Microsoft.Build.Evaluation.Project theProject = collection.LoadProject(csprojFullPath);
                string projectTypeGuids = theProject.GetPropertyValue("ProjectTypeGuids"); //cf. https://github.com/Microsoft/visualfsharp/blob/master/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectFactory.cs
                string isSilverlightApplicationString = theProject.GetPropertyValue("SilverlightApplication");

                // Get the project name:
                projectName = System.IO.Path.GetFileNameWithoutExtension(csprojFullPath);

                // Get the Project Type:
                projectType = GetProjectType(projectTypeGuids);

                // Get the project Output Type:
                Func <string, string> functionToGetAProjectProperty = (string propertyName) =>
                {
                    return(theProject.GetPropertyValue(propertyName));
                };
                projectOutputType = GetProjectOutputType(projectType, functionToGetAProjectProperty, functionToGetAProjectProperty);

                // Return the project itself as well:
                project = theProject;

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                project           = null;
                projectName       = null;
                projectType       = Context.ProjectType.Other;
                projectOutputType = Context.ProjectOutputType.Unknown;
                return(false);
            }
        }
Пример #41
0
 void AddCSharpFiles(Microsoft.Build.Evaluation.Project p)
 {
     foreach (var item in p.GetItems("Compile"))
     {
         try
         {
             string path = Path.Combine(p.DirectoryPath, item.EvaluatedInclude).ForceNativePathSeparator();
             if (File.Exists(path))
             {
                 string file = new FileInfo(path).FullName;
                 _logger.Debug("Loading " + file);
                 Files.Add(new CSharpFile(this, file));
             }
             else
             {
                 _logger.Debug("File does not exist - " + path);
             }
         } catch (NullReferenceException e)
         {
             _logger.Error(e);
         }
     }
 }
 public ProjectLoadedEventArgs(
     ProjectId id,
     MSB.Evaluation.Project project,
     Guid sessionId,
     MSB.Execution.ProjectInstance projectInstance,
     ImmutableArray <MSBuildDiagnostic> diagnostics,
     bool isReload,
     bool projectIdIsDefinedInSolution,
     ImmutableArray <string> sourceFiles,
     SemanticVersion sdkVersion,
     IEnumerable <string> references = null)
 {
     Id              = id;
     Project         = project;
     SessionId       = sessionId;
     ProjectInstance = projectInstance;
     Diagnostics     = diagnostics;
     IsReload        = isReload;
     ProjectIdIsDefinedInSolution = projectIdIsDefinedInSolution;
     References  = references;
     SourceFiles = sourceFiles;
     SdkVersion  = sdkVersion;
 }
Пример #43
0
        public void ChangeSolution()
        {
            Microsoft.Build.Evaluation.Project pc = null;

            if (vs == null)
            {
                return;
            }

            foreach (VSProject p in vs.projects)
            {
                if (File.Exists(p.FileName) == false)
                {
                    continue;
                }

                pc = p.LoadProjectToMemory();

                p.Shuffle(pc);
            }

            MockProject();
        }
Пример #44
0
        public static void RemoveEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
        {
            var targetElement = buildProject.Xml.Targets.FirstOrDefault(
                target => string.Equals(target.Name, targetName, StringComparison.OrdinalIgnoreCase));
            if (targetElement == null)
            {
                return;
            }

            string errorCondition = "!Exists('" + targetsPath + "')";
            var taskElement = targetElement.Tasks.FirstOrDefault(
                task => string.Equals(task.Condition, errorCondition, StringComparison.OrdinalIgnoreCase));
            if (taskElement == null)
            {
                return;
            }

            taskElement.Parent.RemoveChild(taskElement);
            if (targetElement.Tasks.Count == 0)
            {
                targetElement.Parent.RemoveChild(targetElement);
            }
        }
Пример #45
0
        public void SetImportPath(string importPath, Project prj)
        {
            object               service   = null;
            IVsSolution          solution  = null;
            IVsHierarchy         hierarchy = null;
            ProjectImportElement importProject;
            int?result = 0;

            service  = GetServiceObject(prj.DTE, typeof(IVsSolution));
            solution = (IVsSolution)service;
            result   = solution?.GetProjectOfUniqueName(prj.UniqueName, out hierarchy);
            IVsProject project = (IVsProject)hierarchy;

            Microsoft.Build.Evaluation.Project msbuildProject = MSBuildProjectFromIVsProject(project);
            if (msbuildProject == null)
            {
                msbuildProject = ForceLoadMSBuildProjectFromIVsProject(project);
            }
            importProject       = msbuildProject.Xml.AddImport(importPath);
            importProject.Label = "Shared";
            msbuildProject.Save();
            UnloadMSbuildProject(msbuildProject);
        }
Пример #46
0
        /// <summary>
        /// Retrives the list of project guids from the project file.
        /// If you don't want your project to be flavorable, override
        /// to only return your project factory Guid:
        ///      return this.GetType().GUID.ToString("B");
        /// </summary>
        /// <param name="file">Project file to look into to find the Guid list</param>
        /// <returns>List of semi-colon separated GUIDs</returns>
        protected override string ProjectTypeGuids(string file)
        {
            // Load the project so we can extract the list of GUIDs

            this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject);

            // Retrieve the list of GUIDs, if it is not specify, make it our GUID
            string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids);
            if (String.IsNullOrEmpty(guids))
                guids = this.GetType().GUID.ToString("B");

            return guids;
        }
Пример #47
0
        /// <summary>
        /// Rather than directly creating the project, ask VS to initate the process of
        /// creating an aggregated project in case we are flavored. We will be called
        /// on the IVsAggregatableProjectFactory to do the real project creation.
        /// </summary>
        /// <param name="fileName">Project file</param>
        /// <param name="location">Path of the project</param>
        /// <param name="name">Project Name</param>
        /// <param name="flags">Creation flags</param>
        /// <param name="projectGuid">Guid of the project</param>
        /// <param name="project">Project that end up being created by this method</param>
        /// <param name="canceled">Was the project creation canceled</param>
        protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
        {
            project = IntPtr.Zero;
            canceled = 0;

            if ((flags & ((uint)__VSCREATEPROJFLAGS2.CPF_DEFERREDSAVE)) != 0)
            {
                throw new NotSupportedException(SR.GetString(SR.NoZeroImpactProjects));
            }

#if FX_ATLEAST_45
            if ((flags & ((uint)__VSCREATEPROJFLAGS.CPF_OPENFILE)) != 0)
            {
                if (new ProjectInspector(fileName).IsPoisoned(Site))
                {
                    // error out
                    int ehr = unchecked((int)0x80042003); // VS_E_INCOMPATIBLEPROJECT
                    ErrorHandler.ThrowOnFailure(ehr);
                }
            }
#endif

            // Get the list of GUIDs from the project/template
            string guidsList = this.ProjectTypeGuids(fileName);

            // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation)
            IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject));
            int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project);
            if (hr == VSConstants.E_ABORT)
                canceled = 1;
            ErrorHandler.ThrowOnFailure(hr);

            this.buildProject = null;
        }
Пример #48
0
        // This method is to restore the property value with old one when configuration goes wrong.
        // Unlike SetConfigurationProperty(), this method won't reevaluate the project prior to add the value, which may raise exceptions. 
        private void RestoreConfigurationProperty(string propertyName, string propertyValue)
        {
            string condition = this.configCanonicalName.ToMSBuildCondition();
            // Get properties for current configuration from project file and cache it
            MSBuildProject.SetGlobalProperty(this.project.BuildProject, ProjectFileConstants.Configuration, configCanonicalName.ConfigName);
            MSBuildProject.SetGlobalProperty(this.project.BuildProject, ProjectFileConstants.Platform, configCanonicalName.MSBuildPlatform);

            this.evaluatedProject = this.project.BuildProject;

            SetPropertyUnderConditionImpl(propertyName, propertyValue, condition);
            this.evaluatedProject = null;
            UpdateOutputGroup();                
        }
Пример #49
0
        /// <summary>
        /// Loads each MSBuild project in this solution and looks for its project-to-project references so that
        /// we know what build order we should use when building the solution. 
        /// </summary>
        private void ScanProjectDependencies(string childProjectToolsVersion, string fullSolutionConfigurationName)
        {
            // Don't bother with all this if the solution configuration doesn't even exist.
            if (fullSolutionConfigurationName == null)
            {
                return;
            }

            foreach (ProjectInSolution project in _solutionFile.ProjectsInOrder)
            {
                // We only need to scan .wdproj projects: Everything else is either MSBuildFormat or 
                // something we don't know how to do anything with anyway
                if (project.ProjectType == SolutionProjectType.WebDeploymentProject)
                {
                    // Skip the project if we don't have its configuration in this solution configuration
                    if (!project.ProjectConfigurations.ContainsKey(fullSolutionConfigurationName))
                    {
                        continue;
                    }

                    try
                    {
                        Project msbuildProject = new Project(project.AbsolutePath, _globalProperties, childProjectToolsVersion);

                        // ProjectDependency items work exactly like ProjectReference items from the point of 
                        // view of determining that project B depends on project A.  This item must cause
                        // project A to be built prior to project B.
                        //
                        // This has the format 
                        // <ProjectDependency Include="DependentProjectRelativePath">
                        //   <Project>{GUID}</Project>
                        // </Project>
                        IEnumerable<ProjectItem> references = msbuildProject.GetItems("ProjectDependency");

                        foreach (ProjectItem reference in references)
                        {
                            string referencedProjectGuid = reference.GetMetadataValue("Project");
                            AddDependencyByGuid(project, referencedProjectGuid);
                        }

                        // If this is a web deployment project, we have a reference specified as a property
                        // "SourceWebProject" rather than as a ProjectReference item.  This has the format
                        // {GUID}|PATH_TO_CSPROJ
                        // where
                        // GUID is the project guid for the "source" project
                        // PATH_TO_CSPROJ is the solution-relative path to the csproj file.
                        //
                        // NOTE: This is obsolete and is intended only for backward compatability with
                        // Whidbey-generated web deployment projects.  New projects should use the
                        // ProjectDependency item above.
                        string referencedWebProjectGuid = msbuildProject.GetPropertyValue("SourceWebProject");
                        if (!string.IsNullOrEmpty(referencedWebProjectGuid))
                        {
                            // Grab the guid with its curly braces...
                            referencedWebProjectGuid = referencedWebProjectGuid.Substring(0, 38);
                            AddDependencyByGuid(project, referencedWebProjectGuid);
                        }
                    }
                    catch (Exception e)
                    {
                        // We don't want any problems scanning the project file to result in aborting the build.
                        if (ExceptionHandling.IsCriticalException(e))
                        {
                            throw;
                        }

                        _loggingService.LogWarning
                            (
                            _projectBuildEventContext,
                            "SubCategoryForSolutionParsingErrors",
                            new BuildEventFileInfo(project.RelativePath),
                            "SolutionScanProjectDependenciesFailed",
                            project.RelativePath,
                            e.Message
                            );
                    }
                }
            }
        }
Пример #50
0
 private void EnsureCache()
 {
     // Get properties for current configuration from project file and cache it
     this.project.SetConfiguration(configCanonicalName);
     this.evaluatedProject = this.project.BuildProject;
     // REVIEW: The call below will set the Project configuration to the Solution configuration
     // for the purpose of evaluating properties - this is exactly what we don't want to do.
     // Can anyone think of a reason why we'd want to keep it?
     //project.SetCurrentConfiguration();
 }
Пример #51
0
        public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
        {
            if (!this.project.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            string condition = this.configCanonicalName.ToMSBuildCondition();
            SetPropertyUnderCondition(propertyName, propertyValue, condition);

            // property cache will need to be updated
            this.evaluatedProject = null;
            UpdateOutputGroup();                
        }
 private static void SetMsBuildProjectProperty(MsBuildProject buildProject, string name, string value)
 {
     if (!value.Equals(buildProject.GetPropertyValue(name), StringComparison.OrdinalIgnoreCase))
     {
         buildProject.SetProperty(name, value);
     }
 }
        public void TestAddPropertyGroupForSolutionConfigurationBuildProjectInSolutionNotSet()
        {
            string solutionFileContents =
                @"
                Microsoft Visual Studio Solution File, Format Version 9.00
                # Visual Studio 2005
                Project('{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}') = 'ClassLibrary1', 'ClassLibrary1\ClassLibrary1.csproj', '{6185CC21-BE89-448A-B3C0-D1C27112E595}'
                EndProject
                Global
                    GlobalSection(SolutionConfigurationPlatforms) = preSolution
                        Debug|Mixed Platforms = Debug|Mixed Platforms
                        Release|Any CPU = Release|Any CPU
                    EndGlobalSection
                     GlobalSection(ProjectConfigurationPlatforms) = postSolution
                        {6185CC21-BE89-448A-B3C0-D1C27112E595}.Debug|Mixed Platforms.ActiveCfg = CSConfig1|Any CPU
                    EndGlobalSection
                EndGlobal
                ";

            SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents);

            ProjectRootElement projectXml = ProjectRootElement.Create();

            foreach (SolutionConfigurationInSolution solutionConfiguration in solution.SolutionConfigurations)
            {
                SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration(projectXml, solution, solutionConfiguration);
            }

            Project msbuildProject = new Project(projectXml);

            // Both projects configurations should be present for solution configuration "Debug|Mixed Platforms"
            msbuildProject.SetGlobalProperty("Configuration", "Debug");
            msbuildProject.SetGlobalProperty("Platform", "Mixed Platforms");
            msbuildProject.ReevaluateIfNecessary();

            string solutionConfigurationContents = msbuildProject.GetPropertyValue("CurrentSolutionConfigurationContents");
            Assert.IsTrue(solutionConfigurationContents.Contains(@"BuildProjectInSolution=""" + bool.FalseString + @""""));
        }
 private void AddNuGetTargets(MsBuildProject buildProject)
 {
     string targetsPath = Path.Combine(@"$(SolutionDir)", NuGetTargetsFile);
     NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, targetsPath, ProjectImportLocation.Bottom);
 }
        private void AddSolutionDirProperty(MsBuildProject buildProject)
        {
            const string solutiondir = "SolutionDir";

            if (buildProject.Xml.Properties == null ||
                buildProject.Xml.Properties.All(p => p.Name != solutiondir))
            {
                string relativeSolutionPath = PathUtility.GetRelativePath(
                    buildProject.FullPath,
                    PathUtility.EnsureTrailingSlash(_solutionManager.SolutionDirectory));
                relativeSolutionPath = PathUtility.EnsureTrailingSlash(relativeSolutionPath);

                var solutionDirProperty = buildProject.Xml.AddProperty(solutiondir, relativeSolutionPath);
                solutionDirProperty.Condition =
                    String.Format(
                        CultureInfo.InvariantCulture,
                        @"$({0}) == '' Or $({0}) == '*Undefined*'",
                        solutiondir);
            }
        }
 private void EnablePackageRestore(Project project, MsBuildProject buildProject, bool saveProjectWhenDone)
 {
     AddSolutionDirProperty(buildProject);
     AddNuGetTargets(buildProject);
     SetMsBuildProjectProperty(buildProject, "RestorePackages", "true");
     if (saveProjectWhenDone)
     {
         project.Save();
     }
 }
Пример #57
0
        /// <summary>
        /// Saves a .props file for the specified package, containing the paradox version (only Major.Minor)
        /// used to compile the package. 
        /// </summary>
        /// <param name="package">The package.</param>
        public static void SaveProperties(Package package)
        {
            // Props file is in the same folder as the pdxpkg file, just with a ".props" extension.
            var packagePath = package.FullPath;
            var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props")) ;

            var projectCollection = new Microsoft.Build.Evaluation.ProjectCollection();
            var project = new Microsoft.Build.Evaluation.Project(projectCollection);
            var commonPropertyGroup = project.Xml.AddPropertyGroup();

            var dependencies = package.FindDependencies(false, false, true);

            // Add Paradox version
            var pdxVersion = dependencies.FirstOrDefault(d => d.Meta.Name == "Paradox");
            if (pdxVersion != null)
            {
                var versionText = pdxVersion.Meta.Version.Version.Major + "." + pdxVersion.Meta.Version.Version.Minor;
                commonPropertyGroup.AddProperty("SiliconStudioPackageParadoxVersion", versionText);
            }

            if (File.Exists(propsFilePath))
            {
                File.Delete(propsFilePath);
            }
            project.Save(propsFilePath);
        }
Пример #58
0
 public BasicTests()
 {
     this.nuproj = Assets.FromTemplate()
                         .AssignNuProjDirectory()
                         .ToProject();
 }
Пример #59
0
        private static void AddStepDefinitonToIntelliSenseProject(List<NodeFeature> features, string pathToFeatureFile, string pathToIntelliSenseProject)
        {
            foreach (var feature in features)
            {
                List<StepInstance> si = new List<StepInstance>();
                var steps = new List<NodeStep>();
                feature.Scenarios.ForEach(s => steps.AddRange(s.Steps));
                var uniqueSteps = GeneratorHelper.FindUniqueSteps(new List<NodeStep>(), steps);

                foreach (var step in uniqueSteps)
                {
                    StepDefinitionType type;
                    StepDefinitionKeyword keyword;
                    string stepNameWithoutType;

                    if (step.Name.StartsWith("Given"))
                    {
                        type = StepDefinitionType.Given;
                        keyword = StepDefinitionKeyword.Given;
                        stepNameWithoutType = step.Name.Substring("Given".Length);
                    }
                    else if (step.Name.StartsWith("When"))
                    {
                        type = StepDefinitionType.When;
                        keyword = StepDefinitionKeyword.When;
                        stepNameWithoutType = step.Name.Substring("When".Length);
                    }
                    else
                    {
                        type = StepDefinitionType.Then;
                        keyword = StepDefinitionKeyword.Then;
                        stepNameWithoutType = step.Name.Substring("Then".Length);
                    }
                    string scenarioName = feature.Scenarios.First(scenario => scenario.Steps.Contains(step)).Name;
                    si.Add(new StepInstance(type, keyword, stepNameWithoutType, stepNameWithoutType, new StepContext(feature.Name, scenarioName, new List<string>(), CultureInfo.CurrentCulture)));
                }

                var stepDefSkeleton = new StepDefinitionSkeletonProvider(new SpecFlowCSkeletonTemplateProvider(), new StepTextAnalyzer());
                var template = stepDefSkeleton.GetBindingClassSkeleton(TechTalk.SpecFlow.ProgrammingLanguage.CSharp, si.ToArray(), "CppUnitTest", feature.Name, StepDefinitionSkeletonStyle.MethodNamePascalCase, CultureInfo.CurrentCulture);

                string basePathToFeatures = Path.GetDirectoryName(pathToFeatureFile);
                string basePathToIntelliSenseProject = Path.GetDirectoryName(pathToIntelliSenseProject);
                _csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);

                var stepDefinitionDirPathInProj = string.Format("Steps\\{0}\\", PROJECT_NAME);
                var stepDefinitionDirPath = string.Format("{0}\\{1}", basePathToIntelliSenseProject, stepDefinitionDirPathInProj);

                var filePathInProjFile = string.Format("{0}{1}_step.cs", stepDefinitionDirPathInProj, feature.Name);
                var filePath = string.Format("{0}{1}_step.cs", stepDefinitionDirPath, feature.Name);

                if (!_csProj.GetItems("Compile").Any(item => item.UnevaluatedInclude == filePathInProjFile))
                {
                    Console.WriteLine(string.Format("Generating Step Definition file for IntelliSense support: {0}", filePathInProjFile));
                    Directory.CreateDirectory(stepDefinitionDirPath);
                    File.WriteAllText(filePath, template);
                    _csProj.AddItem("Compile", filePathInProjFile);
                    _isDirtyCsProj = true;
                }
            }
        }
Пример #60
0
 private static Microsoft.Build.Evaluation.Project GetUnloadedProject(string projectPath)
 {
     var project = new Microsoft.Build.Evaluation.Project(projectPath);
     project.ProjectCollection.UnloadAllProjects();
     return project;
 }