public static ProjectItem GetItem(this ProjectItems projectItems, string name)
 {
     return(projectItems
            .Cast <ProjectItem>()
            .FirstOrDefault(
                pi => string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase)));
 }
        private static IEnumerable<Project> GetAllProjects(ProjectItems projectItems)
        {
            if(projectItems == null)
                yield break;

            foreach(var projectItem in projectItems.Cast<ProjectItem>())
            {
                if(projectItem.SubProject != null)
                {
                    yield return projectItem.SubProject;

                    foreach(var project in GetAllProjects(projectItem.SubProject))
                    {
                        yield return project;
                    }
                }
                else
                {
                    foreach(var project in GetAllProjects(projectItem.ProjectItems))
                    {
                        yield return project;
                    }
                }
            }
        }
        /// <summary>
        /// Adds a folder to a specified <paramref name="collection"/> of project items.
        /// </summary>
        /// <param name="collection">
        /// A <see cref="ProjectItems"/> collection that belongs to a <see cref="Project"/> or
        /// <see cref="ProjectItem"/> of type <see cref="Constants.vsProjectItemKindPhysicalFolder"/>.
        /// </param>
        /// <param name="folderName">
        /// Name of the folder to be added.
        /// </param>
        /// <param name="basePath">
        /// Absolute path to the directory where the folder is located.
        /// </param>
        /// <returns>
        /// A <see cref="ProjectItem"/> that represents new folder added to the <see cref="Project"/>.
        /// </returns>
        /// <remarks>
        /// If the specified folder doesn't exist in the solution and the file system,
        /// a new folder will be created in both. However, if the specified folder
        /// already exists in the file system, it will be added to the solution instead.
        /// Unfortunately, an existing folder can only be added to the solution with
        /// all of sub-folders and files in it. Thus, if a single output file is
        /// generated in an existing folders not in the solution, the target folder will
        /// be added to the solution with all files in it, generated or not. The
        /// only way to avoid this would be to immediately remove all child items
        /// from a newly added existing folder. However, this could lead to having
        /// orphaned files that were added to source control and later excluded from
        /// the project. We may need to revisit this code and access <see cref="SourceControl"/>
        /// automation model to remove the child items from source control too.
        /// </remarks>
        private static ProjectItem AddFolder(ProjectItems collection, string folderName, string basePath)
        {
            // Does the folder already exist in the solution?
            ProjectItem folder = collection.Cast <ProjectItem>().FirstOrDefault(
                p => string.Compare(p.Name, folderName, StringComparison.OrdinalIgnoreCase) == 0);

            if (folder != null)
            {
                return(folder);
            }

            try
            {
                // Try adding folder to the project.
                // Note that this will work for existing folder in a Database project but not in C#.
                return(collection.AddFolder(folderName, Constants.vsProjectItemKindPhysicalFolder));
            }
            catch (COMException)
            {
                // If folder already exists on disk and the previous attempt to add failed
                string folderPath = Path.Combine(basePath, folderName);
                if (Directory.Exists(folderPath))
                {
                    // Try adding it from disk
                    // Note that this will work in a C# but is not implemented in Database projects.
                    return(collection.AddFromDirectory(folderPath));
                }

                throw;
            }
        }
Exemplo n.º 4
0
        public static ProjectItem GetItem(this ProjectItems projectItems, string name)
        {
            DebugCheck.NotNull(projectItems);
            DebugCheck.NotEmpty(name);

            return(projectItems
                   .Cast <ProjectItem>()
                   .FirstOrDefault(
                       pi => string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase)));
        }
Exemplo n.º 5
0
        public static ProjectItem GetItem(this ProjectItems projectItems, string name)
        {
            Contract.Requires(projectItems != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(name));

            return(projectItems
                   .Cast <ProjectItem>()
                   .FirstOrDefault(
                       pi => string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase)));
        }
Exemplo n.º 6
0
 private static List<ProjectItem>Get(ProjectItems projectItems)
 {
     var items = new List<ProjectItem>();
     foreach (var projectItem in projectItems.Cast<ProjectItem>())
     {
         items.Add(projectItem);
         items.AddRange(Get(projectItem.ProjectItems));
     }
     return items;
 }
