private ProjectItem TravAllItems(string tag) { tag = tag.Trim().TrimEnd('\\'); var stack = new Stack <ProjectItem>(); foreach (var item in ProjectItems.OfType <ProjectItem>()) { var itemTag = item.Tag as string; if (string.Equals(itemTag?.Trim().TrimEnd('\\'), tag, StringComparison.OrdinalIgnoreCase)) { return(item); } stack.Push(item); } while (stack.Count > 0) { var parentItem = stack.Pop(); foreach (var item in parentItem.Children.OfType <ProjectItem>()) { var itemTag = item.Tag as string; if (string.Equals(itemTag?.Trim().TrimEnd('\\'), tag, StringComparison.OrdinalIgnoreCase)) { return(item); } stack.Push(item); } } return(null); }
/// <summary> /// 指定のアイテム一覧に含まれる全てのアイテムを取得します。 /// </summary> /// <remarks> /// フォルダ、ファイルを指定できます。 /// ファイルの中にネストされているアイテムも取得します。 /// </remarks> private IEnumerable <ProjectItem> GetProjectItems(ProjectItems items, Func <string, bool> filter) { return(items .OfType <ProjectItem>() .Recursive(x => { var innerItems = x.ProjectItems; if (innerItems != null) { if (filter(x.Name)) { return innerItems.OfType <ProjectItem>(); } } else { var subProject = x.SubProject; if (subProject != null) { // MEMO : フォルダの場合 return GetProjectItems(subProject, filter); } } return Enumerable.Empty <ProjectItem>(); })); }
private void AddProjectFolder(string name, NewItemTarget target) { // Make sure the directory exists before we add it to the project. Don't // use `PackageUtilities.EnsureOutputPath()` because it can silently fail. Directory.CreateDirectory(Path.Combine(target.Directory, name)); // We can't just add the final directory to the project because that will // only add the final segment rather than adding each segment in the path. // Split the name into segments and add each folder individually. ProjectItems items = target.ProjectItem?.ProjectItems ?? target.Project.ProjectItems; string parentDirectory = target.Directory; foreach (string segment in SplitPath(name)) { parentDirectory = Path.Combine(parentDirectory, segment); // Look for an existing folder in case it's already in the project. ProjectItem folder = items .OfType <ProjectItem>() .Where(item => segment.Equals(item.Name, StringComparison.OrdinalIgnoreCase)) .Where(item => item.IsKind(Constants.vsProjectItemKindPhysicalFolder, Constants.vsProjectItemKindVirtualFolder)) .FirstOrDefault(); if (folder == null) { folder = items.AddFromDirectory(parentDirectory); } items = folder.ProjectItems; } }
public static ProjectItems GetOrCreateFolder(ProjectItems projectItems, string viewModelLocation) { var path = viewModelLocation.Split('/', '\\').Where(p => !String.IsNullOrEmpty(p)).ToList(); for (var i = 0; i < path.Count; i++) { var projectItem = projectItems.OfType <ProjectItem>().FirstOrDefault(p => p.Name == path[i]); if (projectItem == null) { try { projectItem = projectItems.AddFolder(path[i]); } catch { throw new Exception($"Could not add a folder '{path[i]}' in the project!"); } } else if (projectItem.Kind != ProjectItemKindPhysicalFolder) { throw new Exception($"The location of the viewmodel is not valid! Path '{path[i]}'."); } projectItems = projectItem.ProjectItems; } return(projectItems); }
public static ProjectItem FindItem( this ProjectItems items, string itemName, StringComparer comparer ) => items .OfType <ProjectItem>() .FirstOrDefault(p => comparer.Compare(p.Name, itemName) == 0);
///// <summary> ///// Ensuures that a project of a given name exists in the solution ///// </summary> ///// <param name="store">Model from which to look for</param> ///// <param name="relativePath">Relative path where to create the new project if necessary (ending in the project name with .csproj)</param> ///// <param name="sourcePath">Source path of the template of the project</param> ///// <param name="updateAssemblyNameAndNamespace">Should we update the assembly name and namespace of the new project.</param> ///// <remarks> ///// Suppose you want to create add a new project named "MyProject.csproj" from a template (vs vsTemplate located in a sub folder of the location of the extension, ///// and you want to have similar namespaces: ///// <code> ///// StoreHostingProject.EnsureNamedProjectExistsInDslSolution(dsl.Store, "MyProject.csproj" ///// , Path.Combine(Path.GetDirectoryName(typeof(ATypeInMyExtension).Assembly.Location), @"Templates\MyProject\MyTemplate.vstemplate") ///// , true ///// ); ///// </code> ///// </remarks> //public static void EnsureNamedProjectExistsInDslSolution(Store store, string relativePath, string sourcePath, bool updateAssemblyNameAndNamespace) //{ // // Verify that the relative path ends with csproj // if (Path.GetExtension(relativePath) != ".csproj") // { // throw new ArgumentException("relativePath should be relative path of the .csproj file to create with respect to the solution, hence ending in .csproj", "relativePath"); // } // Project project = Store2DTE.GetProjectForStore(store); // Solution solution = project.DTE.Solution; // Project newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.UniqueName == relativePath); // if (newProject != null) // { // return; // } // string projectDirectory = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(project.FullName)), Path.GetFileNameWithoutExtension(relativePath)); // string projectPath = Path.Combine(projectDirectory, Path.GetFileName(relativePath)); // string projectSimpleName = Path.GetFileNameWithoutExtension(relativePath); // // The project exist but is not in the solution: let's just add it. // if (File.Exists(projectPath)) // { // solution.AddFromFile(projectPath, false); // } // // The project does not exist: create it from a template // else // { // newProject = project.DTE.Solution.AddFromTemplate(sourcePath, projectDirectory, Path.GetFileName(relativePath), false); // // Well known workaround for C# and VB projects, AddFromTemplate returns null // newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.Name == projectSimpleName); // // Update the assembly name and namespace if necessary // if (updateAssemblyNameAndNamespace) // { // newProject.Properties.Item("AssemblyName").Value = project.Properties.Item("AssemblyName").Value.ToString().Replace("." + project.Name, "." + projectSimpleName); // newProject.Properties.Item("DefaultNamespace").Value = project.Properties.Item("DefaultNamespace").Value.ToString() + "." + projectSimpleName; // } // } //} #endregion #region Adding a file or a link to a file /// <summary> /// Ensures that a file is present in the project /// </summary> /// <param name="store">Store containing a model</param> /// <param name="relativePath">relative path where the file should be located</param> /// <param name="sourcePath">Path of the file to copy if not already present in the solution</param> /// <example> /// if you have a file Adapter.tt, added to the VSIX, of type Content, and copied if newer, in a folder Temmplates of the extension project, you can add /// it to the GeneratedCode folder of the DSL by the following code: /// <code> /// StoreHostingProject.EnsureFileInProject(dsl.Store, @"GeneratedCode\Adapter.tt", /// Path.Combine(Path.GetDirectoryName(typeof(MyExtensionAuthoring).Assembly.Location), @"Templates\Adapter.tt")); /// </code> /// </example> public static void EnsureFileCopiedInDslProject(Store store, string relativePath, string sourcePath) { Contract.Requires(store != null); Contract.Requires(relativePath != null); Contract.Requires(sourcePath != null); Project project = Store2DTE.GetProjectForStore(store); string[] pathSegments = relativePath.Split('\\'); ProjectItems parent = project.ProjectItems; // Find the folder (or create it if necessary) for (int i = 0; i < pathSegments.Length - 1; ++i) { ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]); if (folder == null) { folder = parent.AddFolder(pathSegments[i]); } parent = folder.ProjectItems; } // Find the file and create it if necessary ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]); if (file == null) { string fileDirectory = Path.Combine(Path.GetDirectoryName(project.FullName), Path.GetDirectoryName(relativePath)); string filePath = Path.Combine(fileDirectory, Path.GetFileName(relativePath)); // Case where the file is already there, but not added to the project if (File.Exists(filePath)) { parent.AddFromFile(filePath); } else { parent.AddFromFileCopy(sourcePath); } } }
private IEnumerable <ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return(SpecializedCollections.EmptyEnumerable <ProjectItem>()); } var items = projectItems.OfType <ProjectItem>(); return(items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)))); }
/// <summary> /// Ensures a link on a file is created in a project /// </summary> /// <param name="store">Store containing a model</param> /// <param name="uniqueProjectName">Unique project name of the project to which to add a link a a file</param> /// <param name="relativePathOfFileToCreate">Relative path to the link to create in the project described by <paramref name="relativePathOfFileToCreate"/></param> /// <param name="originalFileToLink">Path to the original file to link</param> public static void EnsureFileLinkInProject(Store store, string uniqueProjectName, string relativePathOfFileToCreate, string originalFileToLink) { Contract.Requires(store != null); Contract.Requires(relativePathOfFileToCreate != null); Contract.Requires(originalFileToLink != null); Project project = Store2DTE.GetProjectForStore(store); if (!string.IsNullOrWhiteSpace(uniqueProjectName)) { project = project.DTE.Solution.Projects.OfType <Project>().FirstOrDefault(p => p.UniqueName == uniqueProjectName); } if (project == null) { return; } string[] pathSegments = relativePathOfFileToCreate.Split('\\'); ProjectItems parent = project.ProjectItems; // Find the folder (or create it if necessary) for (int i = 0; i < pathSegments.Length - 1; ++i) { ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]); if (folder == null) { folder = parent.AddFolder(pathSegments[i]); } parent = folder.ProjectItems; } // Find the file and create a link on the originalFileToLink it if necessary ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]); if (file == null) { parent.AddFromFile(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project.FullName), originalFileToLink))); } }
/// <summary> /// Find a project item using a path-like address in the project folder hierarchy /// </summary> /// <param name="topItems">Top level items in the project</param> /// <param name="itemPath">path to the required project item</param> /// <returns>the project item</returns> public static ProjectItem FindItemByPath(ProjectItems topItems, string itemPath) { ProjectItem item = topItems.OfType <ProjectItem>().FirstOrDefault(pi => pi.Name == itemPath.UpTo("/")); if (!itemPath.Contains("/")) { return(item); } else { return(FindItemByPath(item.ProjectItems, itemPath.After("/"))); } }
private static ProjectItem GetNestedProjectItem(ProjectItems items, string fileName) { ProjectItem currentItem = null; string[] pathParts = fileName.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); foreach (string part in pathParts) { currentItem = items.OfType <ProjectItem>().FirstOrDefault(i => string.Equals(i.Name, part, StringComparison.OrdinalIgnoreCase)); if (currentItem == null) { return(null); } items = currentItem.ProjectItems; } return(currentItem); }
private static IEnumerable <ProjectItem> GetAllProjectItems(ProjectItems projectItems) { foreach (var item in projectItems.OfType <ProjectItem>()) { if (item.ProjectItems.Count > 0) { foreach (var subItem in GetAllProjectItems(item.ProjectItems)) { yield return(subItem); } } else { yield return(item); } } }
private IEnumerable<string> GetFiles(ProjectItems projectItems) { if (projectItems == null) { return new string[0]; } List<string> files = new List<string>(); foreach (var projectItem in projectItems.OfType<ProjectItem>()) { for (short i = 0; i < projectItem.FileCount; i++) { files.Add(GetFileName(projectItem, i)); } files.AddRange(GetFiles(projectItem.ProjectItems)); } return files; }
/// <summary> /// Find a project item using a path-like address in the project folder hierarchy /// </summary> /// <param name="topItems">Top level items in the project</param> /// <param name="itemPath">path to the required project item</param> /// <returns>the project item</returns> public static ProjectItem FindItemByPath(ProjectItems topItems, string itemPath) { ProjectItem item = topItems.OfType<ProjectItem>().FirstOrDefault(pi => pi.Name == itemPath.UpTo("/")); if (!itemPath.Contains("/")) return item; else return FindItemByPath(item.ProjectItems, itemPath.After("/")); }
private async Task DeleteProjectItemAsync(Project project, string deleteFileName) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ProjectItems prjItems = project.ProjectItems; ProjectItem deleteItem = prjItems.OfType <ProjectItem>() .Where(c => { ThreadHelper.ThrowIfNotOnUIThread(); return(c.Name.ToLower() == deleteFileName.ToLower()); }) .FirstOrDefault(); #pragma warning disable VSTHRD109 // 使用非同步方法時請切換而非判斷提示 ThreadHelper.ThrowIfNotOnUIThread(); #pragma warning restore VSTHRD109 // 使用非同步方法時請切換而非判斷提示 try { deleteItem.Remove(); } catch (Exception ex) { } if (deleteItem != null) { var deletePhysicalName = deleteItem.Properties.Item("FullPath"); string fullPath = deletePhysicalName.Value.ToString(); try { string deletePath = Path.GetDirectoryName(fullPath); try { File.Delete(fullPath); } catch { } //真的移除掉該實體檔案 switch (deleteFileName.ToLower()) { case "web.config": File.Delete(Path.Combine(deletePath, "Web.Debug.config")); File.Delete(Path.Combine(deletePath, "Web.Release.config")); break; case "global.asax": File.Delete(Path.Combine(deletePath, "global.asax.cs")); break; case "app_start": File.Delete(Path.Combine(deletePath, "RouteConfig.cs")); File.Delete(Path.Combine(deletePath, "WebApiConfig.cs")); Directory.Delete(deletePath); break; case "properties": File.Delete(Path.Combine(deletePath, "AssemblyInfo.cs")); break; case "views": File.Delete(Path.Combine(deletePath, "web.config")); break; } } catch (Exception ex) { } } }
List <DTE.ProjectItem> GetAllChildItems(ProjectItems projectItems) { return(projectItems.OfType <DTE.ProjectItem>().ToList()); }
DTE.ProjectItem GetFirstChildItem(ProjectItems projectItems) { return(projectItems.OfType <DTE.ProjectItem>().FirstOrDefault()); }
DTE.ProjectItem GetChildItem(ProjectItems projectItems, string name) { return(projectItems .OfType <DTE.ProjectItem>() .SingleOrDefault(item => item.Name == name)); }