Beispiel #1
1
        private void AddReference(InputProjectDriver inputProjectDriver, Project project, string reference)
        {
            string referenceFullPath = Path.GetFullPath(Path.Combine(AssemblyFolderHelper.GetTestAssemblyFolder(), reference));
            string assemblyName = Path.GetFileNameWithoutExtension(referenceFullPath);
            Debug.Assert(assemblyName != null);

            project.AddItem("Reference", assemblyName, new[]
                                                           {
                                                               new KeyValuePair<string, string>("HintPath", referenceFullPath),
                                                           });
        }
Beispiel #2
0
        public void ProjectGetter()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];

            Assert.Equal(true, Object.ReferenceEquals(project, item.Project));
        }
 public static ProjectItem ThreadSafeAdd(this Microsoft.Build.Evaluation.Project thisp, string itemType, string unevaluatedInclude)
 {
     lock (thisp)
     {
         return(thisp.AddItem(itemType, unevaluatedInclude).First());
     }
 }
        /// <summary>
        /// Creates a temporary MSBuild content project in memory.
        /// </summary>
        void CreateBuildProject()
        {
            string projectPath = Path.Combine(buildDirectory, "content.contentproj");
            string outputPath  = Path.Combine(buildDirectory, "bin");

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

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

            buildProject = new Microsoft.Build.Evaluation.Project(projectRootElement);

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

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

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

            buildParameters         = new BuildParameters(ProjectCollection.GlobalProjectCollection);
            buildParameters.Loggers = new ILogger[] { errorLogger };
        }
Beispiel #5
0
		public static MSbuildResult BuildProject(MsBuildSettings settings, string projectFileName, DirectoryInfo dir)
		{
			var result = new MSbuildResult();
			var path = Path.Combine(dir.FullName, projectFileName);
			var project = new Project(path, null, null, new ProjectCollection());
			project.SetProperty("CscToolPath", settings.CompilerDirectory.FullName);
			var includes = new HashSet<string>(
				project.AllEvaluatedItems
				.Where(i => i.ItemType == "None" || i.ItemType == "Content")
				.Select(i => Path.GetFileName(i.EvaluatedInclude.ToLowerInvariant())));
			foreach (var dll in settings.WellKnownLibsDirectory.GetFiles("*.dll"))
				if (!includes.Contains(dll.Name.ToLowerInvariant()))
					project.AddItem("None", dll.FullName);
			project.Save();
			using (var stringWriter = new StringWriter())
			{
				var logger = new ConsoleLogger(LoggerVerbosity.Minimal, stringWriter.Write, color => { }, () => { });
				result.Success = SyncBuild(project, logger);
				if (result.Success)
					result.PathToExe = Path.Combine(project.DirectoryPath,
													project.GetPropertyValue("OutputPath"),
													project.GetPropertyValue("AssemblyName") + ".exe");
				else
					result.ErrorMessage = stringWriter.ToString();
				return result;
			}
		}
        void CreateBuildProject()
        {
            string projectPath = Path.Combine(buildDirectory, "content.contentproj");
            string outputPath = Path.Combine(buildDirectory, "bin");

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

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

            buildProject = new Project(projectRootElement);

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

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

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

            buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection)
                                  {Loggers = new ILogger[] {errorLogger}};
        }
        public void ProjectGetter()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            ProjectMetadata metadatum = item.SetMetadataValue("m", "m1");

            Assert.AreEqual(true, Object.ReferenceEquals(project, metadatum.Project));
        }
		public static void IncludeFileInCurrentProject(string approved)
		{
			var p = new Project(GetCurrentProjectFile(approved));
			if (!p.Items.Any(i => approved.EndsWith(i.UnevaluatedInclude)))
			{
				p.AddItem("Content", approved);
				p.Save();
			}
		}
Beispiel #9
0
 /// <summary>
 /// Checks if the same item already exists and only adds it to the project if it doesn't.
 /// </summary>
 /// <param name="project">The project to add the item to.</param>
 /// <param name="itemType">The item type of the added item.</param>
 /// <param name="unevaluatedInclude">Include attribute of the item to be added.</param>
 public static bool AddItemIfNotAlready(this Microsoft.Build.Evaluation.Project project, string itemType, string unevaluatedInclude)
 {
     if (project.Items.FirstOrDefault(i => i.EvaluatedInclude == unevaluatedInclude) != null)
     {
         return(false);
     }
     project.AddItem(itemType, unevaluatedInclude);
     return(true);
 }
Beispiel #10
0
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            var filename = Path.Combine(project.DirectoryPath, Name);

            File.WriteAllText(filename, Content);

            if (!IsExcluded)
            {
                project.AddItem("Content", Name);
            }
        }
Beispiel #11
0
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            if (!IsMissing)
            {
                Directory.CreateDirectory(Path.Combine(project.DirectoryPath, Name));
            }

            if (!IsExcluded)
            {
                project.AddItem("Folder", Name);
            }
        }