Exemplo n.º 7
0
        public static ProjectItem GetItem(this ProjectItems projectItems, string name)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            return(projectItems
                   .Cast <ProjectItem>()
                   .FirstOrDefault(
#pragma warning disable VSTHRD010 // Invoke single-threaded types on Main thread
                       pi => string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase)));

#pragma warning restore VSTHRD010 // Invoke single-threaded types on Main thread
        }
Exemplo n.º 8
0
 private void NavigateProjectItems(ProjectItems items, List <ProjectItem> xibs)
 {
     if (items == null)
     {
         return;
     }
     items.Cast <ProjectItem>().ToList().ForEach(pi =>
     {
         if (pi.SubProject != null)
         {
             FindXibs(pi.SubProject, xibs);
         }
     });
 }
Exemplo n.º 9
0
        private ProjectItem FindProjectItem(ProjectItems items, string fullName)
        {
            ProjectItem item = (from i in items.Cast <ProjectItem>()
                                where i.Name == Path.GetFileName(fullName)
                                select i).FirstOrDefault();

            if (item == null)
            {
                File.CreateText(fullName);
                item = items.AddFromFile(fullName);
            }

            return(item);
        }
Exemplo n.º 10
0
        protected ProjectItem CreateTestProjectItem(ProjectItems projectItems, string templateName)
        {
            if (projectItems == null)
            {
                throw new ArgumentNullException("projectItems");
            }

            string      templateFile = Solution.GetProjectItemTemplate(templateName, this.TargetProject.Language);
            string      itemName     = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            ProjectItem projectItem  = projectItems.AddFromTemplate(templateFile, itemName)
                                       ?? projectItems.Cast <ProjectItem>().First(pi => Path.GetFileNameWithoutExtension(pi.Name) == itemName);

            projectItem.Document.Close(); // To avoid sideffects and enable testing by writing to files as opposed to document manipulation
            return(projectItem);
        }
Exemplo n.º 11
0
 /// <summary>
 /// 判断在某个项目集合中是否存在某项目
 /// </summary>
 /// <param name="projectItems">项目集合</param>
 /// <param name="strName">判断存在的项目名</param>
 /// <returns></returns>
 internal static bool IsExists(this ProjectItems projectItems, string strName)
 {
     try
     {
         if (projectItems != null)
         {
             return(projectItems.Cast <ProjectItem>().ToList().Any(x => x.Name.Equals(strName)));
         }
         return(false);
     }
     catch (Exception ex)
     {
         OutputWindowHelper.DiagnosticWriteLine("Unable to find a ProjectItem", ex);
         return(false);
     }
 }
