コード例 #1
1
ファイル: Project.cs プロジェクト: rpepato/StructEx
        public Project(Solution solution, string title, string fileName)
        {
            AssembliesResolved = false;
            ReferencedAssemblies = new List<string>();
            CompilerSettings = new CompilerSettings();
            ReferencedProjects = new List<string>();
            Files = new List<File>();
            Solution = solution;
            Title = title;
            FileName = Path.GetFullPath(fileName);

            ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
            MsBuildProject = new Microsoft.Build.Evaluation.Project(fileName);

            AssemblyName = MsBuildProject.GetPropertyValue("AssemblyName");
            CompilerSettings.AllowUnsafeBlocks = MsBuildProject.GetPropertyAsBoolean("AllowUnsafeBlocks");
            CompilerSettings.CheckForOverflow = MsBuildProject.GetPropertyAsBoolean("CheckForOverflowUnderflow");
            var defineConstants = MsBuildProject.GetPropertyValue("DefineConstants");

            foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
            }

            foreach (var sourceCodeFile in MsBuildProject.GetItems("Compile"))
            {
                Files.Add(new File(this, Path.Combine(MsBuildProject.DirectoryPath, sourceCodeFile.EvaluatedInclude)));
            }

            foreach (var projectReference in MsBuildProject.GetItems("ProjectReference"))
            {
                string referencedFileName = Path.GetFullPath(Path.Combine(MsBuildProject.DirectoryPath, projectReference.EvaluatedInclude));
                ReferencedProjects.Add(referencedFileName);
            }
        }
        private static void AddEnsureImportedTarget(MicrosoftBuildEvaluationProject msBuildProject, string targetsPath)
        {
            // get the target
            var targetElement = msBuildProject.Xml.Targets.FirstOrDefault(
                target => target.Name.Equals(targetName, StringComparison.OrdinalIgnoreCase));

            // if the target does not exist, create the target
            if (targetElement == null)
            {
                targetElement = msBuildProject.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
ファイル: ProjectTest.cs プロジェクト: nlhepler/mono
		public void EscapeDoesWTF ()
		{
			string value_xml = "What are 'ESCAPE' &amp; \"EVALUATE\" ? $ # % ^";
			string value = "What are 'ESCAPE' & \"EVALUATE\" ? $ # % ^";
			string escaped = "What are %27ESCAPE%27 & \"EVALUATE\" %3f %24 # %25 ^";
			string xml = string.Format (@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
	<PropertyGroup>
		<Foo>{0}</Foo>
		<Baz>$(FOO)</Baz>
	</PropertyGroup>
</Project>", value_xml);
			var path = "file://localhost/foo.xml";
			var reader = XmlReader.Create (new StringReader (xml), null, path);
			var root = ProjectRootElement.Create (reader);
			var proj = new Project (root);
			var prop = proj.Properties.First (p => p.Name == "Foo");
			Assert.AreEqual (value, prop.UnevaluatedValue, "#1");
			Assert.AreEqual (value, prop.EvaluatedValue, "#2");
			// eh?
			Assert.AreEqual (value, Project.GetPropertyValueEscaped (prop), "#3");
			prop = proj.Properties.First (p => p.Name == "Baz");
			Assert.AreEqual ("$(FOO)", prop.UnevaluatedValue, "#4");
			Assert.AreEqual (value, prop.EvaluatedValue, "#5");
			// eh?
			Assert.AreEqual (value, Project.GetPropertyValueEscaped (prop), "#6");
			
			// OK you are fine.
			Assert.AreEqual (escaped, ProjectCollection.Escape (value), "#7");
		}
コード例 #4
0
        public void Analyze(Project project)
        {
            if (project == null) { throw new ArgumentNullException("project"); }

            this.Project = project;
            this.TargetGraph = this.BuildTargetGraph(project);
        }
コード例 #5
0
ファイル: ProjectFactory.cs プロジェクト: atheken/nuget
 public ProjectFactory(Project project)
 {
     _project = project;
     ProjectProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
     AddSolutionDir();
     _settings = null;            
 }
コード例 #6
0
		public ProjectProcessor(string path)
		{
			using (ProjectCollection pc = new ProjectCollection())
			{
				this.Project = pc.GetLoadedProjects(path).FirstOrDefault();
			}
		}
コード例 #7
0
        public static Microsoft.Build.Evaluation.Project LoadedProject(String path, bool cached)
        {
            Microsoft.Build.Evaluation.Project project = null;
            ICollection<Microsoft.Build.Evaluation.Project> projects = 
                ProjectCollection.GlobalProjectCollection.GetLoadedProjects(path);


            if (projects.Count == 0)
            {
                project = new Microsoft.Build.Evaluation.Project(path);
            }
            else
            {
                project = projects.First();
                if(!cached)
                {
                    //
                    // That is required to get C++ project properties re-evaluated
                    // with Visual Studio 2013 and Visual Studio 2015
                    //
                    ProjectCollection.GlobalProjectCollection.UnloadProject(project);
                    ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
                    project = ProjectCollection.GlobalProjectCollection.LoadProject(path);
                }
            }
            return project;
        }
コード例 #8
0
		public ProjectProcessor(Project project, string config, string platform)
			: this(project)
		{
			this.Project.SetProperty("Configuration", config);
			this.Project.SetProperty("Platform", platform);
			this.Project.ReevaluateIfNecessary();
		}
コード例 #9
0
        public static IList<string> GetDependsOnTargetsAsList(this ProjectTargetInstance target,Project project)
        {
            if (target == null) { throw new ArgumentNullException("target"); }
            if (project == null) { throw new ArgumentNullException("project"); }

            List<string> targets = new List<string>();
            string depTargets = target.DependsOnTargets != null ? target.DependsOnTargets : string.Empty;
            string depTargetsEvaluated = project.ExpandString(depTargets);

            string[] dtArray = depTargetsEvaluated.Split(';');
            dtArray.ToList().ForEach(t => {
                if (!string.IsNullOrWhiteSpace(t)) {
                    string tName = t.Trim();
                    if (!string.IsNullOrWhiteSpace(tName) &&
                        string.Compare(";", tName, StringComparison.InvariantCultureIgnoreCase) != 0) {
                        targets.Add(tName);
                    }
                }
            });

            int numTarges = targets != null ? targets.Count() : 0;
            string tempDebug = null;
            if (numTarges >= 1) {
                tempDebug = targets[0];
            }

            return targets;
        }
コード例 #10
0
        private Compilation CreateCompilation(Project project)
        {
            var outputPath = project.GetProperty("OutputPath").EvaluatedValue;

            if (!Path.IsPathRooted(outputPath))
            {
                outputPath = Path.Combine(Environment.CurrentDirectory, outputPath);
            }

            var searchPaths = ReadOnlyArray.OneOrZero(outputPath);
            var resolver = new DiskFileResolver(searchPaths, searchPaths, Environment.CurrentDirectory, arch => true, System.Globalization.CultureInfo.CurrentCulture);

            var metadataFileProvider = new MetadataFileProvider();

            // just grab a list of references (if they're null, ignore)
            var list = project.GetItems("Reference").Select(item =>
            {
                var include = item.EvaluatedInclude;
                var path = resolver.ResolveAssemblyName(include);
                if (path == null) return null;
                return metadataFileProvider.GetReference(path);
            }).Where(x => x != null);

            return Compilation.Create(project.GetPropertyValue("AssemblyName"),
                syntaxTrees: project.GetItems("Compile").Select(c => SyntaxTree.ParseFile(c.EvaluatedInclude)),
                references: list);
        }
コード例 #11
0
		public void Properties ()
		{
			string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <ItemDefinitionGroup>
    <Foo>
    	<prop1>value1</prop1>
    	<prop2>value1</prop2>
    </Foo>
    <!-- This one is merged into existing Foo definition above. -->
    <Foo>
    	<prop1>valueX1</prop1><!-- this one overrides value1. -->
    	<prop3>value3</prop3>
    </Foo>
  </ItemDefinitionGroup>
</Project>";
			var xml = XmlReader.Create (new StringReader (project_xml));
			var root = ProjectRootElement.Create (xml);
			var proj = new Project (root);
			Assert.AreEqual (1, proj.ItemDefinitions.Count, "#1"); // Foo
			var def = proj.ItemDefinitions ["Foo"];
			Assert.AreEqual ("Foo", def.ItemType, "#1x");
			Assert.AreEqual (3, def.MetadataCount, "#2");
			var md1 = def.Metadata.First (m => m.Name == "prop1");
			Assert.AreEqual ("Foo", md1.ItemType, "#2x");
			Assert.AreEqual ("valueX1", md1.UnevaluatedValue, "#3");
			// FIXME: enable it once we implemented it.
			//Assert.AreEqual ("valueX1", md1.EvaluatedValue, "#4");
			Assert.IsNotNull (md1.Predecessor, "#5");
			Assert.AreEqual ("value1", md1.Predecessor.UnevaluatedValue, "#6");
			// FIXME: enable it once we implemented it.
			//Assert.AreEqual ("value1", md1.Predecessor.EvaluatedValue, "#7");
		}
コード例 #12
0
ファイル: ResolvedImportTest.cs プロジェクト: nlhepler/mono
		public void SimpleImportAndSemanticValues ()
		{
			string xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <Import Project='test_imported.proj' />
</Project>";
			string imported = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <PropertyGroup>
    <A>x</A>
    <B>y</B>
  </PropertyGroup>
  <ItemGroup>
    <X Include=""included.txt"" />
  </ItemGroup>
</Project>";
			using (var ts = File.CreateText (temp_file_name))
				ts.Write (imported);
			try {
				var reader = XmlReader.Create (new StringReader (xml));
				var root = ProjectRootElement.Create (reader);
				Assert.AreEqual (temp_file_name, root.Imports.First ().Project, "#1");
				var proj = new Project (root);
				var prop = proj.GetProperty ("A");
				Assert.IsNotNull (prop, "#2");
				Assert.IsTrue (prop.IsImported, "#3");
				var item = proj.GetItems ("X").FirstOrDefault ();
				Assert.IsNotNull (item, "#4");
				Assert.AreEqual ("included.txt", item.EvaluatedInclude, "#5");
			} finally {
				File.Delete (temp_file_name);
			}
		}
コード例 #13
0
ファイル: GlobalProjectProperties.cs プロジェクト: kzu/clide
		public GlobalProjectProperties(ProjectNode project)
		{
			msBuildProject = project.As<Project>();
			dteProject = project.As<EnvDTE.Project>();
			vsBuild = project.HierarchyNode.HierarchyIdentity.Hierarchy as IVsBuildPropertyStorage;
			accessor = new DynamicPropertyAccessor(this);
		}
コード例 #14
0
ファイル: ProjectPropertyTest.cs プロジェクト: nlhepler/mono
		public void SetUnevaluatedValueOverwritesElementValue ()
		{
			string project_xml = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <PropertyGroup>
    <Foo>Bar</Foo>
    <Item/>
    <X>1</X>
    <X>2</X>
    <PATH>overriden</PATH>
  </PropertyGroup>
</Project>";
			var xml = XmlReader.Create (new StringReader (project_xml));
			var root = ProjectRootElement.Create (xml);
			var pe = root.Properties.First ();
			Assert.AreEqual ("Bar", pe.Value, "#1");
			var proj = new Project (root);
			var prop = proj.Properties.First (p => p.Name == "Foo");
			Assert.AreEqual ("Bar", prop.UnevaluatedValue, "#2");
			prop.UnevaluatedValue = "x";
			Assert.AreEqual ("x", pe.Value, "#3");
			
			prop = proj.Properties.First (p => p.Name == "X");
			Assert.AreEqual ("2", prop.UnevaluatedValue, "#4");
			Assert.IsNotNull (prop.Predecessor, "#5");
			Assert.AreEqual ("1", prop.Predecessor.UnevaluatedValue, "#6");
			
			// environment property could also be Predecessor (and removed...maybe.
			// I could reproduce only NRE = .NET bug with environment property so far.)
			prop = proj.Properties.First (p => p.Name == "PATH");
			Assert.AreEqual ("overriden", prop.UnevaluatedValue, "#7");
			Assert.IsNotNull (prop.Predecessor, "#8");
		}
コード例 #15
0
ファイル: Project_Tests.cs プロジェクト: cameron314/msbuild
        public void VerifyNewLinesAndTabsEvaluateToEmpty()
        {
            MockLogger mockLogger = new MockLogger();

            string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
                    <Project xmlns='msbuildnamespace'>
                       <PropertyGroup><NewLine>" + Environment.NewLine + Environment.NewLine + "</NewLine></PropertyGroup>" +
                       "<PropertyGroup><Tab>\t\t\t\t</Tab></PropertyGroup>" +
                       "<PropertyGroup><CarriageReturn>\r\r\r\r</CarriageReturn></PropertyGroup>" +
                        @"<PropertyGroup><Message1 Condition =""'$(NewLine)' == ''"">NewLineEvalAsEmpty</Message1></PropertyGroup>
                        <PropertyGroup><Message2 Condition =""'$(Tab)' == ''"">TabEvalAsEmpty</Message2></PropertyGroup>
                        <PropertyGroup><Message3 Condition =""'$(CarriageReturn)' == ''"">CarriageReturnEvalAsEmpty</Message3></PropertyGroup>

                        <Target Name=""BUild"">
                           <Message Text=""$(Message1)"" Importance=""High""/>
                          <Message Text=""$(Message2)"" Importance=""High""/>
                          <Message Text=""$(Message3)"" Importance=""High""/>
                       </Target>                    
                    </Project>");

            ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));
            Project project = new Project(xml);
            bool result = project.Build(new ILogger[] { mockLogger });
            Assert.Equal(true, result);
            mockLogger.AssertLogContains("NewLineEvalAsEmpty");
            mockLogger.AssertLogContains("TabEvalAsEmpty");
            mockLogger.AssertLogContains("CarriageReturnEvalAsEmpty");
        }
 protected override IEnumerable<ProjectReference> ResolveProjectReferences(Project project)
 {
     return
         base.ResolveProjectReferences(project)
             //Don't include project reference to pMixins
             .Where(p => !p.ToString().EndsWith(projectMatchingString));
 }
コード例 #17
0
		public void Hello ()
		{
			string project_xml = @"<Project ToolsVersion='4.0' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <UsingTask
    TaskName='DoNothing'
    TaskFactory='CodeTaskFactory'
    AssemblyFile='$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll' >
    <ParameterGroup />
    <Task>
      <Code Type='Fragment' Language='cs'>
<![CDATA[
// Display ""Hello, world!""
Log.LogWarning(""Hello, world!"");
]]>      </Code>
    </Task>
  </UsingTask>
  <Target Name='default'>
    <DoNothing />
  </Target>
</Project>";
			var root = ProjectRootElement.Create (XmlReader.Create (new StringReader (project_xml))); 
			root.FullPath = "CodeTaskFactoryTest.Hello.proj";
  			var project = new Project (root);
			Assert.IsTrue (project.Build (new ConsoleLogger (LoggerVerbosity.Diagnostic)), "Build");
		}
コード例 #18
0
        public override bool Execute()
        {
            try
            {
                _BE.Project input = new _BE.Project(m_inputFile);

                bool fFound = false;

                foreach (ProjectPropertyGroupElement bpg in input.Xml.PropertyGroups)
                {
                    foreach (ProjectPropertyElement bp in bpg.Properties)
                    {
                        if (string.Compare(bp.Name, "BuildNumber", true) == 0)
                        {
                            bpg.SetProperty(bp.Name, m_buildNumber);
                            fFound = true;
                            break;
                        }
                    }
                    if (fFound) break;
                }

                input.Save(m_outputFile, Encoding.ASCII);
            }
            catch (Exception e)
            {
                Log.LogError("Error trying to create release info file {0} at {1}: ({2})", m_inputFile, m_outputFile, e.Message);
                return false;
            }
            return true;
        }
コード例 #19
0
ファイル: ProjectItem_Tests.cs プロジェクト: nikson/msbuild
        public void ProjectGetter()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];

            Assert.Equal(true, Object.ReferenceEquals(project, item.Project));
        }
