当前位置: 首页>>代码示例>>C#>>正文


C# Project.Save方法代码示例

本文整理汇总了C#中Microsoft.Build.BuildEngine.Project.Save方法的典型用法代码示例。如果您正苦于以下问题:C# Project.Save方法的具体用法?C# Project.Save怎么用?C# Project.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Build.BuildEngine.Project的用法示例。


在下文中一共展示了Project.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

		public override bool Execute() {
			if (this.ProjectReferences.Length != this.References.Length) {
				this.Log.LogError("ProjectReferences and References arrays do not have matching lengths.");
			}

			foreach (var project in Projects) {
				Project doc = new Project();
				doc.Load(project.ItemSpec);

				var projectReferences = doc.EvaluatedItems.OfType<BuildItem>().Where(item => item.Name == "ProjectReference");
				var matchingReferences = from reference in projectReferences
										 join refToRemove in this.ProjectReferences on reference.Include equals refToRemove.ItemSpec
										 let addIndex = Array.IndexOf(this.ProjectReferences, refToRemove)
										 select new { Remove = reference, Add = this.References[addIndex] };
				foreach (var matchingReference in matchingReferences) {
					this.Log.LogMessage("Removing project reference to \"{0}\" from \"{1}\".", matchingReference.Remove.Include, project.ItemSpec);
					doc.RemoveItem(matchingReference.Remove);
					if (matchingReference.Add.ItemSpec != "REMOVE") {
						this.Log.LogMessage("Adding assembly reference to \"{0}\" to \"{1}\".", matchingReference.Add.ItemSpec, project.ItemSpec);
						var newReference = doc.AddNewItem("Reference", Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec), true);
						newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec);
					}
				}

				doc.Save(project.ItemSpec);
			}

			return true;
		}
开发者ID:jongalloway,项目名称:dotnetopenid,代码行数:29,代码来源:ChangeProjectReferenceToAssemblyReference.cs

示例2: Execute

		/// <summary>
		/// Executes this instance.
		/// </summary>
		public override bool Execute() {
			foreach (var projectTaskItem in this.Projects) {
				var project = new Project();
				project.Load(projectTaskItem.ItemSpec);

				foreach (var projectItem in this.Items) {
					string itemType = projectItem.GetMetadata("ItemType");
					if (string.IsNullOrEmpty(itemType)) {
						itemType = "None";
					}
					BuildItem newItem = project.AddNewItem(itemType, projectItem.ItemSpec, false);
					var customMetadata = projectItem.CloneCustomMetadata();
					foreach (DictionaryEntry entry in customMetadata) {
						string value = (string)entry.Value;
						if (value.Length > 0) {
							newItem.SetMetadata((string)entry.Key, value);
						}
					}
				}

				project.Save(projectTaskItem.ItemSpec);
			}

			return !this.Log.HasLoggedErrors;
		}
开发者ID:jongalloway,项目名称:dotnetopenid,代码行数:28,代码来源:AddProjectItems.cs

示例3: Execute

		/// <summary>
		/// Executes this instance.
		/// </summary>
		/// <returns></returns>
		public override bool Execute() {
			foreach (ITaskItem projectTaskItem in this.Projects) {
				this.Log.LogMessage("Fixing up the {0} sample for shipping as source code.", Path.GetFileNameWithoutExtension(projectTaskItem.ItemSpec));

				var project = new Project();
				Uri projectUri = new Uri(projectTaskItem.GetMetadata("FullPath"));
				project.Load(projectTaskItem.ItemSpec, ProjectLoadSettings.IgnoreMissingImports);

				if (this.RemoveImportsStartingWith != null && this.RemoveImportsStartingWith.Length > 0) {
					project.Imports.Cast<Import>()
						.Where(import => this.RemoveImportsStartingWith.Any(start => import.ProjectPath.StartsWith(start, StringComparison.OrdinalIgnoreCase)))
						.ToList()
						.ForEach(import => project.Imports.RemoveImport(import));
				}

				if (this.AddReferences != null) {
					foreach (var reference in this.AddReferences) {
						BuildItem item = project.AddNewItem("Reference", reference.ItemSpec);
						foreach (DictionaryEntry metadata in reference.CloneCustomMetadata()) {
							item.SetMetadata((string)metadata.Key, (string)metadata.Value);
						}
					}
				}

				project.Save(projectTaskItem.ItemSpec);
			}

			return !this.Log.HasLoggedErrors;
		}