Beispiel #12
0
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            if (!IsMissing)
            {
                var absName          = Path.IsPathRooted(Name) ? Name : Path.Combine(project.DirectoryPath, Name);
                var absReferencePath = Path.IsPathRooted(ReferencePath) ? ReferencePath : Path.Combine(project.DirectoryPath, ReferencePath);

                NativeMethods.CreateSymbolicLink(absName, absReferencePath);
            }

            if (!IsExcluded)
            {
                project.AddItem("Folder", Name);
            }
        }
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project();
            var metadata = new Dictionary <string, string>
            {
                { "EscapedSemicolon", "%3B" },  // Microsoft.Build.Internal.Utilities.Escape(";")
                { "EscapedDollarSign", "%24" }, // Microsoft.Build.Internal.Utilities.Escape("$")
            };

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

            SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            SpecialCharactersInMetadataValueTests(item);
        }
        /// <summary>
        /// Adds a new content file to the MSBuild project. The importer and
        /// processor are optional: if you leave the importer null, it will
        /// be autodetected based on the file extension, and if you leave the
        /// processor null, data will be passed through without any processing.
        /// </summary>
        /// <param name="filename">Content file.</param>
        /// <param name="name">Name of the compiled content.</param>
        /// <param name="importer">Importer to use.</param>
        /// <param name="processor">Processor to use.</param>
        public void Add(string filename, string name, string importer, string processor)
        {
            ProjectItem item = buildProject.AddItem("Compile", filename)[0];

            item.SetMetadataValue("Link", Path.GetFileName(filename));
            item.SetMetadataValue("Name", name);

            if (!string.IsNullOrEmpty(importer))
            {
                item.SetMetadataValue("Importer", importer);
            }

            if (!string.IsNullOrEmpty(processor))
            {
                item.SetMetadataValue("Processor", processor);
            }

            projectItems.Add(item);
        }
Beispiel #15
0
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            if (!IsMissing)
            {
                var absName          = Path.IsPathRooted(Name) ? Name : Path.Combine(project.DirectoryPath, Name);
                var absReferencePath = Path.IsPathRooted(ReferencePath) ? ReferencePath : Path.Combine(project.DirectoryPath, ReferencePath);

                try {
                    NativeMethods.CreateSymbolicLink(absName, absReferencePath);
                } catch (UnauthorizedAccessException ex) {
                    Assert.Inconclusive(ex.Message);
                }
            }

            if (!IsExcluded)
            {
                project.AddItem("Folder", Name);
            }
        }
        public void LinkToFile(Project project, BuildAction buildAction, string includeValue, string projectTargetPath)
        {
            if(projectTargetPath.StartsWith("\\"))
                throw new Exception("project target path cannot begin with a backslash");

            var matchingProjectItemByTargetPath = (from t in project.Items
                                                   where
                                                       t.HasMetadata("Link") &&
                                                       t.GetMetadataValue("Link") == projectTargetPath
                                                   select t).SingleOrDefault();

            if (matchingProjectItemByTargetPath != null) 
                project.RemoveItem(matchingProjectItemByTargetPath);

            var buildActionName = Enum.GetName(typeof(BuildAction), buildAction);

            project.AddItem(buildActionName, includeValue,
                            new[] {new KeyValuePair<string, string>("Link", projectTargetPath)});
        }
        public void AddItem_EscapedItemInclude()
        {
            Project project = new Project();

            project.AddItem("i", "i%281%29");

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""i%281%29"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project.Xml);

            List<ProjectItem> items = Helpers.MakeList(project.Items);
            Assert.Equal(1, items.Count);
            Assert.Equal("i", items[0].ItemType);
            Assert.Equal("i(1)", items[0].EvaluatedInclude);
            Assert.Equal("i(1)", Helpers.GetFirst(project.GetItems("i")).EvaluatedInclude);
            Assert.Equal("i(1)", Helpers.MakeList(project.CreateProjectInstance().GetItems("i"))[0].EvaluatedInclude);
        }
Beispiel #18
0
 int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen,
                        string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult)
 {
     if (Directory.Exists(rgpszFilesToOpen[0]))
     {
         AddProject(new MockVsHierarchy(rgpszFilesToOpen[0], this));
     }
     else
     {
         Children.Add(rgpszFilesToOpen[0]);
         if (_project != null)
         {
             FileInfo itemFileInfo = new FileInfo(rgpszFilesToOpen[0]);
             _project.Save(FileName);
             FileInfo projectFileInfo = new FileInfo(_project.ProjectFileLocation.File);
             string   itemName        = itemFileInfo.FullName.Substring(projectFileInfo.Directory.FullName.Length + 1);
             _project.AddItem("Compile", itemName);
             _project.Save(FileName);
         }
     }
     return(VSConstants.S_OK);
 }