コード例 #20
0
        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();
            }
        }
コード例 #21
0
        public void ProjectGetter()
        {
            Project project = new Project();
            ProjectProperty property = project.SetProperty("p", "v");

            Assert.Equal(true, Object.ReferenceEquals(project, property.Project));
        }
コード例 #22
0
ファイル: MsBuildRunner.cs プロジェクト: kontur-edu/uLearn
		public static MSbuildResult BuildProject(MsBuildSettings settings, string projectFileName, DirectoryInfo dir)
		{
			var result = new MSbuildResult();
			var path = Path.Combine(dir.FullName, projectFileName);
			var project = new Project(path, null, null, new ProjectCollection());
			project.SetProperty("CscToolPath", settings.CompilerDirectory.FullName);
			var includes = new HashSet<string>(
				project.AllEvaluatedItems
				.Where(i => i.ItemType == "None" || i.ItemType == "Content")
				.Select(i => Path.GetFileName(i.EvaluatedInclude.ToLowerInvariant())));
			foreach (var dll in settings.WellKnownLibsDirectory.GetFiles("*.dll"))
				if (!includes.Contains(dll.Name.ToLowerInvariant()))
					project.AddItem("None", dll.FullName);
			project.Save();
			using (var stringWriter = new StringWriter())
			{
				var logger = new ConsoleLogger(LoggerVerbosity.Minimal, stringWriter.Write, color => { }, () => { });
				result.Success = SyncBuild(project, logger);
				if (result.Success)
					result.PathToExe = Path.Combine(project.DirectoryPath,
													project.GetPropertyValue("OutputPath"),
													project.GetPropertyValue("AssemblyName") + ".exe");
				else
					result.ErrorMessage = stringWriter.ToString();
				return result;
			}
		}