开发者ID:hnlshzx,项目名称:DotNetOpenAuth,代码行数:33,代码来源:FixupShippingToolSamples.cs

示例4: Execute

		/// <summary>
		/// Executes this instance.
		/// </summary>
		public override bool Execute() {
			foreach (ITaskItem taskItem in this.Projects) {
				switch (GetClassification(taskItem)) {
					case ProjectClassification.VS2010Project:
						this.Log.LogMessage(MessageImportance.Low, "Downgrading project \"{0}\".", taskItem.ItemSpec);
						Project project = new Project();
						project.Load(taskItem.ItemSpec);
						project.DefaultToolsVersion = "3.5";

						if (this.DowngradeMvc2ToMvc1) {
							string projectTypeGuids = project.GetEvaluatedProperty("ProjectTypeGuids");
							if (!string.IsNullOrEmpty(projectTypeGuids)) {
								projectTypeGuids = projectTypeGuids.Replace("{F85E285D-A4E0-4152-9332-AB1D724D3325}", "{603c0e0b-db56-11dc-be95-000d561079b0}");
								project.SetProperty("ProjectTypeGuids", projectTypeGuids);
							}
						}

						// Web projects usually have an import that includes these substrings
						foreach (Import import in project.Imports) {
							import.ProjectPath = import.ProjectPath
								.Replace("$(MSBuildExtensionsPath32)", "$(MSBuildExtensionsPath)")
								.Replace("VisualStudio\\v10.0", "VisualStudio\\v9.0");
						}

						// VS2010 won't let you have a System.Core reference, but VS2008 requires it.
						BuildItemGroup references = project.GetEvaluatedItemsByName("Reference");
						if (!references.Cast<BuildItem>().Any(item => item.FinalItemSpec.StartsWith("System.Core", StringComparison.OrdinalIgnoreCase))) {
							project.AddNewItem("Reference", "System.Core");
						}

						project.Save(taskItem.ItemSpec);
						break;
					case ProjectClassification.VS2010Solution:
						this.Log.LogMessage(MessageImportance.Low, "Downgrading solution \"{0}\".", taskItem.ItemSpec);
						string[] contents = File.ReadAllLines(taskItem.ItemSpec);
						if (contents[1] != "Microsoft Visual Studio Solution File, Format Version 11.00" ||
							contents[2] != "# Visual Studio 2010") {
							this.Log.LogError("Unrecognized solution file header in \"{0}\".", taskItem.ItemSpec);
							break;
						}

						contents[1] = "Microsoft Visual Studio Solution File, Format Version 10.00";
						contents[2] = "# Visual Studio 2008";

						for (int i = 3; i < contents.Length; i++) {
							contents[i] = contents[i].Replace("TargetFrameworkMoniker = \".NETFramework,Version%3Dv", "TargetFramework = \"");
						}

						File.WriteAllLines(taskItem.ItemSpec, contents);
						break;
					default:
						this.Log.LogWarning("Unrecognized project type for \"{0}\".", taskItem.ItemSpec);
						break;
				}
			}

			return !this.Log.HasLoggedErrors;
		}
开发者ID:jongalloway,项目名称:dotnetopenid,代码行数:61,代码来源:DowngradeProjects.cs

