public ProjectCollection FetchAll() { ProjectCollection coll = new ProjectCollection(); Query qry = new Query(Project.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
/// <summary> /// Initializes a new instance of the <see cref="Solution" /> class. /// </summary> /// <param name="fullpath">The fullpath.</param> /// <param name="headers">The headers.</param> /// <param name="projects">The projects.</param> /// <param name="globalSections">The global sections.</param> /// <param name="properties">The properties.</param> public Solution(string fullpath, IEnumerable<string> headers, IEnumerable<Project> projects, IEnumerable<Section> globalSections, IEnumerable<PropertyItem> properties) { FullPath = fullpath; this.headers = new List<string>(headers); this.projects = new ProjectCollection(this, projects); this.globalSections = new SectionCollection(globalSections); this.Properties = new PropertyItemCollection(properties); }
/// <summary> /// Initializes a new instance of the <see cref="Solution"/> class. /// </summary> public Solution() { FullPath = null; headers = new List<string>(); projects = new ProjectCollection(this); globalSections = new SectionCollection(); Properties = new PropertyItemCollection(); }
void BindProject() { ProjectCollection projectCollection = new ProjectCollection(); //coll.Where(DocCat.Columns.Active, 1); projectCollection.Load(); grdProject.DataSource = projectCollection; grdProject.DataBind(); //pnlMain.UpdateAfterCallBack = true; }
/// <summary> /// Create a ProjectInstance from provided project content and host services object /// </summary> private static ProjectInstance GetProjectInstance(string content, HostServices hostServices, IDictionary <string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { XmlReader reader = XmlReader.Create(new StringReader(content)); if (globalProperties == null) { // choose some interesting defaults if we weren't explicitly asked to use a set. globalProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("g1", "v1"); globalProperties.Add("g2", "v2"); } Project project = new Project(reader, globalProperties, toolsVersion ?? "4.0", projectCollection ?? ProjectCollection.GlobalProjectCollection); ProjectInstance instance = project.CreateProjectInstance(); return(instance); }
public ProjectInstance(string projectFile, IDictionary <string, string> globalProperties, string toolsVersion, ProjectCollection projectCollection) : this(ProjectRootElement.Create(projectFile), globalProperties, toolsVersion, projectCollection) { }
public HttpResponseMessage RetrieveTicketProjectList(string clientIds = null, int? includeId = null, bool? inactiveOnly = null, bool? nonProjectOnly = null, int? userId = null) { var ticketProjectsList = new ProjectCollection(); var ticketProjectList = this.lookupService.RetrieveTicketProjectListItem(clientIds, includeId, inactiveOnly, nonProjectOnly, Convert.ToInt32(userId, CultureInfo.CurrentCulture)); ticketProjectList.Where(a => !a.IsDoNotList).ToList().ForEach(ticketProject => ticketProjectsList.Add(MapToTicketProject(ticketProject))); return Request.CreateResponse(HttpStatusCode.OK, ticketProjectsList); }
public void TestCastAssemblyResources() { var engine = new ProjectCollection(); var prel = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine); var asm = AssemblyDefinition.CreateAssembly( new AssemblyNameDefinition("Foo", new Version(1, 0, 0, 0)), "Main", ModuleKind.Dll ); var dll = Path.Combine(TempDir, "Foo.dll"); asm.Write(dll); var unpackDir = GetTempPath("unpacked"); prel.SetProperty("XamarinBuildDownloadDir", unpackDir); prel.SetProperty("TargetFrameworkIdentifier", "Xamarin.iOS"); prel.SetProperty("OutputType", "Exe"); prel.SetProperty("IntermediateOutputPath", Path.Combine(TempDir, "obj")); prel.AddItem( "XamarinBuildDownload", "AppInvites-1.0.2", new Dictionary <string, string> { { "Url", "https://www.gstatic.com/cpdc/278f79fcd3b365e3-AppInvites-1.0.2.tar.gz" }, { "Kind", "Tgz" } }); prel.AddItem( "ReferencePath", dll ); var bundlePath = Path.Combine(unpackDir, "AppInvites-1.0.2", "Frameworks", "GINInvite.framework", "Versions", "A", "Resources", "GINInviteResources.bundle"); var plist = Path.Combine(bundlePath, "Info.plist"); string resourceName = "__monotouch_content_GINInviteResources.bundle_fInfo.plist"; prel.AddItem( "RestoreAssemblyResource", plist, new Dictionary <string, string> { { "AssemblyName", "Foo" }, { "LogicalName", resourceName } } ); var image = Path.Combine(bundlePath, "*****@*****.**"); resourceName = "__monotouch_content_GINInviteResources.bundle_fic__sms__24%403x.png"; prel.AddItem( "RestoreAssemblyResource", image, new Dictionary <string, string> { { "AssemblyName", "Foo" }, { "LogicalName", resourceName } } ); AddCoreTargets(prel); var project = new ProjectInstance(prel); var log = new MSBuildTestLogger(); var success = BuildProject(engine, project, "_XamarinBuildCastAssemblyResources", log); var ignoreMessages = new List <string> { "Enumeration yielded no results" }; ignoreMessages.AddRange(DEFAULT_IGNORE_PATTERNS); AssertNoMessagesOrWarnings(log, ignoreMessages.ToArray()); Assert.True(success); var plistExists = File.Exists(plist); Assert.True(plistExists); var imageExists = File.Exists(image); Assert.True(imageExists); // Check if BundleResources were generated correctly. var bundleResources = project.GetItems("BundleResource"); Assert.True(bundleResources != null); // Check if Optimize metadata was generated correctly. var imageResource = bundleResources.Single(b => b.GetMetadataValue("Identity").ToLower().EndsWith(".png")); Assert.True(imageResource.GetMetadataValue("Optimize") == "False"); }
public void ImportFromExtensionsPathSearchOrder2() { string extnTargetsFileContent1 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromFirstFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromSecondFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; // File with the same name available in two different extension paths, but the one from the first // directory in MSBuildExtensionsPath environment variable should get loaded string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); // MSBuildExtensionsPath* property value has highest priority for the lookups try { var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existstant"), extnDir1)); var logger = new MockLogger(); projColln.RegisterLogger(logger); var project = projColln.LoadProject(mainProjectPath); project.SetProperty("MSBuildExtensionsPath", extnDir2); project.ReevaluateIfNecessary(); Assert.True(project.Build()); logger.AssertLogContains("Running FromExtn"); logger.AssertLogContains("PropertyFromExtn1: FromSecondFile"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } if (extnDir2 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true); } } }
/// <summary> /// Initializes a new instance of the <see cref="DemoDataProvider"/> class. /// </summary> public DemoDataProvider() { this.sampleMediaBinUri = new Uri("http://rce.litwareinc.com/samples/2.0/MediaBin/11111111-1111-1111-1111-111111111111"); this.libraryContainer = new Container(); // Adding sample videos; //this.libraryContainer.Items.Add(CreateSmoothVideoItem(CreateUri(VideoItems), "Elephants Dream", 653.791678, SmpteFrameRate.Smpte2997NonDrop, "http://video3.smoothhd.com/ondemand/ElephantsDream.ism/Manifest", 1280, 720, "SmoothStream")); this.libraryContainer.Items.Add(CreateSmoothVideoItem(CreateUri(VideoItems), "Amazing Caves", 85.4999, SmpteFrameRate.Unknown, "http://www.indoorworx.com/SmoothStreaming/Amazing_Caves_1080.ism/Manifest", 852, 480, "SmoothStream")); this.libraryContainer.Items.Add(CreateImageItem("Francis & ESQL", "http://i.msdn.microsoft.com/bb969103.how-we-do-it(en-us,MSDN.10).png", 300, 200)); this.libraryContainer.Items.Add(CreateSmoothVideoItem(CreateUri(VideoItems), "NBA", 408, SmpteFrameRate.Smpte2997NonDrop, "http://video3.smoothhd.com/ondemand/NBA.ism/Manifest", 1280, 720, "SmoothStream")); this.libraryContainer.Items.Add(CreateImageItem("p&p Logo", "http://i.msdn.microsoft.com/ms998572.pandp-logo-txt-2009(en-us,MSDN.10).png", 250, 68)); this.libraryContainer.Items.Add(CreateSmoothVideoItem(CreateUri(VideoItems), "Basic Curveball", 62.1621042, SmpteFrameRate.Smpte2997Drop, "http://video3.smoothhd.com/ondemand/eHow_Baseball.ism/Manifest", 1280, 720, "SmoothStream")); this.libraryContainer.Items.Add(CreateAudioItem("Glenn Block on Prism", 2286, "http://herdingcode.com/wp-content/uploads/HerdingCode-0011-Glenn-Block-Part-1.mp3")); this.libraryContainer.Items.Add(CreateSmoothVideoItem(CreateUri(VideoItems), "Big Buck Bunny", 596.458333, SmpteFrameRate.Smpte2997NonDrop, "http://video3.smoothhd.com/ondemand/Big%20Buck%20Bunny%20Adaptive.ism/Manifest", 1280, 720, "SmoothStream")); this.libraryContainer.Items.Add(CreateVideoItem(CreateUri(VideoItems), "Carol Bartz", 155, SmpteFrameRate.Smpte2997NonDrop, "http://208.217.186.229/media/WMV/CarolBartz.wmv", 320, 240, "Master")); this.libraryContainer.Items.Add(CreateVideoItem(CreateUri(VideoItems), "Steve Ballmer", 153, SmpteFrameRate.Smpte2997NonDrop, "http://208.217.186.229/media/WMV/SteveBallmer.wmv", 320, 240, "Master")); this.libraryContainer.Items.Add(CreateImageItem("XBox Live", "http://www.xbox.com/NR/rdonlyres/09842316-4F8D-46E5-A504-BE7AB207CE69/0/xbox_white_1280x1204.jpg", 1280, 1024)); this.libraryContainer.Items.Add(CreateImageItem("PDC 2009 640x474", "http://blogs.southworks.net/srenzi/files/2009/11/image3.png", 640, 474)); this.libraryContainer.Items.Add(CreateImageItem("Windows 63 x 63", "http://i.microsoft.com/global/En/us/PublishingImages/SLWindowPane/Windows_T.png", 63, 63)); // Adding sample comments this.sampleComments = new CommentCollection(); this.sampleComments.Add(CreateComment("David", "Some comment", "Global", DateTime.Today, null, null, DateTime.Today.AddDays(-15))); this.sampleComments.Add(CreateComment("Jay", "This is the best one!!", "Timeline", new DateTime(2008, 2, 10), 1400, 1520, DateTime.Today.AddDays(-15))); this.sampleComments.Add(CreateComment("David", "This is a Shot comment", "Shot", new DateTime(2008, 2, 10), 980, 1060, DateTime.Today.AddDays(-15))); // Adding sample media bin this.sampleMediaBin = new MediaBin { Id = this.sampleMediaBinUri }; this.sampleMediaBin.Items.Add(this.libraryContainer.Items[0]); this.sampleMediaBin.Items.Add(this.libraryContainer.Items[1]); this.sampleMediaBin.Items.Add(this.libraryContainer.Items[2]); // Adding sample tracks this.sampleTracks = new TrackCollection(); this.sampleTracks.Add(CreateTrack(TrackType.Visual)); this.sampleTracks[0].Shots.Add(CreateShot(this.sampleMediaBin.Items[0], 180, ((VideoItem)this.sampleMediaBin.Items[0]).Duration.Value - 180, 800, 100)); this.sampleTracks[0].Shots.Add(CreateShot(this.sampleMediaBin.Items[0], 0, ((VideoItem)this.sampleMediaBin.Items[0]).Duration.Value - 60, 0, 65)); this.sampleTracks[0].Shots[0].Comments.Add(this.sampleComments[2]); this.sampleTracks.Add(CreateTrack(TrackType.Audio)); // this.sampleTracks[1].Shots.Add(CreateShot(this.sampleMediaBin.Items[1], 0, ((AudioItem)this.sampleMediaBin.Items[1]).Duration.Value, 60, 80)); // Adding sample title templates this.sampleTitleTemplates = new TitleTemplateCollection(); this.sampleTitleTemplates.Add(CreateTitleTemplate("FadeCenter")); this.sampleTitleTemplates.Add(CreateTitleTemplate("Spinner")); this.sampleTitleTemplates.Add(CreateTitleTemplate("ScrollingCenter")); this.sampleTitleTemplates.Add(CreateTitleTemplate("ZoomCenter")); // Adding sample titles this.sampleTitles = new TitleCollection(); this.sampleTitles.Add(CreateTitle(this.sampleTitleTemplates[0], 1200, 600)); this.sampleTitles.Add(CreateTitle(this.sampleTitleTemplates[0], 2200, 400)); // Adding sample project this.sampleProject = new Project { Id = new Uri("http://rce.litwareinc.com/samples/2.0/Projects/11111111-1111-1111-1111-111111111111"), Title = "Sample Project", Creator = @"RCE\ejadib", Created = new DateTime(2009, 1, 1), RippleMode = false, AutoSaveInterval = 10, SmpteFrameRate = SmpteFrameRate.Smpte2997NonDrop.ToString(), StartTimeCode = 1802, MediaBin = this.sampleMediaBin, Comments = { this.sampleComments[0], this.sampleComments[1], this.sampleComments[2] }, Timeline = { this.sampleTracks[0], this.sampleTracks[1] }, Titles = { this.sampleTitles[0], this.sampleTitles[1] } }; this.sampleProjects = new ProjectCollection(); this.sampleProjects.Add(this.sampleProject); this.sampleProjects.Add(new Project { Id = new Uri("http://rce.litwareinc.com/samples/2.0/Projects/CC8191B0-64FF-438b-89D1-C9464B310FB7"), Title = "WithStartTimeCode1802", Creator = @"RCE\ejadib", Created = new DateTime(2009, 3, 1), RippleMode = false, AutoSaveInterval = 10, SmpteFrameRate = SmpteFrameRate.Smpte25.ToString(), StartTimeCode = 1802, MediaBin = this.sampleMediaBin, Comments = { this.sampleComments[0], this.sampleComments[1], this.sampleComments[2] }, Timeline = { this.sampleTracks[0], this.sampleTracks[1] }, Duration = 200 }); this.sampleProjects.Add(new Project { Id = new Uri("http://rce.litwareinc.com/samples/2.0/Projects/0F20DC18-2164-4683-AB65-51715A5DD7D3"), Title = "WithStartTimeCode600", Creator = @"RCE\ejadib", Created = new DateTime(2009, 2, 6), RippleMode = false, AutoSaveInterval = 10, SmpteFrameRate = SmpteFrameRate.Smpte2997Drop.ToString(), StartTimeCode = 600, MediaBin = this.sampleMediaBin, Comments = { this.sampleComments[0], this.sampleComments[1], this.sampleComments[2] }, Timeline = { this.sampleTracks[0], this.sampleTracks[1] }, Duration = 400 }); this.sampleProjects.Add(new Project { Id = new Uri("http://rce.litwareinc.com/samples/2.0/Projects/0B05A8F0-1D3C-44bb-AD71-1387D2A93414"), Title = "No Titles", Creator = @"RCE\ejadib", Created = new DateTime(2009, 3, 25), RippleMode = true, AutoSaveInterval = 10, SmpteFrameRate = SmpteFrameRate.Smpte2997NonDrop.ToString(), StartTimeCode = 0, MediaBin = this.sampleMediaBin, Comments = { this.sampleComments[0], this.sampleComments[1], this.sampleComments[2] }, Timeline = { this.sampleTracks[0], this.sampleTracks[1] }, Duration = 600 }); }
private ProjectInstance CreateProjectInstance(string projectFullPath, IDictionary <string, string> globalProperties, ProjectCollection projectCollection) { return(Project.FromFile( projectFullPath, new ProjectOptions { EvaluationContext = SharedEvaluationContext, GlobalProperties = globalProperties, LoadSettings = DefaultProjectLoadSettings, ProjectCollection = projectCollection, }) .CreateProjectInstance( ProjectInstanceSettings.ImmutableWithFastItemLookup, SharedEvaluationContext)); }
public ProjectCollection FetchByQuery(Query qry) { ProjectCollection coll = new ProjectCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
public ProjectCollection FetchByID(object ProjectId) { ProjectCollection coll = new ProjectCollection().Where("projectId", ProjectId).Load(); return coll; }
/// <summary> /// Compiles the project and produces an output assembly /// </summary> /// <returns> /// Full name of the output assembly file. /// </returns> public static CompileResult Compile(CompileProject project) { string outputDirectory = string.Empty; if (project == null) { throw new ArgumentNullException(CompileMessages.ProjectNull); } try { //Create output directory for the compile project necessary files outputDirectory = CreateBuildDirectory(); //Create necessary files for MSBuild CreateProjectFiles(project, outputDirectory); // Once all the temporary files are created, we can call MsBuild to compile. // NOTE: If you want to dynamic build, the Targect Framework of this project MUST be .NET Framework 4. // MUST NOT be the Client Profile, or you cannot reference Microsoft.Build.dll using (var projectPropertiesCollection = new ProjectCollection()) { var globalProperty = new Dictionary<string, string>(); var buildRequest = new BuildRequestData( Path.Combine(outputDirectory, project.ProjectName) + ".csproj", globalProperty, null, new[] { "Build" }, null); var buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectPropertiesCollection), buildRequest); if (buildResult == null) { return new CompileResult(BuildResultCode.Failure, outputDirectory, null); } switch (buildResult.OverallResult) { case BuildResultCode.Success: var filePath = Path.Combine(outputDirectory, project.ProjectName) + ".dll"; var result = new CompileResult(buildResult.OverallResult, filePath, null); try { File.Delete(Path.Combine(outputDirectory, PrivateKeyName)); } catch (Exception) //Failure to delete key doesn't affect the result of the operation { } return result; default: throw new CompileException(CompileMessages.ErrorCompiling, buildResult.Exception); } } } catch (CompileException ex) { var result = new CompileResult(BuildResultCode.Failure, outputDirectory, ex); return result; } catch (AggregateException ex) { //More than one exception occured in one of the compile steps var result = new CompileResult(BuildResultCode.Failure, outputDirectory, ex); return result; } catch (ArgumentException ex) { var result = new CompileResult(BuildResultCode.Failure, outputDirectory, ex); return result; } catch (InvalidOperationException ex) { var result = new CompileResult(BuildResultCode.Failure, outputDirectory, ex); return result; } }
public void Execute() { bool result = false; bool show_stacktrace = false; try { parameters.ParseArguments(args); show_stacktrace = (parameters.LoggerVerbosity == LoggerVerbosity.Detailed || parameters.LoggerVerbosity == LoggerVerbosity.Diagnostic); if (!parameters.NoLogo) { ErrorUtilities.ShowVersion(false); } project_collection = new ProjectCollection(); if (!String.IsNullOrEmpty(parameters.ToolsVersion)) { if (project_collection.GetToolset(parameters.ToolsVersion) == null) { ErrorUtilities.ReportError(0, new InvalidToolsetDefinitionException("Toolset " + parameters.ToolsVersion + " was not found").Message); } project_collection.DefaultToolsVersion = parameters.ToolsVersion; } foreach (var p in parameters.Properties) { project_collection.GlobalProperties.Add(p.Key, p.Value); } if (!parameters.NoConsoleLogger) { printer = new ConsoleReportPrinter(); ConsoleLogger cl = new ConsoleLogger(parameters.LoggerVerbosity, printer.Print, printer.SetForeground, printer.ResetColor); cl.Parameters = parameters.ConsoleLoggerParameters; cl.Verbosity = parameters.LoggerVerbosity; project_collection.RegisterLogger(cl); } if (parameters.FileLoggerParameters != null) { for (int i = 0; i < parameters.FileLoggerParameters.Length; i++) { string fl_params = parameters.FileLoggerParameters [i]; if (fl_params == null) { continue; } var fl = new FileLogger(); if (fl_params.Length == 0 && i > 0) { fl.Parameters = String.Format("LogFile=msbuild{0}.log", i); } else { fl.Parameters = fl_params; } project_collection.RegisterLogger(fl); } } foreach (LoggerInfo li in parameters.Loggers) { Assembly assembly; if (li.InfoType == LoadInfoType.AssemblyFilename) { assembly = Assembly.LoadFrom(li.Filename); } else { assembly = Assembly.Load(li.AssemblyName); } ILogger logger = (ILogger)Activator.CreateInstance(assembly.GetType(li.ClassName)); logger.Parameters = li.Parameters; project_collection.RegisterLogger(logger); } string projectFile = parameters.ProjectFile; if (!File.Exists(projectFile)) { ErrorUtilities.ReportError(0, String.Format("Project file '{0}' not found.", projectFile)); return; } XmlReaderSettings settings = new XmlReaderSettings(); if (parameters.Validate) { settings.ValidationType = ValidationType.Schema; if (parameters.ValidationSchema == null) { using (var xsdxml = XmlReader.Create(defaultSchema)) settings.Schemas.Add(XmlSchema.Read(xsdxml, null)); } else { using (var xsdxml = XmlReader.Create(parameters.ValidationSchema)) settings.Schemas.Add(XmlSchema.Read(xsdxml, null)); } } var projectInstances = new List <ProjectInstance> (); if (string.Equals(Path.GetExtension(projectFile), ".sln", StringComparison.OrdinalIgnoreCase)) { var parser = new SolutionParser(); var root = ProjectRootElement.Create(); parser.ParseSolution(projectFile, project_collection, root, LogWarning); foreach (var p in project_collection.LoadedProjects) { projectInstances.Add(p.CreateProjectInstance()); } } else { project = ProjectRootElement.Create(XmlReader.Create(projectFile, settings), project_collection); var pi = new ProjectInstance(project, parameters.Properties, parameters.ToolsVersion, project_collection); projectInstances.Add(pi); } foreach (var projectInstance in projectInstances) { var targets = parameters.Targets.Length == 0 ? projectInstance.DefaultTargets.ToArray() : parameters.Targets; result = projectInstance.Build(targets, parameters.Loggers.Count > 0 ? parameters.Loggers : project_collection.Loggers); if (!result) { break; } } } catch (InvalidProjectFileException ipfe) { ErrorUtilities.ReportError(0, show_stacktrace ? ipfe.ToString() : ipfe.Message); } catch (InternalLoggerException ile) { ErrorUtilities.ReportError(0, show_stacktrace ? ile.ToString() : ile.Message); } catch (CommandLineException cle) { ErrorUtilities.ReportError(cle.ErrorCode, show_stacktrace ? cle.ToString() : cle.Message); } finally { //if (project_collection != null) // project_collection.UnregisterAllLoggers (); Environment.Exit(result ? 0 : 1); } }
public void TestResourcesAdded() { // Tests won't run on windows due to file locking issues with assemblies if (IsWindows) { return; } var engine = new ProjectCollection(); var prel = ProjectRootElement.Create(Path.Combine(TempDir, "project.csproj"), engine); var asm = AssemblyDefinition.CreateAssembly( new AssemblyNameDefinition("Foo", new Version(1, 0, 0, 0)), "Main", ModuleKind.Dll ); var dll = Path.Combine(TempDir, "Foo.dll"); asm.Write(dll); var unpackDir = GetTempPath("unpacked"); prel.SetProperty("XamarinBuildDownloadDir", unpackDir); prel.SetProperty("TargetFrameworkIdentifier", "Xamarin.iOS"); prel.SetProperty("OutputType", "Exe"); prel.SetProperty("IntermediateOutputPath", Path.Combine(TempDir, "obj")); prel.AddItem( "XamarinBuildDownload", "AppInvites-1.0.2", new Dictionary <string, string> { { "Url", "https://www.gstatic.com/cpdc/278f79fcd3b365e3-AppInvites-1.0.2.tar.gz" }, { "Kind", "Tgz" } }); prel.AddItem( "ReferencePath", dll ); var plist = Path.Combine(unpackDir, "AppInvites-1.0.2", "Frameworks", "GINInvite.framework", "Versions", "A", "Resources", "GINInviteResources.bundle", "Info.plist"); const string resourceName = "monotouch_content_GINInviteResources.bundle_fInfo.plist"; prel.AddItem( "RestoreAssemblyResource", plist, new Dictionary <string, string> { { "AssemblyName", "Foo" }, { "LogicalName", resourceName } } ); AddCoreTargets(prel); var project = new ProjectInstance(prel); var log = new MSBuildTestLogger(); var success = BuildProject(engine, project, "_XamariniOSBuildResourceRestore", log); var ignoreMessages = new List <string> { "Enumeration yielded no results" }; ignoreMessages.AddRange(DEFAULT_IGNORE_PATTERNS); AssertNoMessagesOrWarnings(log, ignoreMessages.ToArray()); Assert.True(success); var plistExists = File.Exists(plist); Assert.True(plistExists); //check the referencepath has been replaced by the processed one var items = project.GetItems("ReferencePath"); var mergedItem = items.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude)); Assert.True(mergedItem != null); var itemPath = mergedItem.EvaluatedInclude; //Assert.NotEqual (dll, itemPath); //check the assembly has the processed resource var processedAsm = AssemblyDefinition.ReadAssembly(itemPath); var resource = processedAsm.MainModule.Resources.FirstOrDefault() as EmbeddedResource; Assert.NotNull(resource); Assert.Equal(resourceName, resource.Name); var ps = PObject.FromStream(resource.GetResourceStream()) as PDictionary; Assert.False(ps.ContainsKey("CFBundleExecutable")); Assert.True(ps.Count > 0); var processedAsmMtime = File.GetLastWriteTime(itemPath); // check incremental build works project = new ProjectInstance(prel); log = new MSBuildTestLogger(); var newSuccess = BuildProject(engine, project, "_XamariniOSBuildResourceRestore", log); AssertNoMessagesOrWarnings(log, ignoreMessages.ToArray()); Assert.True(success); var newItems = project.GetItems("ReferencePath"); var newItem = newItems.FirstOrDefault(i => !string.IsNullOrEmpty(i.EvaluatedInclude)); var newItemPath = newItem.EvaluatedInclude; Assert.Equal(itemPath, newItemPath); Assert.Equal(processedAsmMtime, File.GetLastWriteTime(newItemPath)); }
protected void ShowProjectList(ProjectCollection projects) { foreach (Project p in projects) { Console.WriteLine(p.ToString()); Console.WriteLine(); Console.WriteLine("Press any key to continue... D - to show details or Q - to terminate"); ConsoleKey ck = Console.ReadKey().Key; if (ck == ConsoleKey.Q) break; if (ck == ConsoleKey.D) GetProjectDetails(p); } }
public MSBuildEngineV12(MSBuildEngineManager manager) : base(manager) { projects = new ProjectCollection(); }
/// <summary> /// Sets the project collection. /// </summary> /// <param name="projectCollection">The project collection.</param> public void SetProjectCollection(ProjectCollection projectCollection) { this.projects = projectCollection; }
public static ProjectFileInfo Create(ILogger logger, string solutionDirectory, string projectFilePath) { var projectFileInfo = new ProjectFileInfo(); projectFileInfo.ProjectFilePath = projectFilePath; #if ASPNET50 if (!IsMono) { var properties = new Dictionary <string, string> { { "DesignTimeBuild", "true" }, { "BuildProjectReferences", "false" }, { "_ResolveReferenceDependencies", "true" }, { "SolutionDir", solutionDirectory + Path.DirectorySeparatorChar } }; var collection = new ProjectCollection(properties); var project = collection.LoadProject(projectFilePath); var projectInstance = project.CreateProjectInstance(); var buildResult = projectInstance.Build("ResolveReferences", loggers: null); if (!buildResult) { return(null); } projectFileInfo.AssemblyName = projectInstance.GetPropertyValue("AssemblyName"); projectFileInfo.Name = projectInstance.GetPropertyValue("ProjectName"); projectFileInfo.TargetFramework = new FrameworkName(projectInstance.GetPropertyValue("TargetFrameworkMoniker")); projectFileInfo.ProjectId = new Guid(projectInstance.GetPropertyValue("ProjectGuid").TrimStart('{').TrimEnd('}')); projectFileInfo.TargetPath = projectInstance.GetPropertyValue("TargetPath"); projectFileInfo.SourceFiles = projectInstance.GetItems("Compile") .Select(p => p.GetMetadataValue("FullPath")) .ToList(); projectFileInfo.References = projectInstance.GetItems("ReferencePath") .Where(p => !string.Equals("ProjectReference", p.GetMetadataValue("ReferenceSourceTarget"), StringComparison.OrdinalIgnoreCase)) .Select(p => p.GetMetadataValue("FullPath")) .ToList(); projectFileInfo.ProjectReferences = projectInstance.GetItems("ProjectReference") .Select(p => p.GetMetadataValue("FullPath")) .ToList(); projectFileInfo.Analyzers = projectInstance.GetItems("Analyzer") .Select(p => p.GetMetadataValue("FullPath")) .ToList(); } else { // On mono we need to use this API since the ProjectCollection // isn't fully implemented #pragma warning disable CS0618 var engine = Engine.GlobalEngine; engine.DefaultToolsVersion = "4.0"; #pragma warning restore CS0618 // engine.RegisterLogger(new ConsoleLogger()); var propertyGroup = new BuildPropertyGroup(); propertyGroup.SetProperty("DesignTimeBuild", "true"); propertyGroup.SetProperty("BuildProjectReferences", "false"); // Dump entire assembly reference closure propertyGroup.SetProperty("_ResolveReferenceDependencies", "true"); propertyGroup.SetProperty("SolutionDir", solutionDirectory + Path.DirectorySeparatorChar); // propertyGroup.SetProperty("MSBUILDENABLEALLPROPERTYFUNCTIONS", "1"); engine.GlobalProperties = propertyGroup; var project = engine.CreateNewProject(); project.Load(projectFilePath); var buildResult = engine.BuildProjectFile(projectFilePath, new[] { "ResolveReferences" }, propertyGroup, null, BuildSettings.None, null); if (!buildResult) { return(null); } var itemsLookup = project.EvaluatedItems.OfType <BuildItem>() .ToLookup(g => g.Name); var properties = project.EvaluatedProperties.OfType <BuildProperty>() .ToDictionary(p => p.Name); projectFileInfo.AssemblyName = properties["AssemblyName"].FinalValue; projectFileInfo.Name = Path.GetFileNameWithoutExtension(projectFilePath); projectFileInfo.TargetFramework = new FrameworkName(properties["TargetFrameworkMoniker"].FinalValue); projectFileInfo.ProjectId = new Guid(properties["ProjectGuid"].FinalValue.TrimStart('{').TrimEnd('}')); projectFileInfo.TargetPath = properties["TargetPath"].FinalValue; // REVIEW: FullPath here returns the wrong physical path, we need to figure out // why. We must be setting up something incorrectly projectFileInfo.SourceFiles = itemsLookup["Compile"] .Select(b => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, b.FinalItemSpec))) .ToList(); projectFileInfo.References = itemsLookup["ReferencePath"] .Where(p => !p.HasMetadata("Project")) .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec))) .ToList(); projectFileInfo.ProjectReferences = itemsLookup["ProjectReference"] .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec))) .ToList(); projectFileInfo.Analyzers = itemsLookup["Analyzer"] .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec))) .ToList(); } #else // TODO: Shell out to msbuild/xbuild here? #endif return(projectFileInfo); }
public Solution() { Projects = new ProjectCollection(); }
public void ExpandExtensionsPathFallbackInErrorMessage() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" /> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary <string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); Assert.Throws <InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath)); // Expanded $(FallbackExpandDir) will appear in quotes in the log logger.AssertLogContains("\"" + extnDir1 + "\""); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } }
public static void Open(ProjectCollection collection) { Open(collection, VersionControlPath.RootFolder, null); }
public static List<Workspace> GetRemoteWorkspaces(ProjectCollection collection) { var versionControl = collection.GetService<RepositoryService>(); return versionControl.QueryWorkspaces(collection.Server.UserName, string.Empty); }
public static void Open(ProjectCollection collection, string path, string fileName) { foreach (var view in IdeApp.Workbench.Documents) { var sourceDoc = view.GetContent<SourceControlExplorerView>(); if (sourceDoc != null) { sourceDoc.Load(collection); sourceDoc.ExpandPath(path); sourceDoc.FindListItem(fileName); view.Window.SelectWindow(); return; } } var sourceControlExplorerView = new SourceControlExplorerView(); sourceControlExplorerView.Load(collection); sourceControlExplorerView.ExpandPath(path); sourceControlExplorerView.FindListItem(fileName); IdeApp.Workbench.OpenDocument(sourceControlExplorerView, true); }
public static string GetMetadataValueEscaped(ProjectItemInstance item, string name) { var md = item.Metadata.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); return(md != null?ProjectCollection.Escape(md.EvaluatedValue) : null); }
private void Load(ProjectCollection collection) { if (this.projectCollection != null && string.Equals(collection.Id, this.projectCollection.Id, StringComparison.OrdinalIgnoreCase)) { return; } projectCollection = collection; ContentName = GettextCatalog.GetString("Source Explorer") + " - " + projectCollection.Server.Name + " - " + projectCollection.Name; using (var progress = new MonoDevelop.Ide.ProgressMonitoring.MessageDialogProgressMonitor(true, false, false)) { progress.BeginTask("Loading...", 2); FillWorkspaces(); progress.Step(1); FillTreeView(); progress.EndTask(); } }
public bool Build(IEnumerable <string> ProjectsPath, string versionName, string outputPrefix) { var ret = false; try { // Properties passed to MSBUILD (the ones of the .target file) var globalProperties = new Dictionary <string, string>(); // INFERENCE off globalProperties.Add("CodeContractsInferRequires", "false"); globalProperties.Add("CodeContractsInferEnsures", "false"); globalProperties.Add("CodeContractsInferObjectInvariants", "false"); // SUGGESTIONS off globalProperties.Add("CodeContractsSuggestAssumptions", "false"); globalProperties.Add("CodeContractsSuggestRequires", "false"); globalProperties.Add("CodeContractsSuggestEnsures", "false"); globalProperties.Add("CodeContractsSuggestObjectInvariants", "false"); // WARNINGS globalProperties.Add("CodeContractsRunCodeAnalysis", "true"); globalProperties.Add("CodeContractsAnalysisWarningLevel", "3"); globalProperties.Add("CodeContractsNonNullObligations", "true"); globalProperties.Add("CodeContractsBoundsObligations", "true"); globalProperties.Add("CodeContractsArithmeticObligations", "true"); globalProperties.Add("CodeContractsEnumObligations", "true"); globalProperties.Add("CodeContractsRedundantAssumptions", "false"); globalProperties.Add("CodeContractsMissingPublicRequiresAsWarnings", "false"); globalProperties.Add("CodeContractsRunInBackground", "false"); // get output globalProperties.Add("CodeContractsEnableRuntimeChecking", "false"); // speedup globalProperties.Add("CodeContractsReferenceAssembly", "Build"); // make sure we have it //globalProperties.Add("CodeContractsUseBaseLine", "true"); //globalProperties.Add("CodeContractsBaseLineFile", "base.xml"); //globalProperties.Add("CodeContractsExtraAnalysisOptions", "-repro"); globalProperties.Add("CodeContractsCacheAnalysisResults", "true"); globalProperties.Add("CodeContractsSQLServerOption", "cloudotserver"); var extraOptions = this.ExtraOptions == null ? "" : this.ExtraOptions; extraOptions += " -sortwarns:false -stats:perMethod -show:progress -trace:cache"; if (this.SaveSemanticBaseline) { extraOptions += String.Format(" -saveSemanticBaseline:{0}", versionName); } else { extraOptions += String.Format(" -useSemanticBaseline:{0}", versionName); } globalProperties.Add("CodeContractsExtraAnalysisOptions", extraOptions); //globalProperties.Add("CodeContractsCacheVersion", VersionId.ToString()); //globalProperties.Add("CodeContractsCacheMaxSize", Int32.MaxValue.ToString()); globalProperties.Add("DeployExtension", "false"); // avoid vsix deployment // It does not work: The log file is empty var logFileName = "buildlog." + versionName + "." + outputPrefix + (this.SaveSemanticBaseline ? ".save.txt" : ".use.txt"); var fileLogger = new FileLogger(); fileLogger.Parameters = "logfile=" + Path.Combine(this.SourceDirectory, logFileName); fileLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var consoleLogger = new ConsoleLogger(); consoleLogger.Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Normal; var overallLoggers = new[] { fileLogger, consoleLogger }; // with this version, loggers don't work (log files are created but empty), why? var loggers = new FileLogger[0]; using (var projectCollection = new ProjectCollection(globalProperties, loggers, ToolsetDefinitionLocations.Registry)) { // The only way to communicate to msbuild is to create an xml file, and pass it to msbuild XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build")); var properties = ""; foreach (var projectPath in ProjectsPath) { Contract.Assert(projectPath != null); xmlTarget.Add(new XElement(ns + "MSBuild", new XAttribute("Projects", Path.Combine(this.SourceDirectory, projectPath)), new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?) new XAttribute("UseResultsCache", "false"), new XAttribute("UnloadProjectsOnCompletion", "true"), new XAttribute("ContinueOnError", "true"), new XAttribute("StopOnFirstFailure", "false"), new XAttribute("Properties", properties))); } // create the project var xmlProject = new XElement(ns + "Project", xmlTarget); // now read the project var project = projectCollection.LoadProject(xmlProject.CreateReader()); // create an instance of the project var projectInstance = project.CreateProjectInstance(); // create the parameters for the build var buildParameters = new BuildParameters(projectCollection); buildParameters.EnableNodeReuse = false; buildParameters.ResetCaches = true; buildParameters.Loggers = overallLoggers; buildParameters.MaxNodeCount = Environment.ProcessorCount; // Ask a build on this project var buildRequestData = new BuildRequestData(projectInstance, new string[] { "Build" }); // we need to create a new BuildManager each time, otherwise it wrongly caches project files var buildManager = new BuildManager(); // now do the build! var buildResult = buildManager.Build(buildParameters, buildRequestData); ret = buildResult.OverallResult == BuildResultCode.Success; #if WITH_LOG logger.Shutdown(); #endif // now cleanup - it seems it does not improve projectCollection.UnregisterAllLoggers(); projectCollection.UnloadAllProjects(); } #region Version using the default BuildManager (disabled) #if false // First version. It does not work, because msbuild keeps a cache of the projects, and so it compiles the new files with the old project // The Log works Microsoft.Build.Execution.BuildManager.DefaultBuildManager.ResetCaches(); // ensures MSBuild doesn't use cached version of project files (it handles very badly versions changing!), not sure it works XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003"; var xmlTarget = new XElement(ns + "Target", new XAttribute("Name", "Build")); var properties = ""; properties += ";CodeContractsCacheDirectory=" + OutputDirectory; properties += ";CodeContractsCacheAnalysisResults=true"; properties += ";CodeContractsCacheVersion=" + VersionId; foreach (var projectPath in ProjectsPath) { Contract.Assume(projectPath != null); xmlTarget.Add(new XElement(ns + "MSBuild", new XAttribute("Projects", Path.Combine(this.WorkingDirectory, projectPath)), new XAttribute("Targets", "Rebuild"), // ensures the project will be rebuilt from scratch (is it needed?) new XAttribute("UseResultsCache", "false"), new XAttribute("UnloadProjectsOnCompletion", "true"), new XAttribute("ContinueOnError", "true"), new XAttribute("StopOnFirstFailure", "false"), new XAttribute("Properties", properties))); } var xmlProject = new XElement(ns + "Project", xmlTarget); var project = new Project(xmlProject.CreateReader()); var logFileName = "build." + VersionId + ".log"; var logger = new Microsoft.Build.Logging.FileLogger(); logger.Parameters = "logfile=" + Path.Combine(OutputDirectory, logFileName); ret = project.Build(logger); #endif #endregion } catch { ret = false; } return(ret); }
// 打包, 即复制到文件 private void button_CopyToFile_Click(object sender, System.EventArgs e) { int nRet; // 当前已选择的node if (treeView1.SelectedNode == null) { MessageBox.Show(this, "尚未选择方案或者目录"); return; } TreeNode node = treeView1.SelectedNode; if (node.ImageIndex == 0) // 目录 { } else { string strProjectNamePath = node.FullPath; string strLocate = ""; // 获得方案参数 // strProjectNamePath 方案名,或者路径 // return: // -1 error // 0 not found project // 1 found nRet = scriptManager.GetProjectData( strProjectNamePath, out strLocate); if (nRet != 1) { MessageBox.Show(this, "方案 " + strProjectNamePath + " 在ScriptManager中没有找到"); return; } string strPath; string strName; // 从完整的方案"名字路径"中,析出路径和名 ScriptManager.SplitProjectPathName(strProjectNamePath, out strPath, out strName); Project project = null; try { project = Project.MakeProject( strProjectNamePath, strLocate); } catch (Exception ex) { MessageBox.Show(this, "MakeProject error : " + ex.Message); return; } // 目前还允许host参数为空,这样软件不会加以检查 string strHostName = project.GetHostName(); if (string.IsNullOrEmpty(strHostName) == false && strHostName != this.HostName) { string strError = "拟导出的方案其(在metadata.xml定义的)宿主名为 '" + GetHostNameCaption(strHostName) + "', 不符合当前窗口的宿主名 '" + GetHostNameCaption(this.HostName) + "'。拒绝导出"; MessageBox.Show(this, strError); return; } // 询问包文件全路径 SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = "导出方案 -- 请指定要保存的文件名"; dlg.CreatePrompt = true; dlg.FileName = strName + ".projpack"; dlg.InitialDirectory = strRecentPackageFilePath == "" ? Environment.GetFolderPath(Environment.SpecialFolder.Personal) : strRecentPackageFilePath; //Environment.CurrentDirectory; dlg.Filter = "方案打包文件 (*.projpack)|*.projpack|All files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() != DialogResult.OK) { return; } strRecentPackageFilePath = dlg.FileName; // Clipboard.SetDataObject(project); ProjectCollection array = new ProjectCollection(); array.Add(project); /// //Opens a file and serializes the object into it in binary format. using (Stream stream = File.Open(dlg.FileName, FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, array); } } }
/// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(HostServices hostServices, IDictionary <string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { string toolsVersionSubstring = toolsVersion != null ? "ToolsVersion=\"" + toolsVersion + "\" " : String.Empty; string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' InitialTargets='it' DefaultTargets='dt' " + toolsVersionSubstring + @"> <PropertyGroup> <p1>v1</p1> <p2>v2</p2> <p2>$(p2)X$(p)</p2> </PropertyGroup> <ItemGroup> <i Include='i0'/> <i Include='i1'> <m>m1</m> </i> <i Include='$(p1)'/> </ItemGroup> <Target Name='t'> <t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/> <t2/> </Target> <Target Name='tt'/> </Project> "; ProjectInstance p = GetProjectInstance(content, hostServices, globalProperties, projectCollection, toolsVersion); return(p); }
public string GetActiveWorkspace(ProjectCollection collection) { if (!_activeWorkspaces.ContainsKey(collection.Id)) return string.Empty; return _activeWorkspaces[collection.Id]; }
private MsbuildProject(ProjectCollection projects, ProjectRootElement project) { _projects = projects; ProjectRootElement = project; ProjectDirectory = PathUtility.EnsureTrailingSlash(ProjectRootElement.DirectoryPath); }
public void SetActiveWorkspace(ProjectCollection collection, string workspaceName) { _activeWorkspaces[collection.Id] = workspaceName; StorePrefs(); }
internal static Task <List <T> > LoadAllFromDirectoryAsync <T>(string path, string includedPathFilter, string excludedPathFilter, bool ignoreExceptions, ProjectCollection projectCollection, string extension, Func <string, ProjectCollection, T> creator, Dictionary <string, Exception> errors) { var includedPathFilterTerms = includedPathFilter.ToLowerInvariant().Split(' ').Where(t => !string.IsNullOrEmpty(t)).ToArray(); var excludedPathFilterTerms = excludedPathFilter.ToLowerInvariant().Split(' ').Where(t => !string.IsNullOrEmpty(t)).ToArray(); return(Task.Run(async() => { var tasks = new List <Task <T> >(); var projects = new List <T>(); try { var files = GetFiles(path, "*" + extension); foreach (var file in files.Distinct().Where(s => includedPathFilterTerms.All(t => s.ToLowerInvariant().Contains(t)) && excludedPathFilterTerms.All(t => !s.ToLowerInvariant().Contains(t)))) { var ext = System.IO.Path.GetExtension(file); if (ext != null && ext.ToLower() == extension) { var lFile = file; tasks.Add(Task.Run(() => { try { return creator(lFile, projectCollection); } catch (Exception exception) { if (!ignoreExceptions) { throw; } if (errors != null) { errors[lFile] = exception; } } return default(T); })); } } await Task.WhenAll(tasks); foreach (var task in tasks.Where(t => t.Result != null)) { projects.Add(task.Result); } } catch (Exception exception) { if (!ignoreExceptions) { throw; } if (errors != null) { errors[path] = exception; } } return projects; })); }
string ITaskItem2.GetMetadataValueEscaped(string metadataName) { return(ProjectCollection.Escape(GetMetadataValue(metadataName))); }
private MsbuildProject LoadMsbuildProject() { var collection = new ProjectCollection(); return(MsbuildProject.FromFile(collection, ProjectFileAbsolutePath)); }
void ITaskItem.SetMetadata(string metadataName, string metadataValue) { SetMetadata(metadataName, ProjectCollection.Unescape(metadataValue)); }
public override int Run(string fileOrDirectory) { var projects = new ProjectCollection(); MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(projects, fileOrDirectory); if (RemainingArguments.Count == 0) { throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneReferenceToAdd); } string frameworkString = _frameworkOption.Value(); PathUtility.EnsureAllPathsExist(RemainingArguments, CommonLocalizableStrings.ReferenceDoesNotExist); List <MsbuildProject> refs = RemainingArguments .Select((r) => MsbuildProject.FromFile(projects, r)) .ToList(); if (frameworkString == null) { foreach (var tfm in msbuildProj.GetTargetFrameworks()) { foreach (var @ref in refs) { if ([email protected](tfm)) { Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString( @ref, msbuildProj.GetTargetFrameworks().Select((fx) => fx.GetShortFolderName()))); return(1); } } } } else { var framework = NuGetFramework.Parse(frameworkString); if (!msbuildProj.IsTargettingFramework(framework)) { Reporter.Error.WriteLine(string.Format( CommonLocalizableStrings.ProjectDoesNotTargetFramework, msbuildProj.ProjectRootElement.FullPath, frameworkString)); return(1); } foreach (var @ref in refs) { if ([email protected](framework)) { Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString( @ref, new string[] { frameworkString })); return(1); } } } var relativePathReferences = RemainingArguments.Select((r) => PathUtility.GetRelativePath(msbuildProj.ProjectDirectory, Path.GetFullPath(r))).ToList(); int numberOfAddedReferences = msbuildProj.AddProjectToProjectReferences( _frameworkOption.Value(), relativePathReferences); if (numberOfAddedReferences != 0) { msbuildProj.ProjectRootElement.Save(); } return(0); }
private ProjectInstance ProjectInstanceFactory(string projectFile, Dictionary <string, string> globalProperties, ProjectCollection projectCollection) { Invoke(new Action(() => _statusBarLabel.Text = $@"Loading {projectFile}...")); var sw = Stopwatch.StartNew(); var pi = new ProjectInstance( projectFile, globalProperties, "Current", projectCollection); sw.Stop(); Invoke(new Action(() => _statusBarLabel.Text = $@"Loading {projectFile}. Done in {sw.ElapsedMilliseconds}ms")); return(pi); }
private static void EvaluateProject(OutputContext output, ProjectServiceBuilder project) { var sw = Stopwatch.StartNew(); // We need to isolate projects from each other for testing. MSBuild does not support // loading the same project twice in the same collection. var projectCollection = new ProjectCollection(); ProjectInstance projectInstance; try { output.WriteDebugLine($"Loading project '{project.ProjectFile.FullName}'."); var msbuildProject = Microsoft.Build.Evaluation.Project.FromFile(project.ProjectFile.FullName, new ProjectOptions() { ProjectCollection = projectCollection, }); projectInstance = msbuildProject.CreateProjectInstance(); output.WriteDebugLine($"Loaded project '{project.ProjectFile.FullName}'."); } catch (Exception ex) { throw new CommandException($"Failed to load project: '{project.ProjectFile.FullName}'.", ex); } // Currently we only log at debug level. var logger = new ConsoleLogger( verbosity: LoggerVerbosity.Normal, write: message => output.WriteDebug(message), colorSet: null, colorReset: null); try { AssemblyLoadContext.Default.Resolving += ResolveAssembly; var result = projectInstance.Build( targets: new[] { "Restore", "ResolveReferences", "ResolvePackageDependenciesDesignTime", "PrepareResources", "GetAssemblyAttributes", }, loggers: new[] { logger, }); // If the build fails, we're not really blocked from doing our work. // For now we just log the output to debug. There are errors that occur during // running these targets we don't really care as long as we get the data. } finally { AssemblyLoadContext.Default.Resolving -= ResolveAssembly; } // Reading both InformationalVersion and Version is more resilient in the face of build failures. var version = projectInstance.GetProperty("InformationalVersion")?.EvaluatedValue ?? projectInstance.GetProperty("Version").EvaluatedValue; project.Version = version; output.WriteDebugLine($"Found application version: {version}"); var targetFrameworks = projectInstance.GetPropertyValue("TargetFrameworks"); project.TargetFrameworks = targetFrameworks.Split(';', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty <string>(); project.RunCommand = projectInstance.GetPropertyValue("RunCommand"); project.RunArguments = projectInstance.GetPropertyValue("RunArguments"); project.TargetPath = projectInstance.GetPropertyValue("TargetPath"); project.PublishDir = projectInstance.GetPropertyValue("PublishDir"); project.AssemblyName = projectInstance.GetPropertyValue("AssemblyName"); project.IntermediateOutputPath = projectInstance.GetPropertyValue("IntermediateOutputPath"); output.WriteDebugLine($"RunCommand={project.RunCommand}"); output.WriteDebugLine($"RunArguments={project.RunArguments}"); output.WriteDebugLine($"TargetPath={project.TargetPath}"); output.WriteDebugLine($"PublishDir={project.PublishDir}"); output.WriteDebugLine($"AssemblyName={project.AssemblyName}"); output.WriteDebugLine($"IntermediateOutputPath={project.IntermediateOutputPath}"); // Normalize directories to their absolute paths project.IntermediateOutputPath = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.IntermediateOutputPath)); project.TargetPath = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.TargetPath)); project.PublishDir = Path.Combine(project.ProjectFile.DirectoryName, NormalizePath(project.PublishDir)); var targetFramework = projectInstance.GetPropertyValue("TargetFramework"); project.TargetFramework = targetFramework; output.WriteDebugLine($"Found target framework: {targetFramework}"); // TODO: Parse the name and version manually out of the TargetFramework field if it's non-null project.TargetFrameworkName = projectInstance.GetPropertyValue("_ShortFrameworkIdentifier"); project.TargetFrameworkVersion = projectInstance.GetPropertyValue("_ShortFrameworkVersion") ?? projectInstance.GetPropertyValue("_TargetFrameworkVersionWithoutV"); var sharedFrameworks = projectInstance.GetItems("FrameworkReference").Select(i => i.EvaluatedInclude).ToList(); project.Frameworks.AddRange(sharedFrameworks.Select(s => new Framework(s))); output.WriteDebugLine($"Found shared frameworks: {string.Join(", ", sharedFrameworks)}"); project.IsAspNet = project.Frameworks.Any(f => f.Name == "Microsoft.AspNetCore.App") || projectInstance.GetPropertyValue("MicrosoftNETPlatformLibrary") == "Microsoft.AspNetCore.App" || projectInstance.GetPropertyValue("_AspNetCoreAppSharedFxIsEnabled") is string s && !string.IsNullOrEmpty(s) && bool.Parse(s); output.WriteDebugLine($"Evaluation Took: {sw.Elapsed.TotalMilliseconds}ms"); // The Microsoft.Build.Locator doesn't handle the loading of other assemblies // that are shipped with MSBuild (ex NuGet). // // This means that the set of assemblies that need special handling depends on the targets // that we run :( // // This is workaround for this limitation based on the targets we need to run // to resolve references and versions. // // See: https://github.com/microsoft/MSBuildLocator/issues/86 Assembly?ResolveAssembly(AssemblyLoadContext context, AssemblyName assemblyName) { if (assemblyName.Name is object && assemblyName.Name.StartsWith("NuGet.")) { var msbuildDirectory = Environment.GetEnvironmentVariable("MSBuildExtensionsPath") !; var assemblyFilePath = Path.Combine(msbuildDirectory, assemblyName.Name + ".dll"); if (File.Exists(assemblyFilePath)) { return(context.LoadFromAssemblyPath(assemblyFilePath)); } } return(default);
/// <summary> /// Gets the unescaped, unevaluated value. /// </summary> /// <exception cref="ArgumentNullException"> /// <paramref name="element"/> is <see langword="null" />. /// </exception> public static string GetUnescapedValue(this ProjectPropertyElement element) { Requires.NotNull(element, nameof(element)); return(ProjectCollection.Unescape(element.Value)); }
public ProjectCollectionTest() { _projects = new ProjectCollection(); }
string [] GetDefaultTargets(ProjectRootElement xml, bool fromAttribute, bool checkImports) { if (fromAttribute) { var ret = xml.DefaultTargets.Split(item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); if (checkImports && ret.Length == 0) { foreach (var imp in this.raw_imports) { ret = GetDefaultTargets(imp.ImportedProject, true, false); if (ret.Any()) { break; } } } return(ret); } else { if (xml.Targets.Any()) { return new String [] { xml.Targets.First().Name } } ; if (checkImports) { foreach (var imp in this.raw_imports) { var ret = GetDefaultTargets(imp.ImportedProject, false, false); if (ret.Any()) { return(ret); } } } return(new string [0]); } } void InitializeProperties(ProjectRootElement xml) { location = xml.Location; full_path = xml.FullPath; directory = string.IsNullOrWhiteSpace(xml.DirectoryPath) ? System.IO.Directory.GetCurrentDirectory() : xml.DirectoryPath; InitialTargets = xml.InitialTargets.Split(item_target_sep, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList(); raw_imports = new List <ResolvedImport> (); item_definitions = new Dictionary <string, ProjectItemDefinitionInstance> (); targets = new Dictionary <string, ProjectTargetInstance> (); raw_items = new List <ProjectItemInstance> (); properties = new Dictionary <string, ProjectPropertyInstance> (); foreach (DictionaryEntry p in Environment.GetEnvironmentVariables()) { // FIXME: this is kind of workaround for unavoidable issue that PLATFORM=* is actually given // on some platforms and that prevents setting default "PLATFORM=AnyCPU" property. if (!string.Equals("PLATFORM", (string)p.Key, StringComparison.OrdinalIgnoreCase)) { this.properties [(string)p.Key] = new ProjectPropertyInstance((string)p.Key, true, (string)p.Value); } } foreach (var p in global_properties) { this.properties [p.Key] = new ProjectPropertyInstance(p.Key, false, p.Value); } var tools = projects.GetToolset(tools_version) ?? projects.GetToolset(projects.DefaultToolsVersion); foreach (var p in projects.GetReservedProperties(tools, this, xml)) { this.properties [p.Name] = p; } foreach (var p in ProjectCollection.GetWellKnownProperties(this)) { this.properties [p.Name] = p; } ProcessXml(xml); DefaultTargets = GetDefaultTargets(xml).ToList(); }
public void ImportFromExtensionsPathAnd32And64() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn{0}' DependsOnTargets='{1}'> <Message Text='Running FromExtn{0}'/> </Target> {2} </Project> "; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value=""" + /*v4Folder*/ "." + @"""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""{0}"" /> <property name=""MSBuildExtensionsPath32"" value=""{1}"" /> <property name=""MSBuildExtensionsPath64"" value=""{2}"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null, extnDir2 = null, extnDir3 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />")); extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"), String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />")); extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"), String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty)); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); var configFilePath = ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3)); var reader = GetStandardConfigurationReader(); var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(reader); var logger = new MockLogger(); projColln.RegisterLogger(logger); var project = projColln.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn3"); logger.AssertLogContains("Running FromExtn2"); logger.AssertLogContains("Running FromExtn"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } if (extnDir2 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true); } if (extnDir3 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true); } } }
internal IEnumerable <T> GetAllItems <T> (string include, string exclude, Func <string, T> creator, Func <string, ITaskItem> taskItemCreator, Func <string, bool> itemTypeCheck, Action <T, string> assignRecurse) { return(ProjectCollection.GetAllItems <T> (ExpandString, include, exclude, creator, taskItemCreator, Directory, assignRecurse, t => all_evaluated_items.Any(i => i.EvaluatedInclude == t.ItemSpec && itemTypeCheck(i.ItemType)))); }
public void FallbackImportWithUndefinedProperty() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" /> <Target Name='Main' DependsOnTargets='FromExtn' /> </Project>"; string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary <string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); var project = projectCollection.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } }
public static string GetEvaluatedItemIncludeEscaped(ProjectItemInstance item) { return(ProjectCollection.Escape(item.EvaluatedInclude)); }
public static List<Workspace> GetLocalWorkspaces(ProjectCollection collection) { var versionControl = collection.GetService<RepositoryService>(); return versionControl.QueryWorkspaces(collection.Server.UserName, Environment.MachineName); }
public static string GetMetadataValueEscaped(ProjectMetadataInstance metadatum) { return(ProjectCollection.Escape(metadatum.EvaluatedValue)); }
public static Workspace GetWorkspace(ProjectCollection collection, string name) { var versionControl = collection.GetService<RepositoryService>(); return versionControl.QueryWorkspace(collection.Server.UserName, name); }
/// <summary> /// Class is implemented as a singleton, a private constructor is desired /// </summary> private ApplicationManager() { this.moduleCollection = new List<IModule>(); this.projectCollection = new ProjectCollection(); this.services = new ServiceContainer(); }