コード例 #23
0
ファイル: ProjectBuilder.cs プロジェクト: dbug13/dotproject
        public static Project AddConfigurations(Project proj, string defaultConfig)
        {
            try {
                var prop = proj.SetProperty("Configuration", defaultConfig);
                prop.Xml.Condition = " '$(Configuration)' == '' ";

                var debugPropGroup = proj.Xml.AddPropertyGroup();
                var releasePropGroup = proj.Xml.AddPropertyGroup();

                debugPropGroup.Condition = " '$(Configuration)' == 'Release' ";
                debugPropGroup.SetProperty("OutputPath", "bin\\Release");
                debugPropGroup.SetProperty("DebugSymbols", "Fasle");
                debugPropGroup.SetProperty("DebugType", "None");
                debugPropGroup.SetProperty("Optomize", "True");
                debugPropGroup.SetProperty("CheckForOverflowUnderflow", "False");
                debugPropGroup.SetProperty("DefineConstants", "TRACE");

                releasePropGroup.Condition = " '$(Configuration)' == 'Debug' ";
                releasePropGroup.SetProperty("OutputPath", "bin\\Debug");
                releasePropGroup.SetProperty("DebugSymbols", "True");
                releasePropGroup.SetProperty("DebugType", "Full");
                releasePropGroup.SetProperty("Optomize", "False");
                releasePropGroup.SetProperty("CheckForOverflowUnderflow", "True");
                releasePropGroup.SetProperty("DefineConstants", "DEBUG;TRACE");

                return proj;
            } catch {
                throw;
            }
        }