示例5: Main

        public static void Main(string[] args)
        {
            var parser = new Parser(new Worm.WormFactory());
            string workingDir = Directory.GetCurrentDirectory();

            DirectoryInfo libRoot = Directory.GetParent(workingDir).Parent.Parent.GetDirectories("fullflow-lib")[0];
            string modelProjectFile = String.Format("{0}/fullflow-lib.csproj", libRoot.FullName);

            PocoModel model = parser.Parse(modelProjectFile);

            foreach (PocoEntity entity in model.Entities)
            {
                Console.WriteLine("DbFactory: {0}", entity.DbFactory.GetType().Name);
                Console.WriteLine("PocoClassName: {0}", entity.PocoClassName);
                Console.WriteLine("PocoFilename: {0}", entity.PocoFilename);
                Console.WriteLine("PocoNamespace: {0}", entity.PocoNamespace);
                Console.WriteLine("TableName: {0}", entity.TableName);
                Console.WriteLine();

                foreach (PocoField field in entity.Fields)
                {
                    Console.WriteLine("AccessModifier: {0}", field.AccessModifier);
                    Console.WriteLine("AllowNull: {0}", field.AllowNull);
                    Console.WriteLine("ColumnName: {0}", field.ColumnName);
                    Console.WriteLine("HasGetter: {0}", field.HasGetter);
                    Console.WriteLine("HasSetter: {0}", field.HasSetter);
                    Console.WriteLine("IdGenerator: {0}", field.IdGenerator);
                    Console.WriteLine("IsEnum: {0}", field.IsEnum);
                    Console.WriteLine("IsPrimaryKey: {0}", field.IsPrimaryKey);
                    Console.WriteLine("Name: {0}", field.Name);
                    Console.WriteLine("StorageType: {0}", field.StorageType);
                    Console.WriteLine("Type: {0}", field.Type);
                    Console.WriteLine();
                }

                Console.WriteLine();
            }

            Engine eng = new Engine();
            Project proj = new Project(eng);
            proj.Load(modelProjectFile);
            BuildItemGroup compileBuildItemGroup = GetCompileIncludeBuildItemGroup(proj);

            var writer = new DbClassWriter(new WormFactory());
            foreach (PocoEntity entity in model.Entities)
            {
                CodeFile cf = writer.Generate(entity);
                //cf.Filename = cf.Filename.Replace("fullflowlib", "fullflow-lib");
                WriteCodeFile(libRoot, cf);
                AddFileToProject(compileBuildItemGroup, cf);
            }

            proj.Save(modelProjectFile);

            // compile the project again
            parser.Parse(modelProjectFile);
        }
开发者ID:pingvinen,项目名称:worm,代码行数:57,代码来源:Program.cs

示例6: Execute

		public override bool Execute() {
			foreach (var project in Projects) {
				Project doc = new Project();
				doc.Load(project.ItemSpec);
				
				var reference = doc.GetEvaluatedItemsByName("Reference").OfType<BuildItem>().
					Where(item => string.Equals(item.GetMetadata("HintPath"), OldReference, StringComparison.OrdinalIgnoreCase)).Single();
				reference.SetMetadata("HintPath", NewReference);

				doc.Save(project.ItemSpec);
			}

			return true;
		}
开发者ID:hnlshzx,项目名称:DotNetOpenAuth,代码行数:14,代码来源:ChangeAssemblyReference.cs

示例7: Execute

		public override bool Execute() {
			foreach (var project in Projects) {
				Project doc = new Project();
				doc.Load(project.ItemSpec);
				
				var projectReference = doc.EvaluatedItems.OfType<BuildItem>().Where(
					item => item.Name == "ProjectReference" && item.Include == ProjectReference).Single();
				doc.RemoveItem(projectReference);

				var newReference = doc.AddNewItem("Reference", Path.GetFileNameWithoutExtension(Reference));
				newReference.SetMetadata("HintPath", Reference);

				doc.Save(project.ItemSpec);
			}

			return true;
		}
开发者ID:Belxjander,项目名称:Asuna,代码行数:17,代码来源:ChangeProjectReferenceToAssemblyReference.cs

示例8: ImportsUsingTask

 public void ImportsUsingTask()
 {
     string importPath = String.Empty;
     try
     {
         importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified);
         Project p = new Project();
         p.Save(importPath); // required to reproduce
         importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskFile);
         Project p2 = new Project(); // new Engine() here fixes testcase
         p2.AddNewImport(importPath, "true");
         object o = p2.EvaluatedProperties; // evaluate the import
         Assertion.AssertNull(CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p2.UsingTasks)); // fails to find task
     }
     finally
     {
         CompatibilityTestHelpers.RemoveFile(importPath);
     }
 }
开发者ID:nikson,项目名称:msbuild,代码行数:19,代码来源:UsingTaskCollection_Tests.cs