Beispiel #19
0
        public static void AddProjectFiles(FilePath ProjectFile, IReadOnlyList <FilePath> files, bool build = false)
        {
            var project       = new MSEV.Project(ProjectFile);
            var projectFolder = ProjectFile.Folder;

            foreach (var file in files)
            {
                var itemType     = StandardItemTypes.InferItemType(file.FileName);
                var relativePath = file.Value.Replace(projectFolder.FullPath, String.Empty);
                if (relativePath.StartsWith("\\"))
                {
                    relativePath = relativePath.Substring(1);
                }

                project.AddItem(itemType, relativePath);
            }
            project.Save();
            if (build)
            {
                project.Build();
            }
        }
Beispiel #20
0
        public override void Generate(ProjectType projectType, MSBuild.Project project)
        {
            var filename = Path.Combine(project.DirectoryPath, Name + projectType.CodeExtension);

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

            if (!IsExcluded)
            {
                List <KeyValuePair <string, string> > metadata = new List <KeyValuePair <string, string> >();
                if (LinkFile != null)
                {
                    metadata.Add(new KeyValuePair <string, string>("Link", LinkFile + projectType.CodeExtension));
                }

                project.AddItem(
                    "Compile",
                    Name + projectType.CodeExtension,
                    metadata
                    );
            }
        }
        private void ToolStripButton3_Click(object sender, EventArgs e)
        {
            TreeNode node = treeView1.SelectedNode;

            if (node.ImageIndex == PROJECT || node.ImageIndex == FOLDER || node.ImageIndex == FOLDER_OPEN)
            {
                string path =
                    _filePath.Replace(Path.DirectorySeparatorChar + Path.GetFileName(_filePath) ?? string.Empty, "");
                string replace = node.FullPath?.Replace(Path.GetFileName(_filePath) ?? string.Empty, "");
                string target  = path + replace.Replace("\\", Path.DirectorySeparatorChar.ToString());
                if (Directory.Exists(target))
                {
                    StringDialog dialog = new StringDialog((text) => !string.IsNullOrEmpty(text));
                    dialog.Description = "Create Directory Name";
                    dialog.ShowDialog();
                    if (dialog.DialogResult == DialogResult.OK)
                    {
                        string newDir = target + Path.DirectorySeparatorChar + dialog.ResultString;
                        if (!Directory.Exists(newDir))
                        {
                            Directory.CreateDirectory(newDir);
                            string  name = replace.Split(Path.DirectorySeparatorChar)[1];
                            Project proj = _projects[name];
                            proj.AddItem("Folder", newDir.Replace(path + "\\" + name + "\\", "") + "\\");
                            proj.Save();

                            LoadSolution(_solution, _filePath);
                        }
                        else
                        {
                            MessageBox.Show("Created Directory");
                        }
                    }
                }
            }
        }
        public void SetValueWithItemExpression()
        {
            Project project = new Project();
            project.AddItem("i", "i1");
            ProjectItem item = project.AddItem("j", "j1")[0];
            ProjectMetadata metadatum = item.SetMetadataValue("m", "@(i)");
            project.ReevaluateIfNecessary();

            metadatum.UnevaluatedValue = "@(i)";

            Assert.AreEqual("@(i)", metadatum.UnevaluatedValue);
            Assert.AreEqual("i1", metadatum.EvaluatedValue);
        }