コード例 #24
0
        internal static void generate(string filename, string version, string asmName, string ns, ProjectType type)
        {
            Project p = new Project();
            string typeDesc = null;

            p.Xml.DefaultTargets = "Build";
            createItemGroup(p, "ProjectConfigurations");
            createGlobals(ns, type, p, "Globals");
            p.Xml.AddImport(@"$(VCTargetsPath)\Microsoft.Cpp.Default.props");

            switch (type) {
                case ProjectType.ConsoleApp: typeDesc = "Application"; break;
                case ProjectType.XamlApp: typeDesc = "Application"; break;
                case ProjectType.ClassLibrary: typeDesc = "DynamicLibrary"; break;
                default:
                    throw new InvalidOperationException("unhandled projectType: " + type);
            }
            createCfgProp(p.Xml, typeDesc, true);
            createCfgProp(p.Xml, typeDesc, false);
            p.Xml.AddImport(@"$(VCTargetsPath)\Microsoft.Cpp.props");
            addPropertySheetImports(p.Xml);
            addPropertyGroup(p.Xml, makeCfgCondition(DEBUG, PLATFORM), new Blah2(b2));
            addPropertyGroup(p.Xml, makeCfgCondition(RELEASE, PLATFORM), new Blah2(b2));
            addItemDefs(p.Xml);

            const string C_TARGET_RULES = @"$(VCTargetsPath)\Microsoft.Cpp.targets";
            var v99 = p.Xml.CreateImportElement(C_TARGET_RULES);
            p.Xml.AppendChild(v99);
            p.Save(filename);
        }
コード例 #25
0
        public void CreateProjectInstancePassesEnvironment()
        {
            Project p = new Project();
            ProjectInstance i = p.CreateProjectInstance();

            Assert.Equal(true, i.GetPropertyValue("username") != null);
        }
コード例 #26
0
        public void TaskFinished(object sender, BuildEventArgs e)
        {
            var task = (CscTask)e.Task;
            var generator = (GenerateMsBuildTask)sender;
            var projectFileName = String.Format(
                    "{0}{1}{2}.csproj",
                    task.Sources.BaseDirectory.FullName,
                    Path.DirectorySeparatorChar,
                    Path.GetFileNameWithoutExtension(task.OutputFile.Name));

            ProjectRootElement project = null;
            if (!File.Exists(projectFileName))
                project = ProjectRootElement.Create(projectFileName);
            else
                project = ProjectRootElement.Open(projectFileName);
            var projectManipulator = new MB.Project(project);

            project.DefaultTargets = "Build";
            SetKnownProperties(project, task);
            GenerateReferences(project, projectManipulator, task, generator);
            GenerateCompileIncludes(project, projectManipulator, task);
            project.EnsureImportExists("$(MSBuildToolsPath)\\Microsoft.CSharp.targets");

            generator.RegisterProjectInSolution(project);
            project.Save();
        }
コード例 #27
0
ファイル: XamlGenerator.cs プロジェクト: surak8/ProjectGen
        internal static void generateFiles(Project p, PGOptions opts1, ProjectItemGroupElement pige)
        {
            Dictionary<string, string> tmp = new Dictionary<string, string>();
            WinDataProvider wdp = new WinDataProvider(WIN_NAME, opts1.projectNamespace, opts1.xamlType == XamlWindowType.RegularWindow);
            AppDataProvider apd = new AppDataProvider(wdp.fileName, opts1.projectNamespace);
            HomeDataProvider hdp = null;
            string tmp2;

            XamlFileGenerator.generateFile(apd, opts1);
            XamlFileGenerator.generateFile(wdp, opts1);

            if (opts1.xamlType == XamlWindowType.NavigationWindow) {
                hdp = new HomeDataProvider(wdp.homePage, opts1.projectNamespace);
                XamlFileGenerator.generateFile(hdp, opts1);
                generatePageAndModel(pige, hdp);
            }

            if (!string.IsNullOrEmpty(tmp2 = wdp.viewModelName) && File.Exists(tmp2)) {
                generateCompile(pige, tmp2);
            }

            generateApp(pige, apd);
            generatePage(pige, wdp);

            if (opts1.xamlPages.Count > 0) {
                GeneralPage gp;
                foreach (string aPageName in opts1.xamlPages) {
                    gp = new GeneralPage(aPageName, opts1.projectNamespace);
                    XamlFileGenerator.generateFile(gp, opts1);
                    generatePageAndModel(pige, gp);
                }
            }
        }
コード例 #28
0
        void CreateBuildProject()
        {
            string projectPath = Path.Combine(buildDirectory, "content.contentproj");
            string outputPath = Path.Combine(buildDirectory, "bin");

            // Create the build project.
            projectRootElement = ProjectRootElement.Create(projectPath);

            // Include the standard targets file that defines how to build XNA Framework content.
            projectRootElement.AddImport(Application.StartupPath + "\\Exporters\\FBX\\XNA\\XNA Game Studio\\" +
                                         "v4.0\\Microsoft.Xna.GameStudio.ContentPipeline.targets");

            buildProject = new Project(projectRootElement);

            buildProject.SetProperty("XnaPlatform", "Windows");
            buildProject.SetProperty("XnaProfile", "Reach");
            buildProject.SetProperty("XnaFrameworkVersion", "v4.0");
            buildProject.SetProperty("Configuration", "Release");
            buildProject.SetProperty("OutputPath", outputPath);
            buildProject.SetProperty("ContentRootDirectory", ".");
            buildProject.SetProperty("ReferencePath", Application.StartupPath);

            // Register any custom importers or processors.
            foreach (string pipelineAssembly in pipelineAssemblies)
            {
                buildProject.AddItem("Reference", pipelineAssembly);
            }

            // Hook up our custom error logger.
            errorLogger = new ErrorLogger();

            buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection)
                                  {Loggers = new ILogger[] {errorLogger}};
        }
コード例 #29
0
 private IEnumerable<Project> SortProject(Project project)
 {
     if (!visited.Contains(project)) {
         visited.Add(project);
         foreach (var reference in project.GetItems("Reference")) {
             //TODO: Get rid of hard-coded exclusions
             if (reference.EvaluatedInclude != "DevExpress.XtraRichEdit.v12.2.Extensions, Version=12.2.0.0, Culture=neutral, PublicKeyToken=79868b8147b5eae4, processorArchitecture=MSIL") {
                 AssemblyName assemblyName = new AssemblyName(reference.EvaluatedInclude);
                 string shortName = assemblyName.Name;
                 Project referencedProject;
                 if (projects.TryGetValue(shortName, out referencedProject)) {
                     foreach (var sorted in SortProject(referencedProject))
                         yield return sorted;
                 }
                 else if (excludedProjects.Contains(shortName)) {
                     excludedProjects.Add(shortName);
                     yield break;
                 }
                 else if (shortName.StartsWith("DevExpress", StringComparison.OrdinalIgnoreCase))
                     unknownReferences.Add(shortName);
             }
         }
         yield return project;
     }
 }
コード例 #30
0
        public void ProjectGetter()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            ProjectMetadata metadatum = item.SetMetadataValue("m", "m1");

            Assert.AreEqual(true, Object.ReferenceEquals(project, metadatum.Project));
        }