Exemplo n.º 12
0
 private static List<ProjectItem> DeleteGeneratedFilesInProjectItems(ProjectItems projectItems)
 {
     var items = new List<ProjectItem>();
     foreach (var projectItem in projectItems.Cast<ProjectItem>())
     {
         try
         {
             items.AddRange(DeleteGeneratedFilesInProjectItems(projectItem.ProjectItems));
             if (projectItem.FileNames[0].EndsWith(".g.cs"))
                 items.Add(projectItem);
         }
         catch (Exception)
         {
         }
     }
     return items;
 }
        private static void FillSolutionTree(Package connect,
                                             SolutionItem solutionItem,
                                             ProjectItems projectItems)
        {
            if (projectItems == null)
            {
                return;
            }

            foreach (var item in
                     projectItems.Cast <ProjectItem>()
                     .Select(p => ConstructSolutionItem(connect, p.SubProject))
                     .Where(item => item != null))
            {
                solutionItem.SubItems.Add(item);
            }
        }
        private static void FillSolutionTree(Package connect,
                                             SolutionItem solutionItem,
                                             ProjectItems projectItems)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            if (projectItems == null)
            {
                return;
            }

            foreach (var item in
                     projectItems.Cast <ProjectItem>()
                     .Select(p => { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); return(ConstructSolutionItem(connect, p.SubProject)); })
                     .Where(item => item != null))
            {
                solutionItem.SubItems.Add(item);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Find file in projects collection.
        /// </summary>
        /// <param name="items">Projects collection.</param>
        /// <param name="filePath">File path, relative to the <paramref name="items"/> root.</param>
        /// <returns>The found file or <c>null</c>.</returns>
        public static ProjectItem FindProjectItem(this ProjectItems items, string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentException("Argument `filePath` is null or empty.", "filePath");
            }

            var backslashIndex = filePath.IndexOf("\\", StringComparison.Ordinal);
            var findFolder     = backslashIndex != -1;

            if (findFolder)
            {
                var folderName = filePath.Substring(0, backslashIndex);
                return((from ProjectItem item in items where item.Kind == Constants.vsProjectItemKindVirtualFolder || item.Kind == Constants.vsProjectItemKindPhysicalFolder where folderName == item.Name let nextpath = filePath.Substring(backslashIndex + 1) select FindProjectItem(item.ProjectItems, nextpath)).FirstOrDefault());
            }
            else
            {
                var fileName = filePath;
                foreach (var item in items.Cast <ProjectItem>().Where(item => item.Kind == Constants.vsProjectItemKindPhysicalFile))
                {
                    if (item.Name == fileName)
                    {
                        return(item);
                    }

                    // Nested item, e.g. Default.aspx or MainWindow.xaml.
                    if (item.ProjectItems.Count <= 0)
                    {
                        continue;
                    }
                    var childItem = FindProjectItem(item.ProjectItems, fileName);
                    if (childItem != null)
                    {
                        return(childItem);
                    }
                }
            }

            return(null);
        }
        private bool VisitPath(ICollection<ProjectItem> path, string itemname, ProjectItems projectItems)
        {
            if (projectItems == null || projectItems.Count == 0)
            {
                return false;
            }

            if (projectItems.Cast<ProjectItem>().Any(i => i.Name == itemname))
            {
                return !(projectItems.Parent is Project);
            }

            foreach (ProjectItem projectItem in projectItems)
            {
                if  (VisitPath(path, itemname, projectItem.ProjectItems))
                {
                    path.Add(projectItem);
                    return true;
                }
            }

            return false;
        }
