internal BuildItemGroup (XmlElement xmlElement, Project project, ImportedProject importedProject, bool readOnly, bool dynamic) { this.buildItems = new List <BuildItem> (); this.importedProject = importedProject; this.itemGroupElement = xmlElement; this.parentProject = project; this.read_only = readOnly; this.isDynamic = dynamic; if (!FromXml) return; foreach (XmlNode xn in xmlElement.ChildNodes) { if (!(xn is XmlElement)) continue; XmlElement xe = (XmlElement) xn; BuildItem bi = CreateItem (project, xe); buildItems.Add (bi); project.LastItemGroupContaining [bi.Name] = this; } DefinedInFileName = importedProject != null ? importedProject.FullFileName : project != null ? project.FullFileName : null; }
/// <summary> /// Searches our tables for a project with same full path, tools version, and global property settings /// Removes particular project from the project manager. /// </summary> /// <param name="project"></param> internal void RemoveProject ( Project project ) { // We should never be asked to remove null project ErrorUtilities.VerifyThrow(project != null, "Shouldn't ask to remove null projects"); // See if there's an entry in our table for this particular full path. ArrayList projectsWithThisFullPath = (ArrayList)this.projects[project.FullFileName]; // The project should be in the table ErrorUtilities.VerifyThrow(projectsWithThisFullPath != null, "Project missing from the list"); int project_index = -1; for (int i = 0; i < projectsWithThisFullPath.Count; i++) { if (projectsWithThisFullPath[i] == project) { project_index = i; } } // The project should be in the table ErrorUtilities.VerifyThrow(project_index != -1, "Project missing from the list"); if (project_index != -1) { projectsWithThisFullPath.RemoveAt(project_index); AddUnloadedProjectRecord(project.FullFileName, project.GlobalProperties, project.ToolsVersion); } }
/// <summary> /// Adds the specified Project object to our data structure, if it's not already present. /// </summary> /// <param name="project"></param> internal void AddProject(Project project) { // We should never be asked to store a nameless project in our list. ErrorUtilities.VerifyThrow(project.FullFileName.Length > 0, "Can't store nameless projects"); AddProject(projects, project); }
/// <summary> /// Returns a list of build actions available for the specified <paramref name="projectItem"/>. /// </summary> /// <param name="projectItem"> /// A <see cref="ProjectItem"/> object. /// </param> /// <returns> /// A list where each item contains a name of available build action. /// </returns> private static ICollection <string> GetAvailableBuildActions(ProjectItem projectItem) { #pragma warning disable 618 // Microsoft.Build.Engine.Project is obsolete in .NET 4.0. // Code in this method will need to be rewritten when we drop support for DEV9. MSBuild.Project buildProject = new MSBuild.Project(); #pragma warning restore 618 buildProject.LoadXml(File.ReadAllText(GetPath(projectItem.ContainingProject))); List <string> buildActions = new List <string> { "None", "Compile", "Content", "EmbeddedResource" }; foreach (MSBuild.BuildItemGroup itemGroup in buildProject.ItemGroups) { foreach (MSBuild.BuildItem buildItem in itemGroup) { if (buildItem.Name == "AvailableItemName") { buildActions.Add(buildItem.Include); } } } return(buildActions); }
Microsoft.Build.BuildEngine.Project GetMSBuildProject(NPanday.ProjectImporter.Parser.SlnParser.Model.Solution solution, string projectGuid) { foreach (NPanday.ProjectImporter.Parser.SlnParser.Model.Project p in solution.Projects) { if (p.ProjectGUID.Equals("{" + projectGuid + "}", StringComparison.OrdinalIgnoreCase)) { string projectReferenceName = p.ProjectName; string projectReferencePath = p.ProjectPath; string projectReferenceFullPath = null; if (Path.IsPathRooted(projectReferencePath)) { projectReferenceFullPath = Path.GetFullPath(projectReferencePath); } else { projectReferenceFullPath = Path.Combine(solution.File.Directory.FullName, projectReferencePath); } Microsoft.Build.BuildEngine.Project prj = new Microsoft.Build.BuildEngine.Project(BUILD_ENGINE); prj.Load(projectReferenceFullPath); return(prj); } } return(null); }
public void TestFromXml2 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='Target' Condition='false' DependsOnTargets='X' > </Target> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); Target[] t = new Target [1]; project.Targets.CopyTo (t, 0); Assert.AreEqual ("false", t [0].Condition, "A1"); Assert.AreEqual ("X", t [0].DependsOnTargets, "A2"); t [0].Condition = "true"; t [0].DependsOnTargets = "A;B"; Assert.AreEqual ("true", t [0].Condition, "A3"); Assert.AreEqual ("A;B", t [0].DependsOnTargets, "A4"); }
/// <summary> /// Creates an instance of the MSBuildManager. As a part of instance creation moves back project items /// positions of which were adjusted when the project file was saved /// </summary> /// <param name="projectFile">the name of the project file</param> /// <remarks> /// When the compilation order is modified through the properties dialog, such modifications are /// reflected by changing the order of project elements (BuildItem objects) in the project file. /// In certain situations such changes can cause the FSharp base project system to refuse to load the project. /// To prevent this from happening MSBuildManager adjusts the positions of offending elements when saving the project /// <see cref="M:FixupProject"/> method. After the FSharp base project system is done loading the project these /// elements are moevd back to their original positions /// </remarks> public MSBuildManager(BuildProject project) { this.project = project; var item_list = new List <BuildElement>(); var fixup_list = new List <Tuple <BuildElement, int, int> >(); foreach (var item in GetElements( n => n.Name == "Compile" || n.Name == "Content" || n.Name == "None" )) { item_list.Add(item); int offset; if (int.TryParse(item.BuildItem.GetMetadata(moveByTag), out offset)) { fixup_list.Insert(0, new Tuple <BuildElement, int, int>(item, offset, item_list.Count - 1)); } } foreach (var item in fixup_list) { for (int i = 1; i <= item.MoveBy; i++) { item.Element.SwapWith(item_list[item.Index + i]); } item_list.Remove(item.Element); item_list.Insert(item.Index + item.MoveBy, item.Element); } }
public virtual IDisposable Load(Project project, string file) { var backup = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(Path.GetDirectoryName(Path.GetFullPath(file))); project.Load(Path.GetFileName(file)); return Disposable.Create(() => Directory.SetCurrentDirectory(backup)); }
internal Target (XmlElement targetElement, Project project, ImportedProject importedProject) { if (project == null) throw new ArgumentNullException ("project"); if (targetElement == null) throw new ArgumentNullException ("targetElement"); this.targetElement = targetElement; this.name = targetElement.GetAttribute ("Name"); this.project = project; this.engine = project.ParentEngine; this.importedProject = importedProject; this.onErrorElements = new List <XmlElement> (); this.buildState = BuildState.NotStarted; this.buildTasks = new List <BuildTask> (); this.batchingImpl = new TargetBatchingImpl (project, this.targetElement); bool onErrorFound = false; foreach (XmlNode xn in targetElement.ChildNodes) { if (xn is XmlElement) { XmlElement xe = (XmlElement) xn; if (xe.Name == "OnError") { onErrorElements.Add (xe); onErrorFound = true; } else if (onErrorFound) throw new InvalidProjectFileException ( "The element <OnError> must be last under element <Target>. Found element <Error> instead."); else buildTasks.Add (new BuildTask (xe, this)); } } }
public BuildChoose (XmlElement xmlElement, Project project) { this.xmlElement = xmlElement; this.project = project; this.whens = new List <BuildWhen> (); foreach (XmlNode xn in xmlElement.ChildNodes) { if (!(xn is XmlElement)) continue; XmlElement xe = (XmlElement)xn; if (xe.Name == "When") { if (otherwise != null) throw new InvalidProjectFileException ("The 'Otherwise' element must be last in a 'Choose' element."); if (xe.Attributes.GetNamedItem ("Condition") == null) throw new InvalidProjectFileException ("The 'When' element requires a 'Condition' attribute."); BuildWhen bw = new BuildWhen (xe, project); whens.Add (bw); } else if (xe.Name == "Otherwise") { if (this.whens.Count == 0) throw new InvalidProjectFileException ("At least one 'When' element must occur in a 'Choose' element."); otherwise = new BuildWhen (xe, project); } } }
public XnaContentProject(Task task, string msBuildPath, string xnaInstallPath) { m_engine = new Engine(msBuildPath); m_engine.RegisterLogger(new XnaContentLogger(task)); m_project = new Project(m_engine); m_project.AddNewUsingTaskFromAssemblyName("BuildContent", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d"); m_project.AddNewUsingTaskFromAssemblyName("BuildXact", "Microsoft.Xna.Framework.Content.Pipeline, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d"); // Add our Content Pipeline Assemblies m_pipelineGroup = m_project.AddNewItemGroup(); m_contentGroup = m_project.AddNewItemGroup(); m_contentTarget = m_project.Targets.AddNewTarget("_BuildXNAContentLists"); // Add our Build target m_xnaTarget = m_project.Targets.AddNewTarget("Build"); m_xnaTarget.DependsOnTargets = "_BuildXNAContentLists"; // Add Default Pipeline Assemblies. AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll"); AddPilepineAssembly(xnaInstallPath + "Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll"); }
public ProjectInfo(Project project) { _project = project; _properties = new ProjectPropertyList(_project); _references = new ReferenceList(_project); _dependencies = new List<string>(); }
public void SimpleAddAndRetrieveProject() { // Initialize engine. Engine engine = new Engine(@"c:\"); // Instantiate new project manager. ProjectManager projectManager = new ProjectManager(); // Set up variables that represent the information we would be getting from // the "MSBuild" task. string fullPath = @"c:\rajeev\temp\myapp.proj"; BuildPropertyGroup globalProperties = new BuildPropertyGroup(); globalProperties.SetProperty("Configuration", "Debug"); // Create a new project that matches the information that we're pretending // to receive from the MSBuild task. Project project1 = new Project(engine); project1.FullFileName = fullPath; project1.GlobalProperties = globalProperties; // Add the new project to the ProjectManager. projectManager.AddProject(project1); // Try and retrieve the project from the ProjectManager based on the fullpath + globalprops, // and make sure we get back the same project we added. Assertion.AssertEquals(project1, projectManager.GetProject(fullPath, globalProperties, null)); }
public void GetAssemblyNameScalarThatIsNotSet() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("TaskName", @"$(assemblyName)"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"$(assemblyName)", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); }
internal BuildPropertyGroup (XmlElement xmlElement, Project project, ImportedProject importedProject, bool readOnly, bool isDynamic) { this.importedProject = importedProject; this.parentCollection = null; this.parentProject = project; this.propertyGroup = xmlElement; this.read_only = readOnly; this.isDynamic = isDynamic; if (FromXml) { this.properties = new List <BuildProperty> (); foreach (XmlNode xn in propertyGroup.ChildNodes) { if (!(xn is XmlElement)) continue; XmlElement xe = (XmlElement) xn; BuildProperty bp = new BuildProperty (parentProject, xe); AddProperty (bp); } } else this.propertiesByName = new Dictionary <string, BuildProperty> (StringComparer.OrdinalIgnoreCase); DefinedInFileName = importedProject != null ? importedProject.FullFileName : (project != null ? project.FullFileName : null); }
public override bool Execute() { bool result = true; string file = Path.Combine(m_stubsPath, m_name + ".featureproj"); try { Project proj = new Project(); proj.DefaultToolsVersion = "3.5"; proj.DefaultTargets = "Build"; BuildPropertyGroup bpg = proj.AddNewPropertyGroup(true); bpg.AddNewProperty("FeatureName", m_name); bpg.AddNewProperty("Guid", System.Guid.NewGuid().ToString("B")); bpg.AddNewProperty("Description", ""); bpg.AddNewProperty("Groups", ""); BuildItemGroup big = proj.AddNewItemGroup(); big.AddNewItem("InteropFeature", Path.GetFileNameWithoutExtension(m_assemblyName).Replace('.', '_')); big.AddNewItem("DriverLibs", Path.GetFileNameWithoutExtension( m_assemblyName ).Replace( '.', '_' ) + ".$(LIB_EXT)"); big.AddNewItem("MMP_DAT_CreateDatabase", "$(BUILD_TREE_CLIENT)\\pe\\" + m_assemblyName); big.AddNewItem("RequiredProjects", Path.Combine(m_stubsPath, m_nativeProjectFile)); proj.Save(file); } catch(Exception e) { Log.LogError("Error trying to create feature project file \"" + file + "\": " + e.Message); result = false; } return result; }
public static SpecFlowProject LoadSpecFlowProjectFromMsBuild(string projectFile) { projectFile = Path.GetFullPath(projectFile); Project project = new Project(); project.Load(projectFile, ProjectLoadSettings.IgnoreMissingImports); string projectFolder = Path.GetDirectoryName(projectFile); SpecFlowProject specFlowProject = new SpecFlowProject(); specFlowProject.ProjectFolder = projectFolder; specFlowProject.ProjectName = Path.GetFileNameWithoutExtension(projectFile); specFlowProject.AssemblyName = project.GetEvaluatedProperty("AssemblyName"); specFlowProject.DefaultNamespace = project.GetEvaluatedProperty("RootNamespace"); var items = project.GetEvaluatedItemsByName("None").Cast<BuildItem>() .Concat(project.GetEvaluatedItemsByName("Content").Cast<BuildItem>()); foreach (BuildItem item in items) { var extension = Path.GetExtension(item.FinalItemSpec); if (extension.Equals(".feature", StringComparison.InvariantCultureIgnoreCase)) { var featureFile = new SpecFlowFeatureFile(item.FinalItemSpec); var ns = item.GetEvaluatedMetadata("CustomToolNamespace"); if (!String.IsNullOrEmpty(ns)) featureFile.CustomNamespace = ns; specFlowProject.FeatureFiles.Add(featureFile); } if (Path.GetFileName(item.FinalItemSpec).Equals("app.config", StringComparison.InvariantCultureIgnoreCase)) { GeneratorConfigurationReader.UpdateConfigFromFile(specFlowProject.GeneratorConfiguration, Path.Combine(projectFolder, item.FinalItemSpec)); } } return specFlowProject; }
public void SetUp() { // Whole bunch of setup code. XmlElement taskNode = new XmlDocument().CreateElement("MockTask"); LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null)); Engine engine = new Engine(@"c:\"); loggingHelper = new EngineLoggingServicesHelper(); engine.LoggingServices = loggingHelper; Project project = new Project(engine); taskExecutionModule = new MockTaskExecutionModule(new EngineCallback(engine)); // Set up some "fake data" which will be passed to the Task Execution State object Hashtable[] fakeArray = new Hashtable[1]; fakeArray[0] = new Hashtable(); projectLevelProprtiesForInference = new BuildPropertyGroup(); projectLevelPropertiesForExecution = new BuildPropertyGroup(); inferenceBucketItemsByName = fakeArray; inferenceBucketMetaData = fakeArray; projectLevelItemsForInference = new Hashtable(); executionBucketItemsByName = fakeArray; executionBucketMetaData = fakeArray; projectLevelItemsForExecution = new Hashtable(); hostObject = null; projectFileOfTaskNode = "In Memory"; parentProjectFullFileName = project.FullFileName; nodeProxyId = engine.EngineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId)); executionDirectory = Directory.GetCurrentDirectory(); projectId = project.Id; }
protected BatchingImplBase (Project project) { if (project == null) throw new ArgumentNullException ("project"); this.project = project; }
public void Setup() { ccu = new CodeCompileUnit(); mocks = new MockRepository(); engine = Engine.GlobalEngine; engine.BinPath = @"C:\Program Files (x86)\MSBuild"; project = new Project(); buildEngine = mocks.DynamicMock<MockBuildEngine>(project); logger = new NullLogger(); parserService = mocks.DynamicMock<ISiteTreeGeneratorService>(); naming = mocks.DynamicMock<INamingService>(); sourceStorage = mocks.DynamicMock<IParsedSourceStorageService>(); source = mocks.DynamicMock<ISourceGenerator>(); typeResolver = mocks.DynamicMock<ITypeResolver>(); treeService = mocks.DynamicMock<ITreeCreationService>(); viewSourceMapper = mocks.DynamicMock<IViewSourceMapper>(); generator = mocks.DynamicMock<IGenerator>(); task = new GenerateMonoRailSiteTreeTask(logger, parserService, naming, source, sourceStorage, typeResolver, treeService, viewSourceMapper, generator); item = mocks.DynamicMock<ITaskItem>(); parsedSource = mocks.DynamicMock<IParser>(); }
void MsVisitProjects(VisitProject visitor) { Engine e = new Engine(RuntimeEnvironment.GetRuntimeDirectory()); if(e.GetType().Assembly.GetName().Version.Major == 2) try { e.GlobalProperties.SetProperty("MSBuildToolsPath", RuntimeEnvironment.GetRuntimeDirectory()); } catch { } foreach (FileInfo file in _projects) { Project prj = new Project(e); try { prj.Load(file.FullName); } catch (Exception ex) { Console.Error.WriteLine("Unable to open project: {0}", file); Log.Verbose(ex.ToString()); continue; } visitor(new MsBuildProject(prj)); e.UnloadProject(prj); } }
public BuildWhen (XmlElement whenElement, Project parentProject) { this.parentProject = parentProject; this.groupingCollection = new GroupingCollection (parentProject); if (whenElement == null) throw new ArgumentNullException ("whenElement"); this.whenElement = whenElement; foreach (XmlElement xe in whenElement.ChildNodes) { switch (xe.Name) { case "ItemGroup": BuildItemGroup big = new BuildItemGroup (xe, parentProject, null, true); //big.BindToXml (xe); groupingCollection.Add (big); break; case "PropertyGroup": BuildPropertyGroup bpg = new BuildPropertyGroup (xe, parentProject, null, true); //bpg.BindToXml (xe); groupingCollection.Add (bpg); break; case "Choose": BuildChoose bc = new BuildChoose (xe, parentProject); groupingCollection.Add (bc); break; default: throw new InvalidProjectFileException ( string.Format ("Invalid element '{0}' in When.", xe.Name)); } } }
public override bool BoolEvaluate (Project context) { if (left.CanEvaluateToNumber (context) && right.CanEvaluateToNumber (context)) { float l,r; l = left.NumberEvaluate (context); r = right.NumberEvaluate (context); return NumberCompare (l, r, op); } else if (left.CanEvaluateToBool (context) && right.CanEvaluateToBool (context)) { bool l,r; l = left.BoolEvaluate (context); r = right.BoolEvaluate (context); return BoolCompare (l, r, op); } else { string l,r; l = left.StringEvaluate (context); r = right.StringEvaluate (context); return StringCompare (l, r, op); } }
public void Initialize() { ObjectModelHelpers.DeleteTempProjectDirectory(); engine = new Engine(); project = new Project(engine); }
static void Parse(String file) { var obj = JObject.Parse(Console.In.ReadToEnd()); var solution = new Project(); solution.ParentEngine.RegisterLogger(new ConsoleLogger()); foreach (var prop in obj) { solution.GlobalProperties[prop.Key] = new BuildProperty(prop.Key, prop.Value.ToString()); } using (PlatformProjectHelper.Instance.Load(solution, file)) { var result = ToJson(solution); if (Path.GetExtension(file) == ".sln") { var jSolution = result; result = new JObject(); result["Solution"] = jSolution; foreach (var proj in PlatformProjectHelper.Instance.GetBuildLevelItems(solution)) { var project = solution.ParentEngine.CreateNewProject(); foreach (var meta in PlatformProjectHelper.Instance.GetEvaluatedMetadata(proj)) { project.GlobalProperties[meta.Item1] = new BuildProperty(meta.Item1, meta.Item2); } using (PlatformProjectHelper.Instance.Load(project, proj.FinalItemSpec)) { var jProject = ToJson(project); result[Path.GetFileNameWithoutExtension(proj.FinalItemSpec)] = jProject; } } } Console.WriteLine(result.ToString()); } }
public void TestAssemblyFile2 () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <UsingTask AssemblyFile='Test/resources/TestTasks.dll' TaskName='SimpleTask' /> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); IEnumerator en = project.UsingTasks.GetEnumerator (); en.MoveNext (); UsingTask ut = (UsingTask) en.Current; Assert.AreEqual ("Test/resources/TestTasks.dll", ut.AssemblyFile, "A1"); Assert.IsNull (ut.AssemblyName, "A2"); Assert.AreEqual (null, ut.Condition, "A3"); Assert.AreEqual (false, ut.IsImported, "A4"); Assert.AreEqual ("SimpleTask", ut.TaskName, "A5"); }
/// <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; }
public void TestBuildEngineAndProject() { UIThreadInvoker.Invoke((ThreadInvoker) delegate() { //Get the global service provider and the dte IServiceProvider sp = VsIdeTestHostContext.ServiceProvider; DTE dte = (DTE)sp.GetService(typeof(DTE)); string destination = Path.Combine(TestContext.TestDir, TestContext.TestName); ProjectNode project = Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true); FieldInfo fi; PropertyInfo pi; pi = typeof(ProjectNode).GetProperty("BuildEngine", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(project, Microsoft.Build.BuildEngine.Engine.GlobalEngine, new object[] { }); fi = typeof(ProjectNode).GetField("buildEngine", BindingFlags.Instance | BindingFlags.NonPublic); Assert.AreEqual <Microsoft.Build.BuildEngine.Engine>(Microsoft.Build.BuildEngine.Engine.GlobalEngine, fi.GetValue(project) as Microsoft.Build.BuildEngine.Engine); Microsoft.Build.BuildEngine.Project newBuildProject = Microsoft.Build.BuildEngine.Engine.GlobalEngine.CreateNewProject(); pi = typeof(ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(project, newBuildProject, new object[] { }); fi = typeof(ProjectNode).GetField("buildProject", BindingFlags.Instance | BindingFlags.NonPublic); Assert.AreEqual <Microsoft.Build.BuildEngine.Project>(newBuildProject, fi.GetValue(project) as Microsoft.Build.BuildEngine.Project); }); }
public void TestGetEnumerator () { string documentString = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <UsingTask AssemblyFile='Test/resources/TestTasks.dll' TaskName='TrueTestTask' /> <UsingTask AssemblyFile='Test/resources/TestTasks.dll' TaskName='FalseTestTask' /> </Project> "; engine = new Engine (Consts.BinPath); project = engine.CreateNewProject (); project.LoadXml (documentString); IEnumerator en = project.UsingTasks.GetEnumerator (); en.MoveNext (); Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A1"); Assert.AreEqual ("TrueTestTask", ((UsingTask) en.Current).TaskName, "A2"); en.MoveNext (); Assert.AreEqual ("Test/resources/TestTasks.dll", ((UsingTask) en.Current).AssemblyFile, "A3"); Assert.AreEqual ("FalseTestTask", ((UsingTask) en.Current).TaskName, "A4"); Assert.IsFalse (en.MoveNext ()); }
protected override bool CompileSingle(Engine engine, AbstractBaseGenerator gen, string workingPath, string target) { try { using (log4net.NDC.Push("Compiling " + gen.Description)) { Log.DebugFormat("Loading MsBuild Project"); var proj = new Project(engine); proj.Load(Helper.PathCombine(workingPath, gen.TargetNameSpace, gen.ProjectFileName)); Log.DebugFormat("Compiling"); if (engine.BuildProject(proj, target)) { return true; } else { Log.ErrorFormat("Failed to compile {0}", gen.Description); return false; } } } catch (Exception ex) { Log.Error("Failed compiling " + gen.Description, ex); return false; } }
public void GetAssemblyNameSpecialChars() { Project p = new Project(); p.AddNewUsingTaskFromAssemblyName("TaskName", @"%*?@$();\"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"%*?@$();\", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); }
public void Initialize() { engine = new Engine(); myProject = new Project(engine); myLogger = new MockLogger(); myProject.ParentEngine.RegisterLogger(myLogger); }
/// <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; }
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; }
public void GetAssemblyNameSpecialCharsEscaped() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("TaskName", @"%25%2a%3f%40%24%28%29%3b\"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"%25%2a%3f%40%24%28%29%3b\", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); }
/// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { project = IntPtr.Zero; canceled = 0; // Get the list of GUIDs from the project/template string guidsList = this.ProjectTypeGuids(fileName); #if !VS2005 string projectDirectory = String.IsNullOrEmpty(location) ? Path.GetDirectoryName(fileName) : location; if (!this.IsProjectLocationSecure(projectDirectory)) { canceled = 1; ErrorHandler.ThrowOnFailure(VSConstants.VS_E_WIZARDBACKBUTTONPRESS); } #endif // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if (hr == VSConstants.E_ABORT) { canceled = 1; } ErrorHandler.ThrowOnFailure(hr); // This needs to be done after the aggregation is completed (to avoid creating a non-aggregated CCW) and as a result we have to go through the interface IProjectEventsProvider eventsProvider = (IProjectEventsProvider)Marshal.GetTypedObjectForIUnknown(project, typeof(IProjectEventsProvider)); eventsProvider.ProjectEventsProvider = this.GetProjectEventsProvider(); this.buildProject = null; }
internal void BuildInternal(BuildProject project, params string[] targets) { if (project != null) { BuildProperty platform = project.GlobalProperties["Platform"]; if (platform == null) { project.GlobalProperties["Platform"] = platform = new BuildProperty("Platform", "AnyCPU"); } if (string.IsNullOrEmpty(platform.Value)) { platform.Value = "AnyCPU"; } project.ParentEngine.GlobalProperties["SolutionDir"] = solution.GlobalProperties["SolutionDir"]; BuildStarted(delegate() { outputs.Clear(); try { bool res = project.Build(targets, outputs); } catch { if (!bl.cancel) { throw; } } InvokeBuildCompleted(); }); } }
internal static void MarkProjectAsDirtyForReprocessXml(MSBuild.Project project) { typeof(MSBuild.Project).InvokeMember( "MarkProjectAsDirtyForReprocessXml", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, project, null ); }
static XmlElement BeginXmlManipulation(MSBuild.Project project) { return((XmlElement)typeof(MSBuild.Project).InvokeMember( "ProjectElement", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, project, null )); }
internal static void EnsureCorrectTempProject(MSBuild.Project baseProject, string configuration, string platform, ref MSBuild.Project tempProject) { if (configuration == null && platform == null) { // unload temp project if (tempProject != null && tempProject != baseProject) { tempProject.ParentEngine.UnloadAllProjects(); } tempProject = null; return; } if (configuration == null) { configuration = baseProject.GetEvaluatedProperty("Configuration"); } if (platform == null) { platform = baseProject.GetEvaluatedProperty("Platform"); } if (tempProject != null && tempProject.GetEvaluatedProperty("Configuration") == configuration && tempProject.GetEvaluatedProperty("Platform") == platform) { // already correct return; } if (baseProject.GetEvaluatedProperty("Configuration") == configuration && baseProject.GetEvaluatedProperty("Platform") == platform) { tempProject = baseProject; return; } // create new project // unload old temp project if (tempProject != null && tempProject != baseProject) { tempProject.ParentEngine.UnloadAllProjects(); } try { MSBuild.Engine engine = CreateEngine(); tempProject = engine.CreateNewProject(); // tell MSBuild the path so that projects containing <Import Project="relativePath" /> // can be loaded tempProject.FullFileName = baseProject.FullFileName; MSBuildBasedProject.InitializeMSBuildProject(tempProject); tempProject.LoadXml(baseProject.Xml); tempProject.SetProperty("Configuration", configuration); tempProject.SetProperty("Platform", platform); } catch (Exception ex) { ICSharpCode.Core.MessageService.ShowWarning(ex.ToString()); tempProject = baseProject; } }
/// <summary> /// Overloaded constructor. /// </summary> /// <param name="project">An instance of a build project</param> /// <exception cref="ArgumentNullException">Is thrown if the passed Project is null.</exception> internal GlobalPropertyHandler(MSBuild.Project project) { Debug.Assert(project != null, "The project parameter passed cannot be null"); this.globalProjectProperties = project.GlobalProperties; Debug.Assert(project.ParentEngine != null, "The parent engine has not been initialized"); this.globalEngineProperties = project.ParentEngine.GlobalProperties; }
protected virtual void SetMsbuildEngine(ProjectFactory factory) { FieldInfo buildEngine = typeof(ProjectFactory).GetField("buildEngine", BindingFlags.Instance | BindingFlags.NonPublic); buildEngine.SetValue(factory, Engine.GlobalEngine); Microsoft.Build.BuildEngine.Project msbuildproject = Engine.GlobalEngine.CreateNewProject(); FieldInfo buildProject = typeof(ProjectFactory).GetField("buildProject", BindingFlags.Instance | BindingFlags.NonPublic); buildProject.SetValue(factory, msbuildproject); }
private static void FindContentDirectory(Microsoft.Build.BuildEngine.Project project) { AlternativeContentDirectory = null; string projectName = FileManager.RemovePath(FileManager.RemoveExtension(mCurrentGlueFile)); string directory = FileManager.GetDirectory(FileManager.GetDirectory(mCurrentGlueFile)); string preProcessorConstants = GetPreProcessorConstantsFromProject(project); bool wasFound = false; string foundDirectory; if (preProcessorConstants.Contains("ANDROID")) { // Check for this wasFound = TryFindContentFolder(projectName, directory + projectName + "/Assets/content/", out foundDirectory); if (wasFound) { AlternativeContentDirectory = foundDirectory; } } if (!wasFound) { // Not sure why I did this, but it shouldn't have / in front of Content //string directoryToLookFor = directory + projectName + "/Content/"; // Now I know why. On some platforms (like FRB XNA PC 4.0) the // content directory is going to be c:\Project\ProjectContent\ // While on others, the Content folder is in the main project, like // c:\Project\Project\Content\ // Which it is depends on the type of project, so let's support both string directoryToLookFor = directory + projectName + "Content/"; wasFound = TryFindContentFolder(projectName, directoryToLookFor, out foundDirectory); if (wasFound) { AlternativeContentDirectory = foundDirectory; } } if (!wasFound) { string directoryToLookFor = directory + projectName + "/Content/"; wasFound = TryFindContentFolder(projectName, directoryToLookFor, out foundDirectory); if (wasFound) { AlternativeContentDirectory = foundDirectory; } } }
public override object LoadProject(MSBuildProject p, string xml, FilePath fileName) { lock (engine) { engine.GlobalProperties.Clear(); var project = new MSProject(engine); project.BuildEnabled = false; project.FullFileName = fileName; project.LoadXml(xml); return(project); } }
/// <summary> /// Evaluates the specified condition in the project and specified configuration/platform. /// WARNING: EvaluateCondition might add a temporary property group and remove it again, /// which invalidates enumerators over the list of property groups! /// </summary> internal static bool EvaluateCondition(MSBuild.Project project, string configuration, string platform, string condition, ref MSBuild.Project tempProject) { if (string.IsNullOrEmpty(condition)) { return(true); } EnsureCorrectTempProject(project, configuration, platform, ref tempProject); return(EvaluateCondition(tempProject, condition)); }
/// <summary> /// Evaluates the specified condition in the project. /// WARNING: EvaluateCondition might add a temporary property group and remove it again, /// which invalidates enumerators over the list of property groups! /// </summary> internal static bool EvaluateCondition(MSBuild.Project project, string condition) { const string propertyName = "MSBuildInternalsEvaluateConditionDummyPropertyName"; MSBuild.BuildPropertyGroup pGroup = project.AddNewPropertyGroup(true); pGroup.AddNewProperty(propertyName, "ConditionFalse"); pGroup.AddNewProperty(propertyName, "ConditionTrue").Condition = condition; bool result = project.GetEvaluatedProperty(propertyName) == "ConditionTrue"; project.RemovePropertyGroup(pGroup); return(result); }
protected void ParseProjectReferences(Dictionary <string, object> dictionary, NPanday.ProjectImporter.Parser.SlnParser.Model.Project project, NPanday.ProjectImporter.Parser.SlnParser.Model.Solution solution) { if (project.ProjectSections != null) { List <Microsoft.Build.BuildEngine.Project> projectReferenceList = new List <Microsoft.Build.BuildEngine.Project>(); foreach (ProjectSection ps in project.ProjectSections) { if ("WebsiteProperties".Equals(ps.Name)) { // ProjectReferences = "{11F2FCC8-5941-418A-A0E7-42D250BA9D21}|SampleInterProject111.dll;{9F37BA7B-06F9-4B05-925D-B5BC16322E8B}|BongClassLib.dll;" try { Regex regex = new Regex(PROJECT_REFERENCE_REGEX, RegexOptions.Multiline | RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches(ps.Map["ProjectReferences"]); foreach (Match match in matches) { string projectReferenceGUID = match.Groups["ProjectReferenceGUID"].ToString(); string projectReferenceDll = match.Groups["ProjectReferenceDll"].ToString(); Microsoft.Build.BuildEngine.Project prj = GetMSBuildProject(solution, projectReferenceGUID); if (prj != null) { projectReferenceList.Add(prj); } } } catch { } } else if ("ProjectDependencies".Equals(ps.Name)) { //{0D80BE11-F1CE-409E-B9AC-039D3801209F} = {0D80BE11-F1CE-409E-B9AC-039D3801209F} foreach (string key in ps.Map.Keys) { Microsoft.Build.BuildEngine.Project prj = GetMSBuildProject(solution, key.Replace("{", "").Replace("}", "")); if (prj != null) { projectReferenceList.Add(prj); } } } } dictionary.Add("InterProjectReferences", projectReferenceList.ToArray()); } }
public SpecFlowProject ReadSpecFlowProject(IProjectReference projectReference) { var projectFilePath = FileProjectReference.AssertFileProjectReference(projectReference).ProjectFilePath; var project = Engine.GlobalEngine.GetLoadedProject(projectFilePath); if (project == null) { project = new Microsoft.Build.BuildEngine.Project(); project.Load(projectFilePath, ProjectLoadSettings.IgnoreMissingImports); } string projectFolder = Path.GetDirectoryName(projectFilePath); SpecFlowProject specFlowProject = new SpecFlowProject(); specFlowProject.ProjectSettings.ProjectFolder = projectFolder; specFlowProject.ProjectSettings.ProjectName = Path.GetFileNameWithoutExtension(projectFilePath); specFlowProject.ProjectSettings.AssemblyName = project.GetEvaluatedProperty("AssemblyName"); specFlowProject.ProjectSettings.DefaultNamespace = project.GetEvaluatedProperty("RootNamespace"); var items = project.GetEvaluatedItemsByName("None").Cast <BuildItem>() .Concat(project.GetEvaluatedItemsByName("Content").Cast <BuildItem>()); foreach (BuildItem item in items) { var extension = Path.GetExtension(item.FinalItemSpec); if (extension.Equals(".feature", StringComparison.InvariantCultureIgnoreCase)) { var featureFile = new FeatureFileInput(item.FinalItemSpec); var ns = item.GetEvaluatedMetadata("CustomToolNamespace"); if (!String.IsNullOrEmpty(ns)) { featureFile.CustomNamespace = ns; } specFlowProject.FeatureFiles.Add(featureFile); } if (Path.GetFileName(item.FinalItemSpec).Equals("app.config", StringComparison.InvariantCultureIgnoreCase)) { var configFilePath = Path.Combine(projectFolder, item.FinalItemSpec); var configFileContent = File.ReadAllText(configFilePath); var configurationHolder = GetConfigurationHolderFromFileContent(configFileContent); specFlowProject.ProjectSettings.ConfigurationHolder = configurationHolder; specFlowProject.Configuration = configurationLoader.LoadConfiguration(configurationHolder, projectReference); } } return(specFlowProject); }
public void CloseAll() { BuildProject solution = (ServiceHost.Build as BuildService).solution; if (solution != null) { ServiceHost.Window.Document.Save(Path.ChangeExtension(solution.FullFileName, ".xaccdata")); solution.Save(solution.FullFileName); (ServiceHost.Build as BuildService).solution = null; } foreach (Project p in OpenProjects) { p.Save(); } Close(OpenProjects); }
/// <summary> /// Gets the MSBuild build property with the specified name from the WixProject. /// </summary> MSBuild.BuildProperty GetMSBuildProperty(string name) { MSBuild.Project msbuildProject = project.MSBuildProject; foreach (MSBuild.BuildPropertyGroup g in msbuildProject.PropertyGroups.Cast <MSBuild.BuildPropertyGroup>().ToList()) { if (!g.IsImported) { MSBuild.BuildProperty property = MSBuildInternals.GetProperty(g, name); if (property != null) { return(property); } } } return(null); }
public static string GetPreProcessorConstantsFromProject(Microsoft.Build.BuildEngine.Project coreVisualStudioProject) { string preProcessorConstants = ""; foreach (Microsoft.Build.BuildEngine.BuildPropertyGroup propertyGroup in coreVisualStudioProject.PropertyGroups) { foreach (Microsoft.Build.BuildEngine.BuildProperty property in propertyGroup) { if (property.Name == "DefineConstants") { preProcessorConstants += ";" + property.Value; } } } return(preProcessorConstants); }
/// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetEvaluatedProperty(ProjectFileConstants.ProjectTypeGuids); if (String.IsNullOrEmpty(guids)) { guids = this.GetType().GUID.ToString("B"); } return(guids); }
/// <summary> /// Removes all <Import> nodes from a project. /// </summary> public static void ClearImports(MSBuild.Project project) { XmlElement xmlProject = BeginXmlManipulation(project); List <XmlNode> nodesToRemove = new List <XmlNode>(); foreach (XmlNode node in xmlProject.ChildNodes) { if (node.NodeType == XmlNodeType.Element && node.Name == "Import") { nodesToRemove.Add(node); } } foreach (XmlNode node in nodesToRemove) { xmlProject.RemoveChild(node); } }
/// <summary> /// Adds references to this container from a MSBuild project. /// </summary> public void LoadReferencesFromBuildProject(MSBuild.Project buildProject) { foreach (string referenceType in SupportedReferenceTypes) { MSBuild.BuildItemGroup refererncesGroup = buildProject.GetEvaluatedItemsByName(referenceType); ReferenceNode node; bool isComReference = referenceType == ProjectFileConstants.COMReference; bool isAssemblyReference = referenceType == ProjectFileConstants.Reference; bool isProjectReference = referenceType == ProjectFileConstants.ProjectReference; if (isAssemblyReference && this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Sucessful) { continue; } foreach (MSBuild.BuildItem item in refererncesGroup) { ProjectElement element = new ProjectElement(this.ProjectMgr, item, false); if (isComReference) { node = this.CreateComReferenceNode(element); } else if (isAssemblyReference) { node = this.CreateAssemblyReferenceNode(element); } else if (isProjectReference) { node = this.CreateProjectReferenceNode(element); } else { // JRock: Added support for other references node = this.CreateOtherReferenceNode(element); } if (node != null) { this.AddChild(node); } } } }
public void Remove(Project prj) { projects.Remove(prj); BuildProject sol = (ServiceHost.Build as BuildService).solution; if (sol != null && prj.SolBuildItem != null) { sol.RemoveItem(prj.SolBuildItem); } if (prj == current) { current = projects.Count > 0 ? projects[0] as Project : null; } if (prj == startupproject) { startupproject = null; } }
/// <summary> /// Adds references to this container from a MSBuild project. /// </summary> public void LoadReferencesFromBuildProject(MSBuild.Project buildProject) { foreach (string referenceType in SupportedReferenceTypes) { MSBuild.BuildItemGroup refererncesGroup = buildProject.GetEvaluatedItemsByName(referenceType); bool isAssemblyReference = referenceType == ProjectFileConstants.Reference; // If the project was loaded for browsing we should still create the nodes but as not resolved. if (this.ProjectMgr.HasPassedSecurityChecks && isAssemblyReference && this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences) != MSBuildResult.Successful) { continue; } foreach (MSBuild.BuildItem item in refererncesGroup) { ProjectElement element = new ProjectElement(this.ProjectMgr, item, false); 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); } } } } }
public void GeneralPropertyPageTestInitialize() { testString = "This is a test string"; // Create a basic service provider serviceProvider = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider.CreateOleServiceProviderWithBasicServices(); AddBasicSiteSupport(serviceProvider); // Initialize GeneralPropertyPage instance generalPropertyPage = new GeneralPropertyPage(); gppAccessor = new VisualStudio_Project_Samples_GeneralPropertyPageAccessor(generalPropertyPage); // Initialize ProjectPackage context projectPackage = new NestedProjectPackage(); ((IVsPackage)projectPackage).SetSite(serviceProvider); // prepare the factory projectFactory = new NestedProjectFactoryFake(projectPackage); //set the build engine and build project on the factory object FieldInfo buildEngine = typeof(ProjectFactory).GetField("buildEngine", BindingFlags.Instance | BindingFlags.NonPublic); buildEngine.SetValue(projectFactory, MSBuild.Engine.GlobalEngine); MSBuild.Project msbuildproject = MSBuild.Engine.GlobalEngine.CreateNewProject(); FieldInfo buildProject = typeof(ProjectFactory).GetField("buildProject", BindingFlags.Instance | BindingFlags.NonPublic); buildProject.SetValue(projectFactory, msbuildproject); //Create the project object using the projectfactory and load the project int canCreate; if (VSConstants.S_OK == ((IVsProjectFactory)projectFactory).CanCreateProject(fullPathToProjectFile, 2, out canCreate)) { MethodInfo preCreateForOuter = typeof(NestedProjectFactory).GetMethod("PreCreateForOuter", BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(preCreateForOuter, "failed to get the PreCreateForOuter method info object from NestedProjectFactory type"); projectNode = (NesteProjectNodeFake)preCreateForOuter.Invoke(projectFactory, new object[] { IntPtr.Zero }); Assert.IsNotNull(projectNode, "Failed to create the projectnode object"); Guid iidProject = new Guid(); int pfCanceled; projectNode.Load(fullPathToProjectFile, "", "", 2, ref iidProject, out pfCanceled); } }
public override bool Execute() { int i = 0; Engine e = Engine.GlobalEngine; e.BinPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20); this.output = new string[input.Length]; foreach (ITaskItem ti in input) { string location = ti.ItemSpec; BuildProject p = e.GetLoadedProject(location); if (p == null) { p = e.CreateNewProject(); p.Load(location); } string assname = p.GetEvaluatedProperty("AssemblyName") ?? p.GetEvaluatedProperty("MSBuildProjectName"); string outpath = p.GetEvaluatedProperty("OutputPath") ?? "."; string outtype = p.GetEvaluatedProperty("OutputType") ?? "WinExe"; string ext = ".exe"; if (string.Compare(outtype, "Library", true) == 0) { ext = ".dll"; } this.output[i] = System.IO.Path.Combine(outpath, assname + ext); this.output[i] = this.output[i] ?? "fake"; Log.LogMessage("Project: {1,-20}\tOutput: {0}", this.output[i], p.GetEvaluatedProperty("MsBuildProjectName")); i++; } return(true); }
internal bool Build(MSBuildEngine.ProjectToBuild ptb) { LoggingService.Debug("Run MSBuild on " + ptb.file); if (!string.IsNullOrEmpty(ptb.configuration)) { engine.GlobalProperties.SetProperty("Configuration", ptb.configuration); } if (!string.IsNullOrEmpty(ptb.platform)) { engine.GlobalProperties.SetProperty("Platform", ptb.platform); } Microsoft.Build.BuildEngine.Project project = buildRun.LoadProject(engine, ptb.file); if (project == null) { LoggingService.Debug("Error loading " + ptb.file); return(false); } foreach (string additionalTargetFile in MSBuildEngine.AdditionalTargetFiles) { project.AddNewImport(additionalTargetFile, null); } bool success; if (string.IsNullOrEmpty(ptb.targets)) { success = engine.BuildProject(project); } else { success = engine.BuildProject(project, ptb.targets.Split(';')); } logger.FlushCurrentError(); ReleaseOutput(); LoggingService.Debug("MSBuild on " + ptb.file + " finished " + (success ? "successfully" : "with error")); return(success); }
private void BuildProject(IEnumerable <BuildItemFileInfo> buildItemFiles, Engine engine) { Microsoft.Build.BuildEngine.Project proj = engine.CreateNewProject(); engine.RegisterLogger(new Log4NetMSBuildLogger(engine, proj)); engine.RegisterLogger(new BuildLogMSBuildLogger(engine, proj)); AssemblyName = Path.GetFileNameWithoutExtension(c_AssemblyName); proj.FullFileName = Path.Combine(LibraryPath, String.Format("{0}.csproj", AssemblyName)); ConfigureProject(proj); BuildItemGroup items = proj.AddNewItemGroup(); foreach (BuildItemFileInfo buildItemFile in buildItemFiles) { AddFileToProject(items, buildItemFile.Path, buildItemFile.Generator.MSBuildItemType); if (buildItemFile.Generator.DeployFile) { AddOutputFile(buildItemFile.Path); } } proj.Save(Path.Combine(FullProjectDirectory, AssemblyName + ".csproj")); if (!engine.BuildProject(proj)) { throw new BuildException(String.Format(CultureInfo.CurrentUICulture, "Failed to build {0}", c_AssemblyName)); } string asmFileName = Path.Combine(OutputPath, c_AssemblyName); AddOutputFile(asmFileName); // deploy the associated .pdb, if it exists. string pdbFileName = Path.ChangeExtension(asmFileName, ".pdb"); if (File.Exists(pdbFileName)) { AddOutputFile(pdbFileName); } }