コード例 #31
0
        /// <summary>
        /// Stores the value in current project.
        /// </summary>
        /// <param name="selectedFeaturesIds">The selected features ids.</param>
        /// <param name="sharePointProject">The share point project.</param>
        /// <param name="projectPropertyName">Name of the project property.</param>
        public static void StoreValueInCurrentProject(List <string> selectedFeaturesIds,
                                                      ISharePointProject sharePointProject,
                                                      string projectPropertyName)
        {
            string value = String.Empty;

            if (selectedFeaturesIds != null && selectedFeaturesIds.Count > 0)
            {
                value = String.Join(";", selectedFeaturesIds.ToArray());
            }

            Microsoft.Build.Evaluation.Project project = GetCurrentProject(sharePointProject.FullPath);
            if (project != null)
            {
                project.SetProperty(projectPropertyName, value as string);
            }
        }
コード例 #32
0
        public void UpdateProject(PythonProjectNode node, MSBuild.Project project)
        {
            lock (_projects) {
                if (project == null)
                {
                    _projects.Remove(node);
                }
                else if (!_projects.ContainsKey(node) || _projects[node] != project)
                {
                    _projects[node] = project;
                }
            }

            // Always raise the event, this also occurs when we're adding projects
            // to the MSBuild.Project.
            ProjectsChanged?.Invoke(this, EventArgs.Empty);
        }
コード例 #33
0
 public IEnumerable <PropertyEvaluation> EvaluateProjectProperties(FilePath ProjectFile)
 {
     try
     {
         var project     = new MSEV.Project(ProjectFile);
         var evaluations = list(from p in project.AllEvaluatedProperties
                                orderby p.Name
                                let pe = new PropertyEvaluation(p.Name, p.UnevaluatedValue, p.EvaluatedValue, p.IsEnvironmentProperty)
                                         select pe);
         return(evaluations.Stream());
     }
     catch (Exception e)
     {
         Notify(error($"Error occurred during property evaluation of {ProjectFile}: {e}"));
         return(stream <PropertyEvaluation>());
     }
 }
コード例 #34
0
        /// <summary>
        /// Gets the project with the specified source project file from the global project collection if it exists. If it doesn't, a new project object is constructed.
        /// <para>If the project exists in the global project collection, it is updated to incorporate any changes.</para>
        /// </summary>
        /// <param name="projectFilePath">The source project file.</param>
        public static Microsoft.Build.Evaluation.Project GetProject(string projectFilePath)
        {
            string projectFilePathLower = projectFilePath.ToLowerInvariant();
            var    loadedProjects       = ProjectCollection.GlobalProjectCollection.LoadedProjects;
            var    project = loadedProjects.FirstOrDefault(p => p.FullPath.ToLowerInvariant() == projectFilePathLower);

            if (project != null)
            {
                // update the instance of the project
                project.ReevaluateIfNecessary();
            }
            else
            {
                project = new Microsoft.Build.Evaluation.Project(projectFilePath);
            }
            return(project);
        }
コード例 #35
0
        private static bool RemoveImport(Microsoft.Build.Evaluation.Project project, String import)
        {
            ProjectElement element = project.Xml.Imports.FirstOrDefault(p => p.Project.Equals(import));

            if (element != null)
            {
                if (element.Parent != null)
                {
                    element.Parent.RemoveChild(element);
                }
                else
                {
                    project.Xml.RemoveChild(element);
                }
            }
            return(element != null);
        }
コード例 #36
0
        /// <summary>
        /// Gets the value from current project.
        /// </summary>
        /// <param name="sharePointProject">The share point project.</param>
        /// <param name="projectPropertyName">Name of the project property.</param>
        /// <returns></returns>
        public static List <string> GetValueFromCurrentProject(ISharePointProject sharePointProject,
                                                               string projectPropertyName)
        {
            List <string> value = null;

            Microsoft.Build.Evaluation.Project project = GetCurrentProject(sharePointProject.FullPath);
            if (project != null)
            {
                string rawValue = project.GetPropertyValue(projectPropertyName);
                if (!String.IsNullOrEmpty(rawValue))
                {
                    value = rawValue.Split(';').ToList();
                }
            }

            return(value);
        }
コード例 #37
0
ファイル: Extensions.cs プロジェクト: nayanshah/MSBuildTracer
        /// <summary>
        /// Fully resolves all properties in a given string.
        /// </summary>
        /// <param name="project"></param>
        /// <param name="input">The string to resolve</param>
        /// <returns></returns>
        public static string ResolveAllProperties(this MBEV.Project project, string input)
        {
            var   resolvedString = input;
            var   propertyRegex  = new Regex(@"\$\(([\w\d_]+)\)", RegexOptions.Singleline);
            Match match;

            while ((match = propertyRegex.Match(resolvedString)).Success)
            {
                while (match.Success)
                {
                    resolvedString = resolvedString.Replace($"$({match.Groups[1].Value})", project.GetPropertyValue(match.Groups[1].Value));
                    match          = match.NextMatch();
                }
            }

            return(resolvedString);
        }
コード例 #38
0
        public static String GetEvaluatedMetadata(Microsoft.Build.Evaluation.Project project, String type, String name)
        {
            ProjectItemDefinition item     = null;
            ProjectMetadata       metadata = null;

            if (project.ItemDefinitions.TryGetValue("IceBuilder", out item))
            {
                metadata = item.Metadata.FirstOrDefault(m => m.Name.Equals(name));
            }
            else
            {
                metadata =
                    project.AllEvaluatedItemDefinitionMetadata.FirstOrDefault(
                        m => m.ItemType.Equals("IceBuilder") && m.Name.Equals(name));
            }
            return(metadata == null ? String.Empty : metadata.EvaluatedValue);
        }
コード例 #39
0
        public static string GetPreProcessorConstantsFromProject(Microsoft.Build.Evaluation.Project coreVisualStudioProject)
        {
            string preProcessorConstants = "";

            // Victor Chelaru October 20, 2012
            // We used to just look at the XML and had a broad way of determining the
            // patterns.  I decided it was time to clean this up and make it more precise
            // so now we use the Properties from the project.
            foreach (var property in coreVisualStudioProject.Properties)
            {
                if (property.Name == "DefineConstants")
                {
                    preProcessorConstants += ";" + property.EvaluatedValue;
                }
            }
            return(preProcessorConstants);
        }