示例9: Execute

		/// <summary>
		/// Executes this instance.
		/// </summary>
		public override bool Execute() {
			if (this.References.Length == 0 || this.Projects.Length == 0) {
				this.Log.LogMessage(MessageImportance.Low, "Skipping reference hintpath fixup because no projects or no references were supplied.");
				return !this.Log.HasLoggedErrors;
			}

			// Figure out what the assembly names are of the references that are available.
			AssemblyName[] availableReferences = new AssemblyName[this.References.Length];
			for (int i = 0; i < this.References.Length; i++) {
				if (File.Exists(this.References[i].ItemSpec)) {
					availableReferences[i] = AssemblyName.GetAssemblyName(this.References[i].ItemSpec);
				} else {
					availableReferences[i] = new AssemblyName(Path.GetFileNameWithoutExtension(this.References[i].ItemSpec)) {
						CodeBase = this.References[i].GetMetadata("FullPath"),
					};
				}
			}

			foreach (var projectTaskItem in this.Projects) {
				var project = new Project();
				Uri projectUri = new Uri(projectTaskItem.GetMetadata("FullPath"));
				project.Load(projectTaskItem.ItemSpec);

				foreach (BuildItem referenceItem in project.GetEvaluatedItemsByName("Reference")) {
					var referenceAssemblyName = new AssemblyName(referenceItem.Include);
					var matchingReference = availableReferences.FirstOrDefault(r => string.Equals(r.Name, referenceAssemblyName.Name, StringComparison.OrdinalIgnoreCase));
					if (matchingReference != null) {
						var originalSuppliedReferenceItem = this.References[Array.IndexOf(availableReferences, matchingReference)];
						string hintPath = originalSuppliedReferenceItem.GetMetadata("HintPath");
						if (string.IsNullOrEmpty(hintPath)) {
							hintPath = projectUri.MakeRelativeUri(new Uri(matchingReference.CodeBase)).OriginalString.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
						}
						this.Log.LogMessage("Fixing up HintPath to \"{0}\" in project \"{1}\".", referenceAssemblyName.Name, projectTaskItem.ItemSpec);
						referenceItem.SetMetadata("HintPath", hintPath);
					}
				}

				project.Save(projectTaskItem.ItemSpec);
			}

			return !this.Log.HasLoggedErrors;
		}
开发者ID:hnlshzx,项目名称:DotNetOpenAuth,代码行数:45,代码来源:FixupReferenceHintPaths.cs

