本文整理汇总了C#中Microsoft.Build.Evaluation.Project.Save方法的典型用法代码示例。如果您正苦于以下问题:C# Project.Save方法的具体用法?C# Project.Save怎么用?C# Project.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Build.Evaluation.Project
的用法示例。
在下文中一共展示了Project.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Execute
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;
}
示例2: BuildProject
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;
}
}
示例3: generate
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);
}
示例4: IncludeFileInCurrentProject
public static void IncludeFileInCurrentProject(string approved)
{
var p = new Project(GetCurrentProjectFile(approved));
if (!p.Items.Any(i => approved.EndsWith(i.UnevaluatedInclude)))
{
p.AddItem("Content", approved);
p.Save();
}
}
示例5: addPostBuildEvent
private static void addPostBuildEvent(string path)
{
Project project = new Project(path);
project.SetProperty("PostBuildEvent",
string.Format(
@"""{0}"" "" $(TargetDir) "" "" $(TargetName) "" "" $(SolutionDir) """,
Process.GetCurrentProcess().MainModule.FileName));
project.Save();
}
示例6: UpdateCsprojFile
private static void UpdateCsprojFile(string fullPath, Project csproj)
{
try
{
var fileName = Path.GetFileName(fullPath);
File.Delete(fullPath);
csproj.Save(fileName);
File.Move(csproj.FullPath, fullPath);
}
catch (IOException)
{
LogService.WriteError("Erro ao atualizar o arquivo " + fullPath);
}
}
示例7: Save
public MSBuild.Project Save(MSBuild.ProjectCollection collection, string location) {
location = Path.Combine(location, _name);
Directory.CreateDirectory(location);
var project = new MSBuild.Project(collection);
string projectFile = Path.Combine(location, _name) + ProjectType.ProjectExtension;
if (_isUserProject) {
projectFile += ".user";
}
project.Save(projectFile);
if (ProjectType != ProjectType.Generic) {
var projGuid = Guid;
project.SetProperty("ProjectTypeGuid", TypeGuid.ToString());
project.SetProperty("Name", _name);
project.SetProperty("ProjectGuid", projGuid.ToString("B"));
project.SetProperty("SchemaVersion", "2.0");
var group = project.Xml.AddPropertyGroup();
group.Condition = " '$(Configuration)' == 'Debug' ";
group.AddProperty("DebugSymbols", "true");
group = project.Xml.AddPropertyGroup();
group.Condition = " '$(Configuration)' == 'Release' ";
group.AddProperty("DebugSymbols", "false");
}
foreach (var processor in ProjectType.Processors) {
processor.PreProcess(project);
}
foreach (var item in Items) {
item.Generate(ProjectType, project);
}
foreach (var processor in ProjectType.Processors) {
processor.PostProcess(project);
}
project.Save();
return project;
}
示例8: UpdateTargetsInternal
private List<IPackage> UpdateTargetsInternal()
{
var projectCollection = new ProjectCollection();
var project = new Project(projectCollection);
var commonPropertyGroup = project.Xml.AddPropertyGroup();
var target = project.Xml.AddTarget("CheckPackages");
project.Xml.InitialTargets = "CheckPackages";
var packages = GetRootPackagesInDependencyOrder();
foreach (var package in packages)
{
if (package.Tags != null && package.Tags.Contains("internal"))
{
continue; // We don't want to polute the Common.targets file with internal packages
}
var packageVar = GetPackageVersionVariable(package.Id);
var packageTarget = String.Format(@"$(MSBuildThisFileDirectory)..\{0}\{1}.{2}\Targets\{1}.targets", RepositoryPath, package.Id, "$(" + packageVar + ")");
// Add import
// <Import Project="..\Packages\Paradox$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets" Condition="Exists('..\Packages\Paradox.$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets')" />
var importElement = project.Xml.AddImport(packageTarget);
importElement.Condition = String.Format(@"Exists('{0}')", packageTarget);
// Add common properties
var packageVarSaved = packageVar + "Saved";
var packageVarInvalid = packageVar + "Invalid";
var packageVarRevision = packageVar + "Revision";
// <SiliconStudioPackageParadoxVersionSaved>$(SiliconStudioPackageParadoxVersion)</SiliconStudioPackageParadoxVersionSaved>
commonPropertyGroup.AddProperty(packageVarSaved, "$(" + packageVar + ")");
// List all the correspondances: Major.minor -> latest installed explicit version
// Get all the related versions of the same package also installed, and order by Major.Minor
var allMajorVersions = LocalRepository.FindPackagesById(package.Id).GroupBy(p => p.Version.Version.Major, p => p);
foreach (var major in allMajorVersions)
{
var majorVersion = major.Key;
var minorPkg = major.GroupBy(p => p.Version.Version.Minor, p => p);
foreach (var minor in minorPkg)
{
var latestPackage = minor.First();
// <SiliconStudioPackageParadoxVersionRevision Condition="'$(SiliconStudioPackageParadoxVersion)' == '0.5'">0.5.0-alpha09</SiliconStudioPackageParadoxVersionRevision>
var revisionVersionProperty = commonPropertyGroup.AddProperty(packageVarRevision, latestPackage.Version.ToString());
revisionVersionProperty.Condition = "'$(" + packageVar + ")' == '" + majorVersion + "." + minor.Key + "'";
}
}
// Replace the version Major.minor by the full revision name
// <SiliconStudioPackageParadoxVersion>$(SiliconStudioPackageParadoxVersionRevision)</SiliconStudioPackageParadoxVersion>
commonPropertyGroup.AddProperty(packageVar, "$(" + packageVarRevision + ")");
// <SiliconStudioPackageParadoxVersionInvalid Condition="'$(SiliconStudioPackageParadoxVersion)' == '' or !Exists('..\Packages\Paradox.$(SiliconStudioPackageParadoxVersion)\Targets\Paradox.targets')">true</SiliconStudioPackageParadoxVersionInvalid>
commonPropertyGroup.AddProperty(packageVarInvalid, "true").Condition = "'$(" + packageVar + ")' == '' or !" + importElement.Condition;
// <SiliconStudioPackageParadoxVersion Condition="'$(SiliconStudioPackageParadoxVersionInvalid)' == 'true'">1.0.0-alpha01</SiliconStudioPackageParadoxVersion>
// Special case: if major version 1.0 still exists, use it as default (new projects should be created with props file)
var defaultPackageVersion = LocalRepository.FindPackagesById(package.Id).Select(x => x.Version).FirstOrDefault(x => x.Version.Major == 1 && x.Version.Minor == 0) ?? package.Version;
var invalidProperty = commonPropertyGroup.AddProperty(packageVar, defaultPackageVersion.ToString());
invalidProperty.Condition = "'$(" + packageVarInvalid + ")' == 'true'";
// Add in CheckPackages target
// <Warning Condition="$(SiliconStudioPackageParadoxVersionInvalid) == 'true'" Text="Package Paradox $(SiliconStudioPackageParadoxVersionSaved) not found. Use version $(SiliconStudioPackageParadoxVersion) instead"/>
// Disable Warning and use only Message for now
// TODO: Provide a better diagnostic message (in case the version is really not found or rerouted to a newer version)
var warningTask = target.AddTask("Message");
warningTask.Condition = invalidProperty.Condition;
warningTask.SetParameter("Text", String.Format("Package {0} with version [$({1})] not found. Use version $({2}) instead", package.Id, packageVarSaved, packageVar));
}
var targetFile = Path.Combine(RootDirectory, DefaultTargets);
if (File.Exists(targetFile))
{
File.Delete(targetFile);
}
project.Save(targetFile);
return packages;
}
示例9: AssertWhiteSpacePreservation
private void AssertWhiteSpacePreservation(string projectContents, string updatedProject,
Action<ProjectRootElement, Project> act)
{
var projectElement =
ProjectRootElement.Create(
XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))),
ProjectCollection.GlobalProjectCollection,
true);
var project = new Project(projectElement);
act(projectElement, project);
var writer = new StringWriter();
project.Save(writer);
var expected = @"<?xml version=""1.0"" encoding=""utf-16""?>" +
ObjectModelHelpers.CleanupFileContents(updatedProject);
var actual = writer.ToString();
VerifyAssertLineByLine(expected, actual);
}
示例10: TransformsUseCorrectDirectory_Basic
public void TransformsUseCorrectDirectory_Basic()
{
string file = null;
string projectFileContent = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<ItemGroup>
<IntermediateAssembly Include='obj\i386\foo.dll'/>
<BuiltProjectOutputGroupKeyOutput Include=""@(IntermediateAssembly->'%(FullPath)')""/>
</ItemGroup>
</Project>");
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)));
Project project = new Project(xml);
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
project.Save(file);
project.ReevaluateIfNecessary();
Assert.Equal(Path.Combine(Path.GetTempPath(), @"obj\i386\foo.dll"), project.GetItems("BuiltProjectOutputGroupKeyOutput").First().EvaluatedInclude);
}
finally
{
File.Delete(file);
}
}
示例11: DoubleImportIndirectIgnored
public void DoubleImportIndirectIgnored()
{
string file = null;
string file2 = null;
string file3 = null;
try
{
ProjectCollection collection = new ProjectCollection();
MockLogger logger = new MockLogger();
collection.RegisterLogger(logger);
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
file3 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
Project project = new Project(collection);
project.Xml.AddImport(file2);
project.Xml.AddImport(file3);
project.Save(file);
Project project2 = new Project(collection);
project.Xml.AddImport(file3);
project2.Save(file2);
Project project3 = new Project(collection);
project3.Save(file3);
project.ReevaluateIfNecessary();
logger.AssertLogContains("MSB4011"); // duplicate import
}
finally
{
File.Delete(file);
File.Delete(file2);
File.Delete(file3);
}
}
示例12: ImportSelfIgnored
public void ImportSelfIgnored()
{
string file = null;
try
{
ProjectCollection collection = new ProjectCollection();
MockLogger logger = new MockLogger();
collection.RegisterLogger(logger);
Project project = new Project(collection);
project.Xml.AddImport("$(MSBuildProjectFullPath)");
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
project.Save(file);
project.ReevaluateIfNecessary();
logger.AssertLogContains("MSB4210"); // selfimport
}
finally
{
File.Delete(file);
}
}
示例13: Build
//.........这里部分代码省略.........
{
msBuildProject = new Project(scriptFile);
// Add the references
foreach(var r in referenceDictionary.Values)
{
projectItem = msBuildProject.AddItem(r.Item1, r.Item2, r.Item3)[0];
// Make sure hint paths are correct by adding the project folder to any relative
// paths. Skip any containing MSBuild variable references.
if(projectItem.HasMetadata(BuildItemMetadata.HintPath))
{
hintPath = projectItem.GetMetadataValue(BuildItemMetadata.HintPath);
if(!Path.IsPathRooted(hintPath) && hintPath.IndexOf("$(",
StringComparison.Ordinal) == -1)
{
hintPath = FilePath.GetFullPath(Path.Combine(projectFolder, hintPath));
// If the full path length would exceed the system maximums, make it relative
// to keep it under the maximum lengths.
if(hintPath.Length > 259 || Path.GetDirectoryName(hintPath).Length > 247)
hintPath = FolderPath.AbsoluteToRelativePath(workingFolder, hintPath);
projectItem.SetMetadataValue(BuildItemMetadata.HintPath, hintPath);
}
}
}
// Add the assemblies to document
foreach(string assemblyName in assembliesList)
msBuildProject.AddItem("Assembly", assemblyName);
msBuildProject.Save(scriptFile);
}
finally
{
// If we loaded it, we must unload it. If not, it is cached and may cause problems later.
if(msBuildProject != null)
{
ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject);
ProjectCollection.GlobalProjectCollection.UnloadProject(msBuildProject.Xml);
}
}
this.ExecutePlugIns(ExecutionBehaviors.Before);
// Silverlight build targets are only available for 32-bit builds regardless of the framework
// version and require the 32-bit version of MSBuild in order to load the target file correctly.
if(project.FrameworkVersion.StartsWith("Silverlight", StringComparison.OrdinalIgnoreCase))
taskRunner.Run32BitProject("GenerateRefInfo.proj", false);
else
taskRunner.RunProject("GenerateRefInfo.proj", false);
this.ExecutePlugIns(ExecutionBehaviors.After);
}
// If this was a partial build used to obtain API information, stop now
if(this.PartialBuildType == PartialBuildType.GenerateReflectionInfo)
{
commentsFiles.Save();
goto AllDone; // Yeah, I know it's evil but it's quick
}
// Transform the reflection output based on the document model and create the topic manifest
this.ReportProgress(BuildStep.TransformReflectionInfo, "Transforming reflection output...");
示例14: SaveProcessorProj
internal void SaveProcessorProj(Processor proc)
{
if (!string.IsNullOrEmpty(proc.ProjectPath))
{
try
{
string fullpath = ExpandEnvVars(proc.ProjectPath, "");
Project proj = LoadProject(fullpath);
proj.ProjectCollection.UnloadProject(proj);
proj = new Project();
proj.Xml.DefaultTargets = "Build";
Dictionary<string, string> tbl = new Dictionary<string, string>();
tbl["PlatformFamily"] = "PLATFORM_FAMILY";
ProjectPropertyGroupElement bpg = SaveStringProps(proj, proc, tbl);
if (!string.IsNullOrEmpty(proc.DefaultISA))
{
ProjectPropertyElement bp = bpg.AddProperty("INSTRUCTION_SET", proc.DefaultISA);
bp.Condition = "'$(INSTRUCTION_SET)'==''";
}
foreach (MFProperty prop in proc.Properties)
{
ProjectPropertyElement bp = bpg.AddProperty(prop.Name, prop.Value);
bp.Condition = prop.Condition;
}
bpg.AddProperty("TARGETPROCESSOR", proc.Name);
bpg.AddProperty("TARGETCODEBASE", proc.Name);
bpg.AddProperty("TARGETCODEBASETYPE", "Native");
SaveBuildToolRef(proc.BuildToolOptions, proj);
ProjectItemGroupElement big = proj.Xml.AddItemGroup();
big.AddItem("IncludePaths", RemoveSpoClient(Path.GetDirectoryName(proc.ProjectPath)));
//ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();
//bpg.AddProperty("PKUI_Processor", SerializeXml(proc));
proj.Save(fullpath);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: Unable to save procesor file " + proc.ProjectPath + "\r\n" + e.Message);
}
}
}
示例15: CreateSolutionDirProj
internal void CreateSolutionDirProj(MFSolution solution)
{
string solutionDir = @"$(SPOCLIENT)\Solutions\" + solution.Name;
string fullpath = ExpandEnvVars(Path.Combine(solutionDir, "dotnetmf.proj"), "");
Project proj = LoadProject(fullpath);
proj.ProjectCollection.UnloadProject(proj);
proj = new Project();
proj.Xml.DefaultTargets = "Build";
try
{
ProjectPropertyGroupElement bpg = proj.Xml.AddPropertyGroup();
bpg.AddProperty("Directory", RemoveSpoClient(solutionDir));
bpg.AddProperty("MFSettingsFile", Path.Combine(solutionDir, solution.Name + ".settings"));
ProjectItemGroupElement big = proj.Xml.AddItemGroup();
foreach (MFProject mfproj in solution.Projects)
{
if (!string.IsNullOrEmpty(mfproj.Directory) && !string.IsNullOrEmpty(mfproj.ProjectPath))
{
ProjectItemElement bi = big.AddItem("RequiredProjects", Path.Combine(Path.GetFileName(mfproj.Directory), Path.GetFileName(mfproj.ProjectPath)));
}
}
proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Settings");
proj.Xml.AddImport(@"$(SPOCLIENT)\tools\targets\Microsoft.SPOT.System.Targets");
proj.Save(fullpath);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: loading LibCat file: " + fullpath + "\r\n", e.Message);
}
}