コード例 #40
0
ファイル: ReferenceContainerNode.cs プロジェクト: krus/PTVS
        /// <summary>
        /// Adds references to this container from a MSBuild project.
        /// </summary>
        public void LoadReferencesFromBuildProject(MSBuild.Project buildProject)
        {
            ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread();

            foreach (string referenceType in SupportedReferenceTypes)
            {
                IEnumerable <MSBuild.ProjectItem> referencesGroup = this.ProjectMgr.BuildProject.GetItems(referenceType);

                bool isAssemblyReference = referenceType == ProjectFileConstants.Reference;
                // If the project was loaded for browsing we should still create the nodes but as not resolved.
                if (isAssemblyReference &&
                    (!ProjectMgr.BuildProject.Targets.ContainsKey(MsBuildTarget.ResolveAssemblyReferences) || this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Successful))
                {
                    continue;
                }

                foreach (MSBuild.ProjectItem item in referencesGroup)
                {
                    ProjectElement element = new MsBuildProjectElement(this.ProjectMgr, item);

                    ReferenceNode node = CreateReferenceNode(referenceType, element);

                    if (node != null)
                    {
                        // Make sure that we do not want to add the item twice to the ui hierarchy
                        // We are using here the UI representation of the Node namely the Caption to find that out, in order to
                        // avoid different representation problems.
                        // Example :<Reference Include="EnvDTE80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                        //		  <Reference Include="EnvDTE80" />
                        bool found = false;
                        for (HierarchyNode n = this.FirstChild; n != null && !found; n = n.NextSibling)
                        {
                            if (String.Compare(n.Caption, node.Caption, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                found = true;
                            }
                        }

                        if (!found)
                        {
                            this.AddChild(node);
                        }
                    }
                }
            }
        }
コード例 #41
0
        public void SpecialCharactersInMetadataValueConstruction()
        {
            string projectString = ObjectModelHelpers.CleanupFileContents(@"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
    <ItemGroup>
        <None Include='MetadataTests'>
            <EscapedSemicolon>%3B</EscapedSemicolon>
            <EscapedDollarSign>%24</EscapedDollarSign>
        </None>
    </ItemGroup>
</Project>");

            System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString));
            Microsoft.Build.Evaluation.Project     project = new Microsoft.Build.Evaluation.Project(reader);
            Microsoft.Build.Evaluation.ProjectItem item    = project.GetItems("None").Single();

            SpecialCharactersInMetadataValueTests(item);
        }
コード例 #42
0
        public static bool IsIceBuilderEnabled(Microsoft.Build.Evaluation.Project project)
        {
            bool value = false;

            if (IsCppProject(project))
            {
                value = HasImport(project, IceBuilderCppProps) && HasImport(project, IceBuilderCppTargets);
                value = value || (HasImport(project, IceBuilderCppPropsPathOld) && HasImport(project, IceBuilderCppTargetsPathOld));
            }
            else if (IsCSharpProject(project))
            {
                value = HasImport(project, IceBuilderCSharpProps) && HasImport(project, IceBuilderCSharpTargets);
                value = value || (HasImport(project, IceBuilderCSharpPropsPathOld) && HasImport(project, IceBuilderCSharpTargetsPathOld));
                value = value && HasProjectFlavor(project, IceBuilderProjectFlavorGUID);
            }
            return(value);
        }
コード例 #43
0
        public static bool AddIceBuilderToProject(Microsoft.Build.Evaluation.Project project)
        {
            bool modified = false;

            if (project != null)
            {
                if (IsCppProject(project))
                {
                    modified = SetupCppProject(project);
                }
                else if (IsCSharpProject(project))
                {
                    modified = SetupCsharpProject(project);
                }
            }
            return(modified);
        }
コード例 #44
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 platformTarget         = project.GetPropertyValue(PropertyNames.PlatformTarget);
                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 warningsAsErrors               = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsAsErrors), ',');
                var warningsNotAsErrors            = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsNotAsErrors), ',');
                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);
                var runAnalyzers                   = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzers), defaultValue: true);
                var runAnalyzersDuringLiveAnalysis = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzersDuringLiveAnalysis), defaultValue: true);

                return(new ProjectData(
                           guid, name, assemblyName, targetPath, outputPath, intermediateOutputPath, projectAssetsFile,
                           configuration, platform, platformTarget, targetFramework, targetFrameworks, outputKind, languageVersion, nullableContextOptions, allowUnsafeCode, checkForOverflowUnderflow,
                           documentationFile, preprocessorSymbolNames, suppressedDiagnosticIds, warningsAsErrors, warningsNotAsErrors, signAssembly, assemblyOriginatorKeyFile, treatWarningsAsErrors, defaultNamespace, runAnalyzers, runAnalyzersDuringLiveAnalysis, ruleset: null));
            }
コード例 #45
0
ファイル: Extensions.cs プロジェクト: nayanshah/MSBuildTracer
        /// <summary>
        /// Gets a collection of ProjectTargetInstances that this target is dependent on in a given project.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="project">The project to look in</param>
        /// <returns></returns>
        public static IEnumerable <MBEX.ProjectTargetInstance> Dependencies(
            this MBEX.ProjectTargetInstance target, MBEV.Project project)
        {
            var dependencies          = new List <MBEX.ProjectTargetInstance>();
            var dependencyTargetNames = project.ResolveAllProperties(target.DependsOnTargets)
                                        .Replace(Environment.NewLine, "")
                                        .Split(';');

            foreach (var name in dependencyTargetNames)
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    dependencies.Add(project.Targets[name.Trim()]);
                }
            }

            return(dependencies);
        }
コード例 #46
0
        public void GetPropertyWithInvalidArgs()
        {
            CodeSweep.VSPackage.BuildManager_Accessor accessor = new CodeSweep.VSPackage.BuildManager_Accessor(_serviceProvider);

            bool thrown = Utilities.HasFunctionThrown <ArgumentNullException>(delegate { accessor.GetProperty(null, "foo"); });

            Assert.IsTrue(thrown, "GetProperty did not throw ArgumentNullException with null project arg.");

            Microsoft.Build.Evaluation.Project project = Utilities.SetupMSBuildProject();

            MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);

            thrown = Utilities.HasFunctionThrown <ArgumentNullException>(delegate { accessor.GetProperty(vsProject, null); });
            Assert.IsTrue(thrown, "GetProperty did not throw ArgumentNullException with null name arg.");

            thrown = Utilities.HasFunctionThrown <ArgumentException>(delegate { accessor.GetProperty(vsProject, ""); });
            Assert.IsTrue(thrown, "GetProperty did not throw ArgumentException with empty name arg.");
        }
コード例 #47
0
 public IEnumerable <object> EvaluateProjectItems(FilePath ProjectFile)
 {
     try
     {
         var project = new MSEV.Project(ProjectFile);
         var query   = from g in project.AllEvaluatedItems
                       group g by g.ItemType into ig
                       orderby ig.Key
                       from i in ig
                       select i;
         return(query);
     }
     catch (Exception e)
     {
         Notify(error($"Error occurred during item evaluation of {ProjectFile}: {e}"));
         return(stream <object>());
     }
 }