Beispiel #23
0
        /// <summary>
        /// Adds the specified factory to the project. If the factory was
        /// created by this provider, it will be added as an Interpreter element
        /// with full details. If the factory was not created by this provider,
        /// it will be added as an InterpreterReference element with only the
        /// ID and version.
        /// </summary>
        /// <param name="factory">The factory to add.</param>
        public void AddInterpreter(IPythonInterpreterFactory factory, bool disposeInterpreter = false)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }

            if (_factories.ContainsKey(factory))
            {
                return;
            }

            MSBuild.ProjectItem item;

            var derived = factory as DerivedInterpreterFactory;

            if (derived != null)
            {
                var projectHome = CommonUtils.GetAbsoluteDirectoryPath(_project.DirectoryPath, _project.GetPropertyValue("ProjectHome"));
                var rootPath    = CommonUtils.EnsureEndSeparator(factory.Configuration.PrefixPath);
                _rootPaths[factory.Id] = rootPath;

                item = _project.AddItem(InterpreterItem,
                                        CommonUtils.GetRelativeDirectoryPath(projectHome, rootPath),
                                        new Dictionary <string, string> {
                    { IdKey, derived.Id.ToString("B") },
                    { BaseInterpreterKey, derived.BaseInterpreter.Id.ToString("B") },
                    { VersionKey, derived.BaseInterpreter.Configuration.Version.ToString() },
                    { DescriptionKey, derived.Description },
                    { InterpreterPathKey, CommonUtils.GetRelativeFilePath(rootPath, derived.Configuration.InterpreterPath) },
                    { WindowsPathKey, CommonUtils.GetRelativeFilePath(rootPath, derived.Configuration.WindowsInterpreterPath) },
                    { LibraryPathKey, CommonUtils.GetRelativeDirectoryPath(rootPath, derived.Configuration.LibraryPath) },
                    { PathEnvVarKey, derived.Configuration.PathEnvironmentVariable },
                    { ArchitectureKey, derived.Configuration.Architecture.ToString() }
                }).FirstOrDefault();
            }
            else if (_service.FindInterpreter(factory.Id, factory.Configuration.Version) != null)
            {
                // The interpreter exists globally, so add a reference.
                item = _project.AddItem(InterpreterReferenceItem,
                                        string.Format("{0:B}\\{1}", factory.Id, factory.Configuration.Version)
                                        ).FirstOrDefault();
            }
            else
            {
                // Can't find the interpreter anywhere else, so add its
                // configuration to the project file.
                var projectHome = CommonUtils.GetAbsoluteDirectoryPath(_project.DirectoryPath, _project.GetPropertyValue("ProjectHome"));
                var rootPath    = CommonUtils.EnsureEndSeparator(factory.Configuration.PrefixPath);

                item = _project.AddItem(InterpreterItem,
                                        CommonUtils.GetRelativeDirectoryPath(projectHome, rootPath),
                                        new Dictionary <string, string> {
                    { IdKey, factory.Id.ToString("B") },
                    { VersionKey, factory.Configuration.Version.ToString() },
                    { DescriptionKey, factory.Description },
                    { InterpreterPathKey, CommonUtils.GetRelativeFilePath(rootPath, factory.Configuration.InterpreterPath) },
                    { WindowsPathKey, CommonUtils.GetRelativeFilePath(rootPath, factory.Configuration.WindowsInterpreterPath) },
                    { LibraryPathKey, CommonUtils.GetRelativeDirectoryPath(rootPath, factory.Configuration.LibraryPath) },
                    { PathEnvVarKey, factory.Configuration.PathEnvironmentVariable },
                    { ArchitectureKey, factory.Configuration.Architecture.ToString() }
                }).FirstOrDefault();
            }

            lock (_factoriesLock) {
                _factories[factory] = new FactoryInfo(item, disposeInterpreter);
            }
            OnInterpreterFactoriesChanged();
            UpdateActiveInterpreter();
        }
        public void SettingItemExcludeDirties()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            project.ReevaluateIfNecessary();

            item.Xml.Exclude = "i1";
            project.ReevaluateIfNecessary();

            Assert.Equal(0, Helpers.MakeList(project.Items).Count);
        }