Exemplo n.º 17
0
        private bool VisitPath(ICollection <ProjectItem> path, string itemname, ProjectItems projectItems)
        {
            if (projectItems == null || projectItems.Count == 0)
            {
                return(false);
            }

            if (projectItems.Cast <ProjectItem>().Any(i => i.Name == itemname))
            {
                return(!(projectItems.Parent is Project));
            }

            foreach (ProjectItem projectItem in projectItems)
            {
                if (VisitPath(path, itemname, projectItem.ProjectItems))
                {
                    path.Add(projectItem);
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 18
0
 private static IEnumerable <string> EnumerateProjectItems(ProjectItems projectItems)
 {
     return(projectItems.Cast <ProjectItem>().SelectMany(p => EnumerateProjectItems(p)));
 }
Exemplo n.º 19
0
 private void NavigateProjectItems(ProjectItems items, List<ProjectItem> xibs)
 {
     if (items == null) return;
     items.Cast<ProjectItem>().ToList().ForEach(pi =>
     {
         if (pi.SubProject != null) FindXibs(pi.SubProject, xibs);
     });
 }
Exemplo n.º 20
0
        protected ProjectItem CreateTestProjectItem(ProjectItems projectItems, string templateName)
        {
            if (projectItems == null)
            {
                throw new ArgumentNullException("projectItems");
            }

            string templateFile = Solution.GetProjectItemTemplate(templateName, this.TargetProject.Language);
            string itemName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            ProjectItem projectItem = projectItems.AddFromTemplate(templateFile, itemName)
                ?? projectItems.Cast<ProjectItem>().First(pi => Path.GetFileNameWithoutExtension(pi.Name) == itemName);
            projectItem.Document.Close(); // To avoid sideffects and enable testing by writing to files as opposed to document manipulation
            return projectItem;
        }
Exemplo n.º 21
0
 static IEnumerable<ProjectItem> Items(ProjectItems ProjectItems)
 {
     return ProjectItems.Cast<ProjectItem>().SelectMany(Items);
 }
Exemplo n.º 22
0
        public static void CopyTemplates(DTE dte, string templatesFolderName, string netVersion, string toolsPath, string vsVersion, out string templatesFolder, out HashSet <string> existingTTIncludes, out ProjectItems templatesProjectItems)
        {
            var slnFolder = Path.GetDirectoryName(dte.Solution.FullName);

            templatesFolder = Path.Combine(slnFolder, templatesFolderName);
            if (!Directory.Exists(templatesFolder))
            {
                Directory.CreateDirectory(templatesFolder);
            }

            const string    solutionItemsFolderName         = "Solution Items";
            Project         solutionItems                   = dte.Solution.Projects.OfType <Project>().FirstOrDefault(pi => pi.Name == solutionItemsFolderName);
            UIHierarchyItem solutionItemsUIHierarchyItem    = null;
            Action          setSolutionItemsUIHierarchyItem = () => solutionItemsUIHierarchyItem = (dte.Windows.Cast <Window>().First(w => w.Type == vsWindowType.vsWindowTypeSolutionExplorer).Object as UIHierarchy)?.UIHierarchyItems.Cast <UIHierarchyItem>().First().UIHierarchyItems.Cast <UIHierarchyItem>().First(uihi => uihi.Name == solutionItemsFolderName);
            bool            solutionItemsExpanded;

            Project         templates = null;
            UIHierarchyItem templatesUIHierarchyItem    = null;
            Action          setTemplatesUIHierarchyItem = () => templatesUIHierarchyItem = solutionItemsUIHierarchyItem.UIHierarchyItems.Cast <UIHierarchyItem>().First(uihi => uihi.Name == templatesFolderName);
            bool            templatesItemsExpanded      = false;
            Action          addTemplatesUIHierarchyItem = () =>
            {
                templates = ((EnvDTE80.SolutionFolder)solutionItems.Object).AddSolutionFolder(templatesFolderName);
                setTemplatesUIHierarchyItem();
                templatesItemsExpanded = false;
            };

            if (solutionItems == null)
            {
                solutionItems = ((EnvDTE80.Solution2)dte.Solution).AddSolutionFolder(solutionItemsFolderName);
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = false;
                addTemplatesUIHierarchyItem();
            }
            else
            {
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded;

                templates = ((IEnumerable)solutionItems.ProjectItems).Cast <ProjectItem>().FirstOrDefault(pi => pi.Name == templatesFolderName).SubProject;
                if (templates == null)
                {
                    addTemplatesUIHierarchyItem();
                }
                else
                {
                    setTemplatesUIHierarchyItem();
                    templatesItemsExpanded = templatesUIHierarchyItem.UIHierarchyItems.Expanded;
                }
            }

            var ttincludesFolder = Path.Combine(toolsPath, "ttincludes");

            templatesProjectItems = (ProjectItems)templates.ProjectItems;
            existingTTIncludes    = new HashSet <string>(templatesProjectItems.Cast <ProjectItem>().Select(pi => pi.Name));
            string ttIncludeName = null;

            foreach (var ttInclude in Directory.GetFiles(ttincludesFolder).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            var ttIncludesFolderVS = Path.Combine(ttincludesFolder, vsVersion);

            foreach (var ttInclude in Directory.GetFiles(ttIncludesFolderVS).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            const string mergeTTIncludeFileName = "MergeT4Files.ttinclude";

            File.Copy(Path.Combine(ttincludesFolder, mergeTTIncludeFileName), Path.Combine(templatesFolder, mergeTTIncludeFileName), true);
            var specialMergeFolder = Path.Combine(ttincludesFolder, "SpecialMerge");

            foreach (var specialMerge in Directory.GetFiles(specialMergeFolder))
            {
                var ttSpecialMergeFileName = Path.GetFileName(specialMerge);
                var specialMergeFile       = Path.Combine(specialMergeFolder, ttSpecialMergeFileName);
                var ttSpecialMergeFileCopy = Path.Combine(templatesFolder, ttSpecialMergeFileName);
                File.Copy(specialMergeFile, ttSpecialMergeFileCopy, true);
                if (!existingTTIncludes.Contains(ttSpecialMergeFileName))
                {
                    templatesProjectItems.AddFromFile(ttSpecialMergeFileCopy);
                }
            }
            try
            {
                templatesUIHierarchyItem.UIHierarchyItems.Expanded     = templatesItemsExpanded;
                solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded = solutionItemsExpanded;
            }
            catch
            {
            }
            MergeTTIncludes(dte, templates, templatesFolder);
        }
Exemplo n.º 23
0
 public static ProjectItem Find(this ProjectItems projectItems, string fileName)
 {
     return((from pi in projectItems.Cast <ProjectItem>()
             where string.Compare(pi.Name, fileName, true) == 0
             select pi).FirstOrDefault());
 }
Exemplo n.º 24
0
        private void ParseProjectItems(ProjectItems projectItems)
        {
            if (projectItems == null)
                return;
            WriteLine("ParseProjectItems " + projectItems.Count);

            foreach (var item in projectItems.Cast<ProjectItem>())
            {
                ParseProjectItem(item);
            }
        }
Exemplo n.º 25
0
 static IEnumerable <ProjectItem> Items(ProjectItems ProjectItems)
 {
     return(ProjectItems.Cast <ProjectItem>().SelectMany(Items));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Adds a folder to a specified <paramref name="collection" /> of project items.
        /// </summary>
        /// <param name="collection">
        /// A <see cref="ProjectItems" /> collection that belongs to a <see cref="Project" /> or
        /// <see cref="ProjectItem" /> of type <see cref="EnvDTE.Constants.vsProjectItemKindPhysicalFolder" />.
        /// </param>
        /// <param name="folderName">
        /// Name of the folder to be added.
        /// </param>
        /// <param name="basePath">
        /// Absolute path to the directory where the folder is located.
        /// </param>
        /// <returns>
        /// A <see cref="ProjectItem" /> that represents new folder added to the <see cref="Project" />.
        /// </returns>
        /// <remarks>
        /// If the specified folder doesn't exist in the solution and the file system,
        /// a new folder will be created in both. However, if the specified folder
        /// already exists in the file system, it will be added to the solution instead.
        /// Unfortunately, an existing folder can only be added to the solution with
        /// all of sub-folders and files in it. Thus, if a single output file is
        /// generated in an existing folders not in the solution, the target folder will
        /// be added to the solution with all files in it, generated or not. The
        /// only way to avoid this would be to immediately remove all child items
        /// from a newly added existing folder. However, this could lead to having
        /// orphaned files that were added to source control and later excluded from
        /// the project. We may need to revisit this code and access <see cref="SourceControl" />
        /// automation model to remove the child items from source control too.
        /// </remarks>
        private static ProjectItem AddFolder(ProjectItems collection, string folderName, string basePath)
        {
            // Does the folder already exist in the solution?
            ProjectItem folder = collection.Cast<ProjectItem>().FirstOrDefault(p => string.Equals(p.Name, folderName, StringComparison.OrdinalIgnoreCase));
            if (folder != null)
            {
                return folder;
            }

            try
            {
                // Try adding folder to the project.
                // Note that this will work for existing folder in a Database project but not in C#.
                return collection.AddFolder(folderName);
            }
            catch (COMException)
            {
                // If folder already exists on disk and the previous attempt to add failed
                string folderPath = Path.Combine(basePath, folderName);
                if (Directory.Exists(folderPath))
                {
                    // Try adding it from disk
                    // Note that this will work in a C# but is not implemented in Database projects.
                    return collection.AddFromDirectory(folderPath);
                }

                throw;
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Removes the files and folders.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="targetProjectType">Type of the target project.</param>
        /// <param name="levels">The number of levels to walk down the chain. If <c>-1</c>, it will handle all levels.</param>
        /// <param name="fileFilter">An enumerable of files that should be handled with care, can be <c>null</c>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="source" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target" /> is <c>null</c>.</exception>
        private void RemoveFilesAndFolders(ProjectItems source, ProjectItems target, ProjectType targetProjectType, int levels, IEnumerable<string> fileFilter)
        {
            Argument.IsNotNull("source", source);
            Argument.IsNotNull("target", target);

            if (fileFilter == null)
            {
                fileFilter = new string[] { };
            }

            string targetParentName = target.Parent.GetObjectName();

            Log.Debug("Removing files and folders from target '{0}'", targetParentName);

            if (levels == 0)
            {
                return;
            }

            levels--;

            // Yep, this is right, we start at 1... :(
            for (int i = 1; i < target.Count + 1; i++)
            {
                var targetItem = target.Item(i);

                if (ShouldSkipRemovingOfItem(source.ContainingProject, targetItem, targetProjectType))
                {
                    Log.Debug("Skipping item '{0}' because it is ignored by a rule for target project {1}", targetItem.GetObjectName(), targetProjectType);
                    continue;
                }

                var existingSourceItem = (from sourceItem in source.Cast<ProjectItem>() where string.Equals(targetItem.Name, sourceItem.Name, StringComparison.InvariantCultureIgnoreCase) select sourceItem).FirstOrDefault();

                if (existingSourceItem != null && !fileFilter.Any(x => string.Equals(x, targetItem.GetNameRelativeToRoot(), StringComparison.InvariantCultureIgnoreCase)))
                {
                    // Check if the item should be removed (when the item should not be added as linked file, then we should remove it)
                    if (!ShouldSkipAddingOfItem(existingSourceItem, targetProjectType))
                    {
                        RemoveFilesAndFolders(existingSourceItem.ProjectItems, targetItem.ProjectItems, targetProjectType, levels, fileFilter);
                        continue;
                    }

                    Log.Debug("Found linked file '{0}' that is now ignored by a rule, removing it", targetItem.FileNames[0]);
                }

                // Get it once, we don't want to retrieve this several times
                var relatedProjects = source.ContainingProject.GetRelatedProjects(false);

                if (targetItem.IsFolder())
                {
                    RemoveNestedItems(targetItem.ProjectItems, relatedProjects);

                    if (targetItem.ProjectItems.Count == 0)
                    {
                        Log.Debug("Removing folder '{0}' because it no longer contains items", targetItem.Name);

                        targetItem.Remove();
                        i--;
                    }
                }
                else
                {
                    // If this is a linked file and not an actual file in another related project, remove it
                    if (targetItem.IsLinkedFile() && !targetItem.IsActualFileInAnyRelatedProject(relatedProjects))
                    {
                        Log.Debug("Removing file '{0}' because it is a linked file to the root project", targetItem.FileNames[0]);

                        targetItem.Remove();
                        i--;
                    }
                }
            }

            Log.Debug("Removed files and folders from target '{0}'", targetParentName);
        }
Exemplo n.º 28
0
 private static bool ContainsItem(string itemName, ProjectItems items)
 {
     return(items.Cast <ProjectItem>().Any(item => item.Name == itemName));
 }
Exemplo n.º 29
0
        public static void CopyTemplates(DTE dte, string templatesFolderName, string netVersion, string toolsPath, string vsVersion, out string templatesFolder, out HashSet<string> existingTTIncludes, out ProjectItems templatesProjectItems)
        {
            var slnFolder = Path.GetDirectoryName(dte.Solution.FullName);
            templatesFolder = Path.Combine(slnFolder, templatesFolderName);
            if (!Directory.Exists(templatesFolder))
            {
                Directory.CreateDirectory(templatesFolder);
            }

            const string solutionItemsFolderName = "Solution Items";
            Project solutionItems = dte.Solution.Projects.OfType<Project>().FirstOrDefault(pi => pi.Name == solutionItemsFolderName);
            UIHierarchyItem solutionItemsUIHierarchyItem = null;
            Action setSolutionItemsUIHierarchyItem = () => solutionItemsUIHierarchyItem = (dte.Windows.Cast<Window>().First(w => w.Type == vsWindowType.vsWindowTypeSolutionExplorer).Object as UIHierarchy)?.UIHierarchyItems.Cast<UIHierarchyItem>().First().UIHierarchyItems.Cast<UIHierarchyItem>().First(uihi => uihi.Name == solutionItemsFolderName);
            bool solutionItemsExpanded;

            Project templates = null;
            UIHierarchyItem templatesUIHierarchyItem = null;
            Action setTemplatesUIHierarchyItem = () => templatesUIHierarchyItem = solutionItemsUIHierarchyItem.UIHierarchyItems.Cast<UIHierarchyItem>().First(uihi => uihi.Name == templatesFolderName);
            bool templatesItemsExpanded = false;
            Action addTemplatesUIHierarchyItem = () =>
            {
                templates = ((EnvDTE80.SolutionFolder)solutionItems.Object).AddSolutionFolder(templatesFolderName);
                setTemplatesUIHierarchyItem();
                templatesItemsExpanded = false;
            };

            if (solutionItems == null)
            {
                solutionItems = ((EnvDTE80.Solution2)dte.Solution).AddSolutionFolder(solutionItemsFolderName);
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = false;
                addTemplatesUIHierarchyItem();
            }
            else
            {
                setSolutionItemsUIHierarchyItem();
                solutionItemsExpanded = solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded;

                templates = ((IEnumerable)solutionItems.ProjectItems).Cast<ProjectItem>().FirstOrDefault(pi => pi.Name == templatesFolderName).SubProject;
                if (templates == null)
                {
                    addTemplatesUIHierarchyItem();
                }
                else
                {
                    setTemplatesUIHierarchyItem();
                    templatesItemsExpanded = templatesUIHierarchyItem.UIHierarchyItems.Expanded;
                }
            }

            var ttincludesFolder = Path.Combine(toolsPath, "ttincludes");
            templatesProjectItems = (ProjectItems)templates.ProjectItems;
            existingTTIncludes = new HashSet<string>(templatesProjectItems.Cast<ProjectItem>().Select(pi => pi.Name));
            string ttIncludeName = null;
            foreach (var ttInclude in Directory.GetFiles(ttincludesFolder).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            var ttIncludesFolderVS = Path.Combine(ttincludesFolder, vsVersion);
            foreach (var ttInclude in Directory.GetFiles(ttIncludesFolderVS).Where(f => (ttIncludeName = Path.GetFileName(f)).StartsWith("WAQS.")))
            {
                AddItem(ttInclude, vsVersion, netVersion, ttIncludeName, templatesFolder, existingTTIncludes, templatesProjectItems);
            }
            const string mergeTTIncludeFileName = "MergeT4Files.ttinclude";
            File.Copy(Path.Combine(ttincludesFolder, mergeTTIncludeFileName), Path.Combine(templatesFolder, mergeTTIncludeFileName), true);
            var specialMergeFolder = Path.Combine(ttincludesFolder, "SpecialMerge");
            foreach (var specialMerge in Directory.GetFiles(specialMergeFolder))
            {
                var ttSpecialMergeFileName = Path.GetFileName(specialMerge);
                var specialMergeFile = Path.Combine(specialMergeFolder, ttSpecialMergeFileName);
                var ttSpecialMergeFileCopy = Path.Combine(templatesFolder, ttSpecialMergeFileName);
                File.Copy(specialMergeFile, ttSpecialMergeFileCopy, true);
                if (!existingTTIncludes.Contains(ttSpecialMergeFileName))
                {
                    templatesProjectItems.AddFromFile(ttSpecialMergeFileCopy);
                }
            }
            try
            {
                templatesUIHierarchyItem.UIHierarchyItems.Expanded = templatesItemsExpanded;
                solutionItemsUIHierarchyItem.UIHierarchyItems.Expanded = solutionItemsExpanded;
            }
            catch
            {
            }
            MergeTTIncludes(dte, templates, templatesFolder);
        }
Exemplo n.º 30
0
 public static IEnumerable <ProjectItem> AsEnumerable(this ProjectItems source)
 {
     return(source.Cast <ProjectItem>());
 }