コード例 #48
0
        private static T?GetEnumFromProperty <T>(Microsoft.Build.Evaluation.Project project, string propertyName) where T : struct
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName");
            }
            var value = project.GetPropertyValue(propertyName);

            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }
            return((T)Enum.Parse(typeof(T), value));
        }
コード例 #49
0
        /// <summary>
        /// Generates a project object of the elements set so forth in this object. This returns the new MSBuild project instance
        /// </summary>
        public ProjectInstance GetMSBuildProjectInstance()
        {
            if (!this.createMSBuildProject)
            {
                return(null);
            }

            if (this.msbuildProjectInstance != null)
            {
                return(this.msbuildProjectInstance);
            }

            CreateDefaultTarget();
            ProjectRootElement pXml = ProjectRootElement.Open(this.projectXmlDocument);

            Microsoft.Build.Evaluation.Project pDef = new Microsoft.Build.Evaluation.Project(pXml);
            return(pDef.CreateProjectInstance());
        }
コード例 #50
0
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project();
            var metadata = new Dictionary <string, string>
            {
                { "EscapedSemicolon", "%3B" },  // Microsoft.Build.Internal.Utilities.Escape(";")
                { "EscapedDollarSign", "%24" }, // Microsoft.Build.Internal.Utilities.Escape("$")
            };

            Microsoft.Build.Evaluation.ProjectItem item = project.AddItem(
                "None",
                "MetadataTests",
                metadata).Single();

            SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            SpecialCharactersInMetadataValueTests(item);
        }
コード例 #51
0
        public static bool UpgradeProjectImports(Microsoft.Build.Evaluation.Project project)
        {
            bool modified = false;

            if (IsCppProject(project))
            {
                modified = AddCppGlobalProperties(project);
                modified = UpdateImport(project, IceBuilderCppPropsPathOld, IceBuilderCppProps) || modified;
                modified = UpdateImport(project, IceBuilderCppTargetsPathOld, IceBuilderCppTargets) || modified;
            }
            else if (IsCSharpProject(project))
            {
                modified = AddCsharpGlobalProperties(project);
                modified = UpdateImport(project, IceBuilderCSharpPropsPathOld, IceBuilderCSharpProps) || modified;
                modified = UpdateImport(project, IceBuilderCSharpTargetsPathOld, IceBuilderCSharpTargets) || modified;
            }
            return(modified);
        }
コード例 #52
0
        private void LoadStrongName(MSBuildAssembly assembly, Build.Project project, string projectFolder)
        {
            string keyFile  = GetKeyFile(project, projectFolder);
            string password = null;

            if (StrongNameUtils.IsPKCS12File(keyFile))
            {
                if (!StrongNamePasswordCache.TryGet(keyFile, out password))
                {
                    return;
                }
            }

            assembly.Sign        = true;
            assembly.DelaySign   = IsDelaySign(project);
            assembly.KeyFilePath = keyFile;
            assembly.KeyPassword = password;
        }
コード例 #53
0
        private bool GetBoolProperty(Build.Project project, string name)
        {
            string s = project.GetPropertyValue(name);

            if (string.IsNullOrEmpty(s))
            {
                return(false);
            }

            bool result;

            if (!bool.TryParse(s, out result))
            {
                return(false);
            }

            return(true);
        }
コード例 #54
0
ファイル: CustomItem.cs プロジェクト: zjherp/nodejstools
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            var filename = Path.Combine(project.DirectoryPath, Name);

            if (!IsMissing)
            {
                File.WriteAllText(filename, Content);
            }

            if (!IsExcluded)
            {
                project.AddItem(
                    ItemType,
                    Name,
                    Metadata
                    );
            }
        }