Beispiel #25
0
        public void ItemsByEvaluatedIncludeDirectAdd()
        {
            Project project = new Project();
            project.AddItem("i", "i1");

            List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1"));
            Assert.Equal(1, items.Count);
        }
        public void AddItemWithMetadata_DoesNotMatchWildcardWithNoMetadata()
        {
            Project project = new Project();
            ProjectItemElement item1 = project.Xml.AddItem("i", "*.xxx");
            project.ReevaluateIfNecessary();

            Dictionary<string, string> metadata = new Dictionary<string, string>() { { "m", "m1" } };
            ProjectItemElement item2 = project.AddItem("i", "i1.xxx", metadata)[0].Xml;

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" />
    <i Include=""i1.xxx"">
      <m>m1</m>
    </i>
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project();
            var metadata = new Dictionary<string, string>
            {
                { "EscapedSemicolon", "%3B" }, // Microsoft.Build.Internal.Utilities.Escape(";")
                { "EscapedDollarSign", "%24" }, // Microsoft.Build.Internal.Utilities.Escape("$")
            };
            Microsoft.Build.Evaluation.ProjectItem item = project.AddItem(
                "None",
                "MetadataTests",
                metadata).Single();

            SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            SpecialCharactersInMetadataValueTests(item);
        }
        public void NormalizePaths(bool addImports)
        {
            List <_BE.ProjectItem> removeItems = new List <_BE.ProjectItem>();

            foreach (_BE.ProjectItem folderItem in m_project.GetItems("Folder"))
            {
                string path = folderItem.Xml.Include;

                if (!path.Equals(GetRelativePath(path), StringComparison.OrdinalIgnoreCase))
                {
                    removeItems.Add(folderItem);
                    continue;
                }

                if (!Directory.Exists(path))
                {
                    removeItems.Add(folderItem);
                    continue;
                }
            }

            foreach (string groupName in ProjectEx.FileGroups)
            {
                List <MyImportItems> importItems = new List <MyImportItems>();
                foreach (_BE.ProjectItem buildItem in m_project.GetItems(groupName))
                {
                    string projectRelativePath = GetRelativePath(buildItem.Xml.Include);

                    // The path has to be an absolute path to somewhere
                    // outside the project directory.
                    if (projectRelativePath == null)
                    {
                        string origPath = Path.Combine(Path.GetDirectoryName(m_origProjPath), buildItem.EvaluatedInclude);
                        if (File.Exists(origPath))
                        {
                            projectRelativePath = buildItem.Xml.Include;
                            externalFiles.Add(buildItem.Xml.Include, origPath);
                        }
                        else if (File.Exists(BuildTaskUtility.ExpandEnvironmentVariables(buildItem.Xml.Include)))
                        {
                            projectRelativePath = Path.GetFileName(buildItem.Xml.Include);
                            externalFiles.Add(
                                projectRelativePath,
                                BuildTaskUtility.ExpandEnvironmentVariables(buildItem.Xml.Include));
                        }
                        else if (!buildItem.IsImported)
                        {
                            // since the file doesn't even exist
                            // remove it from the project
                            removeItems.Add(buildItem);
                            continue;
                        }
                        else
                        {
                            // This is an imported item
                            // it can't be removed, so
                            // ignore it.
                            if (Task != null)
                            {
                                Task.Log.LogWarning("Ignoring missing imported build item, \"{0}, {1}\"", buildItem.ItemType, buildItem.Xml.Include);
                            }
                            continue;
                        }
                    }

                    if (!buildItem.IsImported)
                    {
                        // Reset the path to the file relative to
                        // the project
                        buildItem.Xml.Include = projectRelativePath;
                    }
                    else if (addImports)
                    {
                        MyImportItems newItem = new MyImportItems();
                        newItem.name    = buildItem.ItemType;
                        newItem.include = projectRelativePath;
                        newItem.meta    = new Dictionary <string, string>();

                        foreach (_BE.ProjectMetadata meta in buildItem.Metadata)
                        {
                            newItem.meta.Add(meta.Name, meta.UnevaluatedValue);
                        }
                        importItems.Add(newItem);
                    }
                }

                foreach (MyImportItems importItem in importItems)
                {
                    m_project.AddItem(importItem.name, importItem.include, importItem.meta);
                }
            }

            foreach (_BE.ProjectItem removeItem in removeItems)
            {
                Task.Log.LogWarning("Removing missing build item, \"{0}, {1}\"", removeItem.ItemType, removeItem.Xml.Include);
                m_project.RemoveItem(removeItem);
            }
        }
        public void AddItem_DoesntMatchComplicatedWildcard()
        {
            Project project = new Project();
            ProjectItemElement item1 = project.Xml.AddItem("i", @"c:\subdir1\**\subdir2\**\*.x?x");
            project.ReevaluateIfNecessary();

            ProjectItemElement item2 = project.AddItem("i", @"c:\subdir1\a\b\c\i1.xyx")[0].Xml;

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""c:\subdir1\**\subdir2\**\*.x?x"" />
    <i Include=""c:\subdir1\a\b\c\i1.xyx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
            Assert.Equal(false, Object.ReferenceEquals(item1, item2));
        }
        public void SpecialCharactersInMetadataValueEvaluation()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("None", "MetadataTests", new Dictionary<string, string> {
                {"EscapedSemicolon", "%3B"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape(";")
                {"EscapedDollarSign", "%24"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape("$")
            }).Single();

            EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
            project.ReevaluateIfNecessary();
            EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
        }
        public void AddItem_MatchesWildcardWithCondition()
        {
            Project project = new Project();
            ProjectItemElement itemElement = project.Xml.AddItem("i", "*.xxx");
            itemElement.Condition = "true";
            project.ReevaluateIfNecessary();

            project.AddItem("i", "i1.xxx");

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" Condition=""true"" />
    <i Include=""i1.xxx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }
        public void AddItem_ContainingSemicolonExistingWildcard()
        {
            Project project = new Project();
            project.Xml.AddItem("i", "*.xxx");
            project.ReevaluateIfNecessary();

            project.AddItem("i", "i1.xxx;i2.xxx");

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" />
    <i Include=""i1.xxx;i2.xxx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }
Beispiel #33
0
 private static void ReplaceReference(Project project, ProjectItem item, string reference, string path)
 {
     project.RemoveItem(item);
     project.AddItem("Reference", reference, new[] { new KeyValuePair <string, string>("HintPath", Path.Combine(path, reference + ".dll")) });
 }
        public void AddItem_MatchesWildcardWithPropertyReference()
        {
            Project project = new Project();
            project.SetProperty("p", "xxx");
            project.Xml.AddItem("i", "a;*.$(p);b");
            project.ReevaluateIfNecessary();

            project.AddItem("i", "i1.xxx");

            string expected = ObjectModelHelpers.CleanupFileContents(
    @"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <PropertyGroup>
    <p>xxx</p>
  </PropertyGroup>
  <ItemGroup>
    <i Include=""a;*.$(p);b"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }
        public void IsImportedFalse()
        {
            Project project = new Project();
            ProjectMetadata metadata = project.AddItem("i", "i1")[0].SetMetadataValue("m", "m1");

            Assert.AreEqual(false, metadata.IsImported);
        }
        public void RenameItem_MatchesWildcard()
        {
            Project project = new Project();
            project.AddItem("i", "*.xxx");
            project.AddItem("i", "i1");
            project.ReevaluateIfNecessary();

            ProjectItem item = Helpers.GetLast(project.Items);
            item.Rename("i1.xxx");

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" />
    <i Include=""i1.xxx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }
        public void SetUnchangedValue()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            item.SetMetadataValue("m", "m1");
            project.ReevaluateIfNecessary();

            item.SetMetadataValue("m", "m1");

            Assert.AreEqual(false, project.IsDirty);

            item.GetMetadata("m").UnevaluatedValue = "m1";

            Assert.AreEqual(false, project.IsDirty);
        }
        public void RenameItem_NewNameContainsPropertyExpression()
        {
            Project project = new Project();
            project.SetProperty("p", "v1");
            project.AddItem("i", "i1");
            project.ReevaluateIfNecessary();

            ProjectItem item = Helpers.GetFirst(project.Items);

            item.Rename("$(p)");

            Assert.Equal("$(p)", item.UnevaluatedInclude);

            // Rename should have been expanded in this simple case
            Assert.Equal("v1", item.EvaluatedInclude);

            // The ProjectItemElement should be the same
            ProjectItemElement newItemElement = Helpers.GetFirst((Helpers.GetFirst(project.Xml.ItemGroups)).Items);
            Assert.Equal(true, Object.ReferenceEquals(item.Xml, newItemElement));
        }
Beispiel #39
0
        public void ItemsByEvaluatedIncludeDirectRemove()
        {
            Project project = new Project();
            ProjectItem item1 = project.AddItem("i", "i1;j1")[0];
            project.RemoveItem(item1);

            List<ProjectItem> items = Helpers.MakeList(project.GetItemsByEvaluatedInclude("i1"));
            Assert.Equal(0, items.Count);
        }
        public void RenameItem_NewNameContainsItemExpressionExpandingToTwoItems()
        {
            Project project = new Project();
            project.AddItem("h", "h1");
            project.AddItem("h", "h2");
            project.AddItem("i", "i1");
            project.ReevaluateIfNecessary();

            ProjectItem item = Helpers.GetLast(project.Items);

            item.Rename("@(h)");

            Assert.Equal("@(h)", item.UnevaluatedInclude);
            Assert.Equal("@(h)", item.EvaluatedInclude);

            // The ProjectItemElement should be the same
            ProjectItemElement newItemElement = Helpers.GetLast((Helpers.GetLast(project.Xml.ItemGroups)).Items);
            Assert.Equal(true, Object.ReferenceEquals(item.Xml, newItemElement));
        }
        private static bool UpgadeCppConfiguration(Microsoft.Build.Evaluation.Project project, OldConfiguration cfg)
        {
            ProjectPropertyGroupElement propertyGroup = project.Xml.PropertyGroups.FirstOrDefault(g => g.Label.Equals("IceBuilder"));

            if (propertyGroup == null)
            {
                propertyGroup       = project.Xml.AddPropertyGroup();
                propertyGroup.Label = "IceBuilder";
            }

            if (!string.IsNullOrEmpty(cfg.OutputDir))
            {
                propertyGroup.AddProperty(PropertyNames.OutputDir, cfg.OutputDir);
            }

            if (!string.IsNullOrEmpty(cfg.HeaderExt))
            {
                propertyGroup.AddProperty(PropertyNames.HeaderExt, cfg.HeaderExt);
            }

            if (!string.IsNullOrEmpty(cfg.SourceExt))
            {
                propertyGroup.AddProperty(PropertyNames.SourceExt, cfg.SourceExt);
            }

            if (!string.IsNullOrEmpty(cfg.AdditionalOptions))
            {
                propertyGroup.AddProperty(PropertyNames.AdditionalOptions, cfg.AdditionalOptions);
            }

            if (!string.IsNullOrEmpty(cfg.IncludeDirectories))
            {
                propertyGroup.AddProperty(PropertyNames.IncludeDirectories,
                                          string.Format("{0};$({1})", cfg.IncludeDirectories, PropertyNames.IncludeDirectories));
            }

            if (cfg.Stream)
            {
                propertyGroup.AddProperty(PropertyNames.Stream, "True");
            }

            if (cfg.Checksum)
            {
                propertyGroup.AddProperty(PropertyNames.Checksum, "True");
            }

            if (cfg.Ice)
            {
                propertyGroup.AddProperty(PropertyNames.AllowIcePrefix, "True");
            }

            if (!string.IsNullOrEmpty(cfg.DLLExport))
            {
                propertyGroup.AddProperty(PropertyNames.DLLExport, cfg.DLLExport);
            }

            foreach (ProjectItemDefinitionGroupElement group in project.Xml.ItemDefinitionGroups)
            {
                //
                // Remove old property sheet from all configurations
                //
                IEnumerable <ProjectImportElement> imports = project.Xml.Imports.Where(
                    p => p.Project.Equals("$(ALLUSERSPROFILE)\\ZeroC\\Ice.props"));
                if (imports != null)
                {
                    foreach (ProjectImportElement import in imports)
                    {
                        import.Parent.RemoveChild(import);
                    }
                }
                //
                // WinRT SDK old property sheet
                //
                imports = project.Xml.Imports.Where(
                    p => p.Project.IndexOf("CommonConfiguration\\Neutral\\Ice.props") != -1);
                if (imports != null)
                {
                    foreach (ProjectImportElement import in imports)
                    {
                        import.Parent.RemoveChild(import);
                    }
                }

                foreach (ProjectItemDefinitionElement i in group.ItemDefinitions)
                {
                    if (i.ItemType.Equals("ClCompile"))
                    {
                        if (!string.IsNullOrEmpty(cfg.OutputDir))
                        {
                            ProjectMetadataElement metaData = i.Metadata.FirstOrDefault(
                                e => e.Name.Equals("AdditionalIncludeDirectories"));

                            if (metaData != null)
                            {
                                List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' }));
                                values.Remove(cfg.OutputDir);
                                metaData.Value = string.Join(";", values);

                                if (values.Count == 0 ||
                                    (values.Count == 1 && values[0].Equals("%(AdditionalIncludeDirectories)")))
                                {
                                    i.RemoveChild(metaData);
                                }
                                else
                                {
                                    if (!values.Contains("%(AdditionalIncludeDirectories)"))
                                    {
                                        values.Add("%(AdditionalIncludeDirectories)");
                                    }
                                    metaData.Value = string.Join(";", values);
                                }
                            }
                        }
                    }
                    else if (i.ItemType.Equals("Link"))
                    {
                        ProjectMetadataElement metaData = i.Metadata.FirstOrDefault(
                            e => e.Name.Equals("AdditionalDependencies"));

                        if (metaData != null)
                        {
                            List <string> values = new List <string>(metaData.Value.Split(new char[] { ';' }));
                            foreach (string name in Package.CppLibNames)
                            {
                                values.Remove(string.Format("{0}.lib", name));
                                values.Remove(string.Format("{0}d.lib", name));
                            }

                            if (values.Count == 0 || (values.Count == 1 && values[0].Equals("%(AdditionalDependencies)")))
                            {
                                i.RemoveChild(metaData);
                            }
                            else
                            {
                                metaData.Value = string.Join(";", values);
                            }
                        }

                        metaData = i.Metadata.FirstOrDefault(e => e.Name.Equals("AdditionalLibraryDirectories"));
                        if (metaData != null)
                        {
                            if (metaData.Value.Equals("%(AdditionalLibraryDirectories)"))
                            {
                                i.RemoveChild(metaData);
                            }
                        }
                    }
                }
            }

            List <ProjectItem> sliceItems =
                project.GetItems("None").Where(item => Path.GetExtension(item.UnevaluatedInclude).Equals(".ice")).ToList();

            //
            // Default output directory has changed
            //
            if (string.IsNullOrEmpty(cfg.OutputDir))
            {
                foreach (string itemType in new string[] { "ClInclude", "ClCompile" })
                {
                    project.GetItems(itemType).Where(
                        item =>
                    {
                        return(sliceItems.FirstOrDefault(
                                   slice =>
                        {
                            return slice.UnevaluatedInclude.Equals(Path.ChangeExtension(item.UnevaluatedInclude, ".ice"));
                        }) != null);
                    })
                    .ToList()
                    .ForEach(item => project.RemoveItem(item));
                }
            }

            sliceItems.ForEach(item =>
            {
                project.RemoveItem(item);
                project.AddItem("IceBuilder", item.UnevaluatedInclude);
            });
            return(true);
        }
        public void RenameItem_NewNameContainsItemExpressionExpandingToZeroItems()
        {
            Project project = new Project();
            project.AddItem("i", "i1");
            project.ReevaluateIfNecessary();

            ProjectItem item = Helpers.GetLast(project.Items);

            item.Rename("@(h)");

            Assert.Equal("@(h)", item.UnevaluatedInclude);
            Assert.Equal("@(h)", item.EvaluatedInclude);
        }
        public void SettingItemIncludeDirties()
        {
            Project project = new Project();
            ProjectItem item = project.AddItem("i", "i1")[0];
            project.ReevaluateIfNecessary();

            item.Xml.Include = "i2";
            project.ReevaluateIfNecessary();

            Assert.Equal("i2", Helpers.GetFirst(project.Items).EvaluatedInclude);
        }
        public void SetValueWithPropertyExpression()
        {
            Project project = new Project();
            project.SetProperty("p", "p0");
            ProjectItem item = project.AddItem("i", "i1")[0];
            ProjectMetadata metadatum = item.SetMetadataValue("m", "m1");
            project.ReevaluateIfNecessary();

            metadatum.UnevaluatedValue = "$(p)";

            Assert.AreEqual("$(p)", metadatum.UnevaluatedValue);
            Assert.AreEqual("p0", metadatum.EvaluatedValue);
        }
        public void AddItem_MatchesWildcard()
        {
            Project project = new Project();
            ProjectItemElement item1 = project.Xml.AddItem("i", "*.xxx");
            project.ReevaluateIfNecessary();

            ProjectItemElement item2 = project.AddItem("i", "i1.xxx")[0].Xml;

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
            Assert.Equal(true, Object.ReferenceEquals(item1, item2));
        }
Beispiel #46
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            string message = "Refactoy concluido com sucesso !";
            string title   = "Refactory - Microserviço";

            IntPtr             hierarchyPointer, selectionContainerPointer;
            Object             selectedObject = null;
            IVsMultiItemSelect multiItemSelect;
            uint projectItemId;

            IVsMonitorSelection monitorSelection =
                (IVsMonitorSelection)Package.GetGlobalService(
                    typeof(SVsShellMonitorSelection));

            monitorSelection.GetCurrentSelection(out hierarchyPointer,
                                                 out projectItemId,
                                                 out multiItemSelect,
                                                 out selectionContainerPointer);

            IVsHierarchy selectedHierarchy = Marshal.GetTypedObjectForIUnknown(
                hierarchyPointer,
                typeof(IVsHierarchy)) as IVsHierarchy;

            if (selectedHierarchy != null)
            {
                ErrorHandler.ThrowOnFailure(selectedHierarchy.GetProperty(
                                                projectItemId,
                                                (int)__VSHPROPID.VSHPROPID_ExtObject,
                                                out selectedObject));
            }

            EnvDTE.Project selectedProject = selectedObject as EnvDTE.Project;

            string projectPath = selectedProject.FullName;

            var classesEncontradas = GetAllProjectFiles(selectedProject.ProjectItems, ".cs");

            var projectEvalution = new Microsoft.Build.Evaluation.Project(projectPath);

            if (!Directory.Exists(Path.Combine(selectedProject.Properties.Item("FullPath").Value.ToString(), "Service")))
            {
                selectedProject.ProjectItems.AddFolder("Service");

                projectEvalution.AddItem("Folder",
                                         Path.Combine(selectedProject.Properties.Item("FullPath").Value.ToString(), "Service"));
            }


            foreach (string classe in classesEncontradas)
            {
                var newClass = AnalisadorAST.Analisar(Arquivo.LerClasse(classe));

                if (newClass != null)
                {
                    Arquivo.CriarArquivo(newClass.Interface, selectedProject, projectEvalution, "I" + newClass.Name + ".cs");
                    Arquivo.CriarArquivo(newClass.Classe, selectedProject, projectEvalution, newClass.Name + ".cs");
                }
            }


            //Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                this.ServiceProvider,
                message,
                title,
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }
Beispiel #47
0
        public void TestRunPythonCommand() {
            var expectedSearchPath = string.Format("['{0}', '{1}']",
                TestData.GetPath(@"TestData").Replace("\\", "\\\\"),
                TestData.GetPath(@"TestData\HelloWorld").Replace("\\", "\\\\")
            );

            var proj = new Project(TestData.GetPath(@"TestData\Targets\Commands4.pyproj"));

            foreach (var version in PythonPaths.Versions) {
                var verStr = version.Version.ToVersion().ToString();
                proj.SetProperty("InterpreterId", version.Id.ToString("B"));
                proj.SetProperty("InterpreterVersion", verStr);
                proj.RemoveItems(proj.ItemsIgnoringCondition.Where(i => i.ItemType == "InterpreterReference").ToArray());
                proj.AddItem("InterpreterReference", string.Format("{0:B}\\{1}", version.Id, verStr));
                proj.Save();
                proj.ReevaluateIfNecessary();

                var log = new StringLogger(LoggerVerbosity.Minimal);
                Assert.IsTrue(proj.Build("CheckCode", new ILogger[] { new ConsoleLogger(LoggerVerbosity.Detailed), log }));
                
                Console.WriteLine();
                Console.WriteLine("Output from {0:B} {1}", version.Id, version.Version.ToVersion());
                foreach (var line in log.Lines) {
                    Console.WriteLine("* {0}", line.TrimEnd('\r', '\n'));
                }

                var logLines = log.Lines.Last().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                Assert.AreEqual(2, logLines.Length);
                Assert.AreEqual(version.Version.ToVersion().ToString(), logLines[0].Trim());
                Assert.AreEqual(expectedSearchPath, logLines[1].Trim());
            }
        }
        public void AddItem_MatchesWildcardButNotItemType()
        {
            Project project = new Project();
            project.Xml.AddItem("i", "*.xxx");
            project.ReevaluateIfNecessary();

            project.AddItem("j", "j1.xxx");

            string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
  <ItemGroup>
    <i Include=""*.xxx"" />
  </ItemGroup>
  <ItemGroup>
    <j Include=""j1.xxx"" />
  </ItemGroup>
</Project>");

            Helpers.VerifyAssertProjectContent(expected, project);
        }