示例10: Execute

        public override bool Execute()
        {
            try
            {
                Project input = new Project();

                input.Load(m_inputFile);

                bool fFound = false;

                foreach (BuildPropertyGroup bpg in input.PropertyGroups)
                {
                    if (bpg.IsImported) continue;

                    foreach (BuildProperty bp in bpg)
                    {
                        if (string.Compare(bp.Name, "BuildNumber", true) == 0)
                        {
                            bp.Value = 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;
        }
开发者ID:prabby,项目名称:miniclr,代码行数:36,代码来源:GenerateReleaseInfo.cs

示例11: Execute

		public override bool Execute() {
			if (this.ProjectReferences.Length != this.References.Length) {
				this.Log.LogError("ProjectReferences and References arrays do not have matching lengths.");
				this.Log.LogError("ProjectReferences contents ({0} elements): {1}", this.ProjectReferences.Length, String.Join<ITaskItem>(";", this.ProjectReferences));
				this.Log.LogError("References contents ({0} elements): {1}", this.References.Length, String.Join<ITaskItem>(";", this.References));
				return false;
			}

			foreach (var project in Projects) {
				Project doc = new Project();
				doc.Load(project.ItemSpec, ProjectLoadSettings.IgnoreMissingImports);

				var projectReferences = doc.EvaluatedItems.OfType<BuildItem>().Where(item => item.Name == "ProjectReference");
				var matchingReferences = from reference in projectReferences
										 join refToRemove in this.ProjectReferences on reference.Include equals refToRemove.ItemSpec
										 let addIndex = Array.IndexOf(this.ProjectReferences, refToRemove)
										 select new { Remove = reference, Add = this.References[addIndex] };
				foreach (var matchingReference in matchingReferences) {
					this.Log.LogMessage("Removing project reference to \"{0}\" from \"{1}\".", matchingReference.Remove.Include, project.ItemSpec);
					doc.RemoveItem(matchingReference.Remove);
					if (matchingReference.Add.ItemSpec != "REMOVE") {
						this.Log.LogMessage("Adding assembly reference to \"{0}\" to \"{1}\".", matchingReference.Add.ItemSpec, project.ItemSpec);

						string newItemSpec = Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec);
						if (!doc.GetEvaluatedItemsByName("Reference").OfType<BuildItem>().Any(bi => String.Equals(bi.Include, newItemSpec, StringComparison.OrdinalIgnoreCase))) {
							var newReference = doc.AddNewItem("Reference", newItemSpec, true);
							newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec);
						}
					}
				}

				doc.Save(project.ItemSpec);
			}

			return true;
		}
开发者ID:hnlshzx,项目名称:DotNetOpenAuth,代码行数:36,代码来源:ChangeProjectReferenceToAssemblyReference.cs

示例12: Execute


//.........这里部分代码省略.........
                phoneFileItemGroup.AddNewItem("Compile", Path.Combine("Properties", "AssemblyInfo.cs"));
            }
            catch(Exception)
            {
                System.Diagnostics.Trace.WriteLine("Couldn't generate the AssemblyInfo.cs file for this project", "warn");
            }
            #endregion
            #endregion

            #region Code Create
            // Convert class rep to list
            List<Feature> features = new List<Feature>();
            foreach (KeyValuePair<String, Feature> kv in classRep)
                features.Add(kv.Value);
            // Sort so classes are processed first
            features.Sort(delegate(Feature a, Feature b)
            {
                if ((a is SubSystem) && !(b is SubSystem)) return -1;
                else if ((b is SubSystem) && !(a is SubSystem)) return 1;
                else return a.GetType().Name.CompareTo(b.GetType().Name);
            });

            RenderFeatureList(features, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Any added features?
            // HACK: This should be fixed soon, but meh... I'll get around to it
            List<Feature> addlFeatures = new List<Feature>();
            foreach (KeyValuePair<String, Feature> kv in classRep)
                if(!features.Contains(kv.Value))
                    addlFeatures.Add(kv.Value);
            RenderFeatureList(addlFeatures, templateFields, renderers, fileItemGroup, phoneFileItemGroup, parameters);

            // Save the project
            project.Save(Path.Combine(hostContext.Output, ProjectFileName) + ".csproj");
            #endregion

            // Compile?
            #region Compile this project

            // Does the user want to compile?
            if (parameters.ContainsKey("rimbapi-compile") && Convert.ToBoolean(parameters["rimbapi-compile"][0]))
            {
                string logPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); // Create log
                Microsoft.Build.BuildEngine.FileLogger logger = new Microsoft.Build.BuildEngine.FileLogger();
                logger.Parameters = "logfile=" + logPath;
                engine.RegisterLogger(logger);

                System.Diagnostics.Trace.Write(String.Format("Compiling project (Build log {0})...", logPath), "information");

                // Compile
                if (engine.BuildProject(project))
                    System.Diagnostics.Trace.WriteLine("Success!", "information");
                else
                {
                    System.Diagnostics.Trace.WriteLine("Fail", "information");
                    throw new InvalidOperationException("Failed compilation, operation cannot continue");

                }
                engine.UnregisterAllLoggers();
                
            }
            #endregion

            #region Windows Phone

            if (makeWP7Proj)
开发者ID:oneminot,项目名称:everest,代码行数:67,代码来源:RimbaCsRenderer.cs

示例13: UpdateCache

        /// <summary>
        /// Attempt to save a new, updated solution cache file.
        /// </summary>
        private static void UpdateCache(Engine parentEngine, Project msbuildProject, string solutionProjectCache, BuildEventContext projectBuildEventContext)
        {
            if (!IsSolutionCacheEnabled())
            {
                return;
            }

            try
            {
                msbuildProject.Save(solutionProjectCache);
            }
            catch (Exception ex)
            {
                if (ExceptionHandling.IsCriticalException(ex))
                    throw;
                // Eat any regular exceptions: we'll just not use the cache
                parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheWriteError", solutionProjectCache, ex.Message);
            }
        }
开发者ID:nikson,项目名称:msbuild,代码行数:22,代码来源:SolutionWrapperProject.cs

示例14: Build


//.........这里部分代码省略.........
                    File.Copy(templateFolder + @"..\SharedContent\" + languageFile, workingFolder + "StopWordList.txt");
                    File.SetAttributes(workingFolder + "StopWordList.txt", FileAttributes.Normal);

                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                // Generate the API filter used by MRefBuilder
                this.GenerateApiFilter();

                // Generate the reflection information
                this.ReportProgress(BuildStep.GenerateReflectionInfo, "Generating reflection information...");

                reflectionFile = workingFolder + "reflection.org";

                if(!this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
                {
                    this.TransformTemplate("MRefBuilder.config", templateFolder, workingFolder);
                    scriptFile = this.TransformTemplate("GenerateRefInfo.proj", templateFolder, workingFolder);

                    msBuildProject = new Project(Engine.GlobalEngine);
                    msBuildProject.Load(scriptFile);

                    // Add the references
                    foreach(BuildItem item in referenceDictionary.Values)
                    {
                        buildItem = msBuildProject.AddNewItem(item.Name, item.Include);
                        item.CopyCustomMetadataTo(buildItem);
                    }

                    // Add the assemblies to document
                    foreach(string assemblyName in assembliesList)
                        buildItem = msBuildProject.AddNewItem("Assembly", assemblyName);

                    msBuildProject.Save(scriptFile);

                    this.ExecutePlugIns(ExecutionBehaviors.Before);
                    this.RunProcess(msBuildExePath, "/nologo /clp:NoSummary /v:m GenerateRefInfo.proj");
                    this.ExecutePlugIns(ExecutionBehaviors.After);
                }

                reflectionInfo = new XmlDocument();
                reflectionInfo.Load(reflectionFile);
                apisNode = reflectionInfo.SelectSingleNode("reflection/apis");

                // Generate namespace summary information
                this.GenerateNamespaceSummaries();

                // Remove unwanted items from the reflection information file
                this.ApplyVisibilityProperties();

                // If there is nothing to document, stop the build
                if(apisNode.ChildNodes.Count == 0)
                    throw new BuilderException("BE0033", "No APIs found to " +
                        "document.  See error topic in help file for details.");

                reflectionInfo = null;
                apisNode = null;

                // If this was a partial build used to obtain API information,
                // stop now.
                if(isPartialBuild)
                {
                    commentsFiles.Save();
                    goto AllDone;       // Yeah, I know it's evil but it's quick
                }
开发者ID:codemonster234,项目名称:scbuilder,代码行数:66,代码来源:BuildProcess.cs

示例15: GenerateVCWrapperProject

        /// <summary>
        /// This method generates an XmlDocument representing an MSBuild project wrapper for a VC project
        /// </summary>
        /// <owner>LukaszG</owner>
        static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion)
        {
            string projectPath = Path.GetFullPath(vcProjectFilename);
            Project msbuildProject = null;

            try
            {
                msbuildProject = new Project(parentEngine, toolsVersion);
            }
            catch (InvalidOperationException)
            {
                BuildEventFileInfo fileInfo = new BuildEventFileInfo(projectPath);
                string errorCode;
                string helpKeyword;
                string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", toolsVersion);
                throw new InvalidProjectFileException(projectPath, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword);
            }

            msbuildProject.IsLoadedByHost = false;
            msbuildProject.DefaultTargets = "Build";

            string wrapperProjectToolsVersion = SolutionWrapperProject.DetermineWrapperProjectToolsVersion(toolsVersion);
            msbuildProject.DefaultToolsVersion = wrapperProjectToolsVersion;

            BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' == '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)");

            propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)|$(Platform)");

            // only use PlatformName if we only have the platform part
            propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
            propertyGroup.Condition = " ('$(Configuration)' == '') and ('$(Platform)' != '') ";
            propertyGroup.AddNewProperty("PlatformName", "$(Platform)");

            AddVCBuildTarget(msbuildProject, projectPath, "Build", null);
            AddVCBuildTarget(msbuildProject, projectPath, "Clean", "Clean");
            AddVCBuildTarget(msbuildProject, projectPath, "Rebuild", "Rebuild");
            AddVCBuildTarget(msbuildProject, projectPath, "Publish", "Publish");

            // Special environment variable to allow people to see the in-memory MSBuild project generated
            // to represent the VC project.
            if (Environment.GetEnvironmentVariable("MSBuildEmitSolution") != null)
            {
                msbuildProject.Save(vcProjectFilename + ".proj");
            }

            return msbuildProject.XmlDocument;
        }
开发者ID:nikson,项目名称:msbuild,代码行数:55,代码来源:VCWrapperProject.cs


注:本文中的Microsoft.Build.BuildEngine.Project.Save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。