コード例 #55
0
        IEnumerable <string> ResolveAssemblyReferences(Microsoft.Build.Evaluation.Project project)
        {
            // Use MSBuild to figure out the full path of the referenced assemblies
            var projectInstance = project.CreateProjectInstance();

            projectInstance.SetProperty("BuildingProject", "false");
            project.SetProperty("DesignTimeBuild", "true");

            //projectInstance.Build("ResolveAssemblyReferences", new [] { new ConsoleLogger(LoggerVerbosity.Minimal) });
            projectInstance.Build();
            //projectInstance.Build("ResolveAssemblyReferences", new[] { new ConsoleLogger(LoggerVerbosity.Minimal) });

            var items = projectInstance.GetItems("_ResolveAssemblyReferenceResolvedFiles");

            string baseDirectory = Path.GetDirectoryName(this.FileName);

            return(items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity"))));
        }
コード例 #56
0
        public void TestBuildBegin()
        {
            CodeSweep.VSPackage.BuildManager_Accessor accessor = new CodeSweep.VSPackage.BuildManager_Accessor(_serviceProvider);

            accessor.IsListeningToBuildEvents = true;

            // Listen for task list refresh events.
            List <int>   resultCounts = new List <int>();
            MockTaskList taskList     = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;

            taskList.OnRefreshTasks += delegate(object sender, MockTaskList.RefreshTasksArgs args)
            {
                resultCounts.Add(Utilities.TasksOfProvider(args.Provider).Count);
            };

            // Create multiple projects with ScannerTask tasks.
            string scanFile  = Utilities.CreateTempTxtFile("foo abc foo def foo");
            string termTable = Utilities.CreateTermTable(new string[] { "foo", "bar" });

            Microsoft.Build.Evaluation.Project project1 = Utilities.SetupMSBuildProject(new string[] { scanFile }, new string[] { termTable });
            Microsoft.Build.Evaluation.Project project2 = Utilities.SetupMSBuildProject(new string[] { scanFile }, new string[] { termTable });

            Utilities.RegisterProjectWithMocks(project1, _serviceProvider);
            Utilities.RegisterProjectWithMocks(project2, _serviceProvider);

            // Fire the build begin event.
            MockDTE         dte         = _serviceProvider.GetService(typeof(EnvDTE.DTE)) as MockDTE;
            MockBuildEvents buildEvents = dte.Events.BuildEvents as MockBuildEvents;

            buildEvents.FireOnBuildBegin(vsBuildScope.vsBuildScopeProject, vsBuildAction.vsBuildActionBuild);

            try
            {
                Assert.IsNotNull(ProjectCollection.GlobalProjectCollection.HostServices.GetHostObject(project1.FullPath, "AfterBuild", "ScannerTask"), "Host object for task in first project not set.");
                Assert.IsNotNull(ProjectCollection.GlobalProjectCollection.HostServices.GetHostObject(project2.FullPath, "AfterBuild", "ScannerTask"), "Host object for task in second project not set.");

                Assert.AreEqual(1, resultCounts.Count, "Task list recieved wrong number of refresh requests.");
                Assert.AreEqual(0, resultCounts[0], "Task list was not cleared.");
            }
            finally
            {
                buildEvents.FireOnBuildDone(vsBuildScope.vsBuildScopeProject, vsBuildAction.vsBuildActionBuild);
            }
        }
コード例 #57
0
        static int Main(string[] args)
        {
            var options = Options.ProcessCommandLineArguments(args);

            if (!options.Valid)
            {
                Usage();
                return(1);
            }

            MBEV.Project project;

            try
            {
                project = new MBEV.Project(options.Filename);
            }
            catch (Microsoft.Build.Exceptions.InvalidProjectFileException e)
            {
                Console.WriteLine($"The project file '{options.Filename}' is invalid or doesn't exist.");
                Console.WriteLine();
                Console.WriteLine(e.Message);
                return(1);
            }

            switch (options.Mode)
            {
            case Mode.Imports:

                new ImportTracer(project).TraceAll();
                break;

            case Mode.Properties:

                new PropertyTracer(project).TraceAll(options.Query);
                break;

            case Mode.Targets:

                new TargetTracer(project).TraceAll(options.Query);
                break;
            }

            return(0);
        }
コード例 #58
0
        public void PostProcess(MSBuild.Project project)
        {
            var projectExt = project.Xml.CreateProjectExtensionsElement();

            projectExt.Content = @"
    <VisualStudio>
      <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"">
        <WebProjectProperties>
          <UseIIS>False</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>0</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl>http://localhost:48022/</IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>True</UseCustomServer>
          <CustomServerUrl>http://localhost:1337</CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
      <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"" User="""">
        <WebProjectProperties>
          <StartPageUrl>
          </StartPageUrl>
          <StartAction>CurrentPage</StartAction>
          <AspNetDebugging>True</AspNetDebugging>
          <SilverlightDebugging>False</SilverlightDebugging>
          <NativeDebugging>False</NativeDebugging>
          <SQLDebugging>False</SQLDebugging>
          <ExternalProgram>
          </ExternalProgram>
          <StartExternalURL>
          </StartExternalURL>
          <StartCmdLineArguments>
          </StartCmdLineArguments>
          <StartWorkingDirectory>
          </StartWorkingDirectory>
          <EnableENC>False</EnableENC>
          <AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
";
            project.Xml.AppendChild(projectExt);
        }
コード例 #59
0
ファイル: NuGet.cs プロジェクト: frasten/FixNuGetPackagePaths
        private static int ModifyPackagePaths(MsBuild.Project project, IReadOnlyCollection <IVsPackageMetadata> packages, string slnDir, ModifyPackagePathDelegate modifyPackagePath)
        {
            const string pathAttributeName = "HintPath";
            var          projectDirPath    = project.DirectoryPath;
            var          result            = 0;

            foreach (var reference in project.GetItems("Reference").Where(r => r.HasMetadata(pathAttributeName)))
            {
                var metadata = reference.GetMetadata(pathAttributeName);
                var newPath  = modifyPackagePath(metadata.EvaluatedValue, metadata.UnevaluatedValue, packages, slnDir, projectDirPath);
                result += SetIfNew("reference", x => metadata.UnevaluatedValue = x, newPath, metadata.UnevaluatedValue);
            }

            foreach (var import in project.Imports)
            {
                var unevaluatedOldPath = import.ImportingElement.Project;
                var evaluatedOldPath   = import.ImportedProject.FullPath;

                var newPath = modifyPackagePath(evaluatedOldPath, unevaluatedOldPath, packages, slnDir, projectDirPath);
                result += SetIfNew("import path", x => import.ImportingElement.Project = x, newPath, unevaluatedOldPath);

                var oldCondition = import.ImportingElement.Condition;
                var newCondition = GetNewImportCondition(oldCondition, evaluatedOldPath, unevaluatedOldPath, packages, slnDir, projectDirPath, modifyPackagePath);
                result += SetIfNew("import condition", x => import.ImportingElement.Condition = x, newCondition, oldCondition);
            }

            var errors = project.Xml.Targets
                         .Where(x => x.Name == "EnsureNuGetPackageBuildImports")
                         .SelectMany(t => t.Children)
                         .OfType <ProjectTaskElement>()
                         .Where(x => x.Name == "Error");

            foreach (var error in errors)
            {
                var oldCondition = error.Condition;
                var newCondition = GetNewErrorCondition(oldCondition, packages, slnDir, projectDirPath, modifyPackagePath, project);
                result += SetIfNew("error condition", x => error.Condition = x, newCondition, oldCondition);

                var oldText = error.GetParameter("Text");
                var newText = GetNewErrorText(oldText, packages, slnDir, projectDirPath, modifyPackagePath, project);
                result += SetIfNew("error text", x => error.SetParameter("Text", x), newText, oldText);
            }
            return(result);
        }
コード例 #60
0
        private ClassifiedReferences ClassifyReferences(
            Microsoft.Build.Evaluation.Project project,
            IReadOnlyCollection <INuGetPackage> nuGetPackages,
            ISolution solution)
        {
            var projectReferences = project.GetItemsIgnoringCondition("ProjectReference").Select(r => new ProjectReference(solution, r));

            var dllReferences =
                project.GetItemsIgnoringCondition("Reference")
                .Select(r => new ReferenceItem(r.EvaluatedInclude, r.Metadata.ToDictionary(m => m.Name, m => m.EvaluatedValue)));

            var gacReferences   = new List <GacReference>();
            var fileReferences  = new List <FileReference>();
            var nuGetReferences = new List <NuGetReference>();

            foreach (var reference in dllReferences)
            {
                if (reference.HintPath == null)
                {
                    gacReferences.Add(new GacReference(reference.AssemblyName));
                    continue;
                }

                var matchingNuGetPackage =
                    nuGetPackages.SingleOrDefault(p => reference.HintPath.StartsWith($@"..\packages\{p.PackageDirectoryName}", StringComparison.Ordinal));

                if (matchingNuGetPackage != null)
                {
                    nuGetReferences.Add(
                        new NuGetReference(
                            matchingNuGetPackage,
                            reference.AssemblyName,
                            reference.Metadata.GetValueOrDefault("Private") == "True",
                            reference.HintPath,
                            project.DirectoryPath));
                }
                else
                {
                    fileReferences.Add(new FileReference(reference.AssemblyName, reference.HintPath, project.DirectoryPath));
                }
            }

            return(new ClassifiedReferences(gacReferences, fileReferences, nuGetReferences, projectReferences));
        }