Ejemplo n.º 1
0
        public static EnvDTE.ProjectItem FindProjectItem(EnvDTE.ProjectItems items, string file)
        {
            string atom = file.Substring(0, file.IndexOf("\\") + 1);

            foreach (EnvDTE.ProjectItem item in items)
            {
                //if ( item
                //if (item.ProjectItems.Count > 0)
                if (atom.StartsWith(item.Name))
                {
                    // then step in
                    EnvDTE.ProjectItem ritem = FindProjectItem(item.ProjectItems, file.Substring(file.IndexOf("\\") + 1));
                    if (ritem != null)
                    {
                        return(ritem);
                    }
                }
                if (Regex.IsMatch(item.Name, file))
                {
                    return(item);
                }
                if (item.ProjectItems.Count > 0)
                {
                    EnvDTE.ProjectItem ritem = FindProjectItem(item.ProjectItems, file.Substring(file.IndexOf("\\") + 1));
                    if (ritem != null)
                    {
                        return(ritem);
                    }
                }
            }
            return(null);
        }
        public IEnumerable <ProjectItem> GetProjects(EnvDTE.ProjectItems projectItems)
        {
            foreach (EnvDTE.ProjectItem item in projectItems)
            {
                yield return(item);

                if (item.SubProject != null)
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.SubProject.ProjectItems))
                    {
                        if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                        {
                            yield return(childItem);
                        }
                    }
                }
                else
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.ProjectItems))
                    {
                        if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                        {
                            yield return(childItem);
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public static IEnumerable <ProjectItem> GetProjectItems(EnvDTE.ProjectItems projectItems)
        {
            foreach (EnvDTE.ProjectItem item in projectItems)
            {
                yield return(item);

                if (item.SubProject != null)
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.SubProject.ProjectItems))
                    {
                        string fullpath = GetFullPath(childItem);
                        Debug.WriteLine(fullpath);
                        //if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                        yield return(childItem);
                    }
                }
                else
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.ProjectItems))
                    {
                        string fullpath = GetFullPath(childItem);
                        Debug.WriteLine(fullpath);
                        //if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                        yield return(childItem);
                    }
                }
            }
        }
Ejemplo n.º 4
0
 private void EnumerateProjectItems(EnvDTE.ProjectItems items, System.Collections.Generic.List <EnvDTE.CodeInterface> result)
 {
     foreach (EnvDTE.ProjectItem i in items)
     {
         if (i.FileCodeModel != null && i.FileCodeModel.CodeElements != null)
         {
             foreach (EnvDTE.CodeElement n in i.FileCodeModel.CodeElements)
             {
                 if (n.Kind == EnvDTE.vsCMElement.vsCMElementNamespace)
                 {
                     foreach (EnvDTE.CodeElement c in (n as EnvDTE.CodeNamespace).Members)
                     {
                         if (c.Kind == EnvDTE.vsCMElement.vsCMElementInterface)
                         {
                             result.Add(c as EnvDTE.CodeInterface);
                         }
                     }
                 }
             }
         }
         if (i.ProjectItems != null)
         {
             EnumerateProjectItems(i.ProjectItems, result);
         }
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Recursively gets all the ProjectItem objects in a list of projectitems from a Project
        /// </summary>
        /// <param name="projectItems">The project items.</param>
        /// <returns></returns>
        public static IEnumerable <ProjectItem> GetProjectItems(EnvDTE.ProjectItems projectItems)
        {
            if (projectItems != null)
            {
                foreach (EnvDTE.ProjectItem item in projectItems)
                {
                    yield return(item);

                    if (item.SubProject != null)
                    {
                        foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.SubProject.ProjectItems))
                        {
                            yield return(childItem);
                        }
                    }
                    else
                    {
                        foreach (EnvDTE.ProjectItem childItem in GetProjectItems(item.ProjectItems))
                        {
                            yield return(childItem);
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private EnvDTE.ProjectItem FindItemByName(EnvDTE.ProjectItems projectItems, string name)
        {
            foreach (EnvDTE.ProjectItem item in projectItems)
            {
                if (item.Name == name)
                {
                    return(item);
                }
            }

            return(null);
        }
Ejemplo n.º 7
0
 //从项目项集合中搜索搜索子元素
 public static EnvDTE.ProjectItem GetItem(EnvDTE.ProjectItems items, string name)
 {
     Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
     for (var i = 1; i <= items.Count; i++)
     {
         if (items.Item(i).Name == name)
         {
             return(items.Item(i));
         }
     }
     return(null);
 }
Ejemplo n.º 8
0
        public static EnvDTE.ProjectItem FindFolderByName(EnvDTE.ProjectItems inItems, string withName)
        {
            var folders = withName.Split(new char[] { '.', '/', '\\' });

            if (folders.Length == 1)
            {
                var items = GetAllProjectItemsRecursive(inItems).Where(p => p.Name == withName);

                if (items.Count() == 1)
                {
                    return(items.First());
                }

                foreach (EnvDTE.ProjectItem r in items)
                {
                    if (r.Collection.Parent is EnvDTE.Project)
                    {
                        return(r);
                    }
                }

                return(items.First());
            }

            var startItemEnumerator = GetAllProjectItemsRecursive(inItems).Where(p => p.Name == folders[0])
                                      .Cast <ProjectItem>().GetEnumerator();

            EnvDTE.ProjectItem item = null;
            int    idx         = 1;
            string joinedNames = string.Empty;

            while (startItemEnumerator.MoveNext() && item == null)
            {
                item = startItemEnumerator.Current;
                for (idx = 1; idx < folders.Length; idx++)
                {
                    var subItems = item.ProjectItems.Cast <ProjectItem>();
                    joinedNames = string.Join(", ", subItems.Select(i => i.Name));
                    item        = subItems.Where(i => i.Name == folders[idx]).FirstOrDefault();
                    if (item == null)
                    {
                        break;
                    }
                }
            }
            if (item == null)
            {
                throw new ArgumentException(folders[idx] + " not found in path " + withName + " among " + joinedNames);
            }

            return(item);
        }
Ejemplo n.º 9
0
        private static EnvDTE.ProjectItem FindProjectItem(EnvDTE.ProjectItems items, string fullName, bool canCreateIfNotExists)
        {
            EnvDTE.ProjectItem item = (from i in items.Cast <EnvDTE.ProjectItem>()
                                       where i.Name == Path.GetFileName(fullName)
                                       select i).FirstOrDefault();
            if (item == null)
            {
                File.CreateText(fullName);
                item = items.AddFromFile(fullName);
            }

            return(item);
        }
Ejemplo n.º 10
0
        //// Code in this region was copied verbatim from templateWiz.cs,
        //// the VS code that invokes the IWizard interfaces and performs
        //// parameter replacement in the template.
        ////
        //// This code is duplicated here for just one reason -- the existing
        //// template implementation does not compute $rootnamespace$ at a point
        //// where we can use it, and it is required for our code generation.
        ////
        //// From the IWizard's perspective, $rootnamespace$ is not set in the
        //// replacements dictionary until ProjectItemFinishedGenerating is called.
        //// And by then, parameter substitution in the template has been done.

        /// <summary>
        /// Returns the namespace to use for the specified project items
        /// </summary>
        /// <param name="projItems">The project items used to compute the namespace.</param>
        /// <returns>The string value to use for the root namespace</returns>
        /// <remarks>Project resource</remarks>
        private static string FindNSOfItem(EnvDTE.ProjectItems projItems)
        {
            string extension = Path.GetExtension(projItems.ContainingProject.FileName);

            if ((String.Equals(extension, ".csproj", System.StringComparison.OrdinalIgnoreCase) == false) && (String.Equals(extension, ".vjsproj", System.StringComparison.OrdinalIgnoreCase) == false))
            {
                if (projItems.ContainingProject.Object is VSLangProj.VSProject)
                {
                    return(projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString());
                }
                return(MakeNameCompliant(Path.GetFileNameWithoutExtension(projItems.ContainingProject.FileName)));
            }

            if (projItems is EnvDTE.Project)
            {
                return(projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString());
            }
            else
            {
                string rootNamespace = string.Empty;
                while (projItems.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
                {
                    if (projItems.Parent is EnvDTE.Project)
                    {
                        if (rootNamespace.Length == 0)
                        {
                            return(projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString());
                        }
                        else
                        {
                            return(projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString() + "." + rootNamespace);
                        }
                    }
                    else
                    {
                        if (rootNamespace.Length == 0)
                        {
                            rootNamespace = MakeNameCompliant(((EnvDTE.ProjectItem)projItems.Parent).Name);
                        }
                        else
                        {
                            rootNamespace = MakeNameCompliant(((EnvDTE.ProjectItem)projItems.Parent).Name) + "." + rootNamespace;
                        }
                        projItems = ((EnvDTE.ProjectItem)projItems.Parent).Collection;
                    }
                }
                return(rootNamespace);
            }
        }
Ejemplo n.º 11
0
        public List <EnvDTE.ProjectItem> GetProjectItemsRecursively(EnvDTE.ProjectItems items)
        {
            var ret = new List <EnvDTE.ProjectItem>();

            if (items == null)
            {
                return(ret);
            }
            foreach (EnvDTE.ProjectItem item in items)
            {
                ret.Add(item);
                ret.AddRange(GetProjectItemsRecursively(item.ProjectItems));
            }
            return(ret);
        }
Ejemplo n.º 12
0
        private EnvDTE.ProjectItems GetOrCreateFolderItem(EnvDTE.ProjectItems parentItems, string folderPath)
        {
            var relativeFolderParts = folderPath.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string relativefolderPart in relativeFolderParts)
            {
                var folderItem = FindItemByName(parentItems, relativefolderPart);
                if (folderItem == null)
                {
                    folderItem = parentItems.AddFolder(relativefolderPart);
                }
                parentItems = folderItem.ProjectItems;
            }

            return(parentItems);
        }
Ejemplo n.º 13
0
        public static IEnumerable <EnvDTE.ProjectItem> GetAllProjectItemsRecursive(EnvDTE.ProjectItems projectItems)
        {
            foreach (EnvDTE.ProjectItem projectItem in projectItems)
            {
                if (projectItem.ProjectItems == null)
                {
                    continue;
                }

                foreach (EnvDTE.ProjectItem subItem in GetAllProjectItemsRecursive(projectItem.ProjectItems))
                {
                    yield return(subItem);
                }

                yield return(projectItem);
            }
        }
Ejemplo n.º 14
0
        public static List <EnvDTE.ProjectItem> FindProjectItems(EnvDTE.ProjectItems items, string match)
        {
            List <EnvDTE.ProjectItem> values = new List <EnvDTE.ProjectItem>();

            foreach (EnvDTE.ProjectItem item in items)
            {
                if (Regex.IsMatch(item.Name, match))
                {
                    values.Add(item);
                }
                if (item.ProjectItems.Count > 0)
                {
                    values.AddRange(FindProjectItems(item.ProjectItems, match));
                }
            }
            return(values);
        }
Ejemplo n.º 15
0
        private static EnvDTE.ProjectItems FindProjectFolder(EnvDTE.ProjectItems container, string suggestedPath)
        {
            var path = suggestedPath.Split('\\').Skip(1);

            foreach (var stepName in path)
            {
                foreach (var folder in container)
                {
                    if (folder != null && folder.As <EnvDTE.ProjectItem>().Name == stepName)
                    {
                        container = folder.As <EnvDTE.ProjectItem>().ProjectItems;
                        break;
                    }
                }
            }

            return(container);
        }
Ejemplo n.º 16
0
            private EnvDTE.ProjectItem GetProjItem(EnvDTE.ProjectItems projItems, string fileName)
            {
                if (projItems == null)
                {
                    return(null);
                }
                foreach (EnvDTE.ProjectItem projItem in projItems)
                {
                    if (projItem.Name == fileName)
                    {
                        return(projItem);
                    }
                    EnvDTE.ProjectItem theProjItem = GetProjItem(projItem.ProjectItems, fileName);
                    if (theProjItem != null)
                    {
                        return(theProjItem);
                    }
                }

                return(null);
            }
Ejemplo n.º 17
0
 private IEnumerable <string> EnumerateProjectFiles(EnvDTE.ProjectItems items)
 {
     if (items == null)
     {
         yield break;
     }
     foreach (var item in items)
     {
         var pi       = item as EnvDTE.ProjectItem;
         var fullPath = (item as EnvDTE.ProjectItem)?.Properties?.Item("FullPath")?.Value as string;
         if (!string.IsNullOrEmpty(fullPath))
         {
             yield return(fullPath);
         }
         if (pi.ProjectItems?.Count != 0)
         {
             foreach (var x in EnumerateProjectFiles(pi.ProjectItems))
             {
                 yield return(x);
             }
         }
     }
 }
        public static async Task <IEnumerable <EnvDTEProject> > GetAllEnvDTEProjectsAsync(DTE dte)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var envDTESolution = dte.Solution;

            if (envDTESolution == null ||
                !envDTESolution.IsOpen)
            {
                return(Enumerable.Empty <EnvDTEProject>());
            }

            var envDTEProjects = new Stack <EnvDTEProject>();

            foreach (EnvDTEProject envDTEProject in envDTESolution.Projects)
            {
                if (!EnvDTEProjectUtility.IsExplicitlyUnsupported(envDTEProject))
                {
                    envDTEProjects.Push(envDTEProject);
                }
            }

            var resultantEnvDTEProjects = new List <EnvDTEProject>();

            while (envDTEProjects.Any())
            {
                EnvDTEProject envDTEProject = envDTEProjects.Pop();

                if (EnvDTEProjectUtility.IsSupported(envDTEProject))
                {
                    resultantEnvDTEProjects.Add(envDTEProject);
                }
                else if (EnvDTEProjectUtility.IsExplicitlyUnsupported(envDTEProject))
                {
                    // do not drill down further if this project is explicitly unsupported, e.g. LightSwitch projects
                    continue;
                }

                EnvDTEProjectItems envDTEProjectItems = null;
                try
                {
                    // bug 1138: Oracle Database Project doesn't implement the ProjectItems property
                    envDTEProjectItems = envDTEProject.ProjectItems;
                }
                catch (NotImplementedException)
                {
                    continue;
                }

                // ProjectItems property can be null if the project is unloaded
                if (envDTEProjectItems != null)
                {
                    foreach (EnvDTEProjectItem envDTEProjectItem in envDTEProjectItems)
                    {
                        try
                        {
                            if (envDTEProjectItem.SubProject != null)
                            {
                                envDTEProjects.Push(envDTEProjectItem.SubProject);
                            }
                        }
                        catch (NotImplementedException)
                        {
                            // Some project system don't implement the SubProject property,
                            // just ignore those
                        }
                    }
                }
            }

            return(resultantEnvDTEProjects);
        }
 public ProjectItemCollectionLocator(ProjectItemCollection projectItems)
 {
     this.projectItems = projectItems;
 }
Ejemplo n.º 20
0
 public ProjectItemCollectionLocator(ProjectItemCollection projectItems)
 {
     this.projectItems = projectItems;
 }
Ejemplo n.º 21
0
        protected override void OnClosed(EventArgs e)
        {
            if (_savedChanges)
            {
                // Make sure the current document has the necessary
                // extensions loaded.
                // UNDONE: We should be able to do this with the document
                // closed or open as text as well via a registered service
                // on the ORMDesignerPackage, but this is sufficient for now.
                Dictionary <string, string> requiredExtensions = null;
                string[] loadedExtensions = null;
                foreach (IORMGenerator selectedGenerator in _mainBranch.SelectedGenerators)
                {
                    foreach (string requiredExtension in selectedGenerator.GetRequiredExtensionsForInputFormat("ORM"))
                    {
                        if (loadedExtensions == null)
                        {
                            loadedExtensions = (new ORMExtensionManager(_projectItem)).GetLoadedExtensions(_serviceProvider);
                        }
                        if (Array.BinarySearch <string>(loadedExtensions, requiredExtension) < 0)
                        {
                            if (requiredExtensions == null)
                            {
                                requiredExtensions = new Dictionary <string, string>();
                            }
                            else if (requiredExtensions.ContainsKey(requiredExtension))
                            {
                                continue;
                            }
                            requiredExtensions.Add(requiredExtension, requiredExtension);
                        }
                    }
                }
                if (requiredExtensions != null)
                {
                    _savedChanges = ORMExtensionManager.EnsureExtensions(_projectItem, _serviceProvider, requiredExtensions.Values);
                }
            }
            if (_savedChanges)
            {
#if VISUALSTUDIO_10_0
                ProjectItemGroupElement itemGroup = _originalItemGroup;
                ProjectRootElement      project   = _project;
#else // VISUALSTUDIO_10_0
                BuildItemGroup itemGroup = _originalItemGroup;
                Microsoft.Build.BuildEngine.Project project = _project;
#endif // VISUALSTUDIO_10_0
                EnvDTE.ProjectItem projectItem    = _projectItem;
                string             sourceFileName = _sourceFileName;
                Dictionary <string, PseudoBuildItem> pseudoItems = _pseudoItemsByOutputFormat;
                IDictionary <string, IORMGenerator>  generators  =
#if VISUALSTUDIO_15_0
                    ORMCustomTool.GetORMGenerators(_serviceProvider);
#else
                    ORMCustomTool.ORMGenerators;
#endif
                PseudoBuildItem pseudoItem;
                string          generatorNameData;        // The first string is the primary generator, others are the format modifiers, space delimited
                IVsShell        shell;

                Dictionary <string, IORMGenerator> generatorsWithTargetsByOutputFormat = null;
                IDictionary <string, ORMCustomToolUtility.GeneratorTargetSet> targetSetsByFormatName = null;
                foreach (PseudoBuildItem testPseudoItem in pseudoItems.Values)
                {
                    string         primaryGeneratorName;
                    IList <string> generatorTargets;
                    IORMGenerator  generator;
                    if (!string.IsNullOrEmpty(generatorNameData = testPseudoItem.CurrentGeneratorNames) &&
                        null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData)) &&
                        generators.TryGetValue(primaryGeneratorName, out generator) &&
                        null != (generatorTargets = generator.GeneratorTargetTypes) &&
                        0 != generatorTargets.Count)
                    {
                        (generatorsWithTargetsByOutputFormat ?? (generatorsWithTargetsByOutputFormat = new Dictionary <string, IORMGenerator>(StringComparer.OrdinalIgnoreCase)))[generator.ProvidesOutputFormat] = generator;
                    }
                }
                if (generatorsWithTargetsByOutputFormat != null)
                {
                    IDictionary <string, GeneratorTarget[]> docTargets = null;
                    EnvDTE.Document projectItemDocument = projectItem.Document;
                    string          itemPath;
                    if (projectItemDocument != null)
                    {
                        using (Stream targetsStream = ORMCustomToolUtility.GetDocumentExtension <Stream>(projectItemDocument, "ORMGeneratorTargets", itemPath = projectItem.get_FileNames(0), _serviceProvider))
                        {
                            if (targetsStream != null)
                            {
                                targetsStream.Seek(0, SeekOrigin.Begin);
                                docTargets = new BinaryFormatter().Deserialize(targetsStream) as IDictionary <string, GeneratorTarget[]>;
                            }
                        }
                    }
                    else if (null != (shell = _serviceProvider.GetService(typeof(SVsShell)) as IVsShell))
                    {
                        Guid       pkgId = typeof(ORMDesignerPackage).GUID;
                        IVsPackage package;
                        if (0 != shell.IsPackageLoaded(ref pkgId, out package) || package == null)
                        {
                            shell.LoadPackage(ref pkgId, out package);
                        }

                        // Temporarily load the document so that the generator targets can be resolved.
                        using (Store store = new ModelLoader(ORMDesignerPackage.ExtensionLoader, true).Load(projectItem.get_FileNames(0)))
                        {
                            docTargets = GeneratorTarget.ConsolidateGeneratorTargets(store as IFrameworkServices);
                        }
                    }

                    // We have generators that care about targets, which means that ExpandGeneratorTargets will
                    // product placeholder targets for these generators even if docTargets is currently null.
                    // This allows the dialog to turn on a generator before the data (or even extension) to feed
                    // it is available in the model and provides a smooth transition in and out of this placeholder
                    // state. It is up to the individual generators to proceed without explicit target data or
                    // to produce a message for the user with instructions on how to add the data to the model.
                    Dictionary <string, string> generatorNamesByOutputFormat = new Dictionary <string, string>();
                    foreach (KeyValuePair <string, PseudoBuildItem> pair in pseudoItems)
                    {
                        generatorNameData = pair.Value.CurrentGeneratorNames;
                        if (!string.IsNullOrEmpty(generatorNameData))
                        {
                            generatorNamesByOutputFormat[pair.Key] = ORMCustomToolUtility.GetPrimaryGeneratorName(generatorNameData);
                        }
                    }
                    targetSetsByFormatName = ORMCustomToolUtility.ExpandGeneratorTargets(generatorNamesByOutputFormat, docTargets
#if VISUALSTUDIO_15_0
                                                                                         , _serviceProvider
#endif // VISUALSTUDIO_15_0
                                                                                         );
                }

                Dictionary <string, BitTracker> processedGeneratorTargets = null;
                if (targetSetsByFormatName != null)
                {
                    processedGeneratorTargets = new Dictionary <string, BitTracker>();
                    foreach (KeyValuePair <string, ORMCustomToolUtility.GeneratorTargetSet> kvp in targetSetsByFormatName)
                    {
                        processedGeneratorTargets[kvp.Key] = new BitTracker(kvp.Value.Instances.Length);
                    }
                }

                if (null != itemGroup)
                {
#if VISUALSTUDIO_10_0
                    Dictionary <string, ProjectItemElement> removedItems = null;
                    foreach (ProjectItemElement item in itemGroup.Items)
#else // VISUALSTUDIO_10_0
                    Dictionary <string, BuildItem> removedItems = null;
                    foreach (BuildItem item in itemGroup)
#endif // VISUALSTUDIO_10_0
                    {
                        string        primaryGeneratorName;
                        string        outputFormat;
                        IORMGenerator generator;
                        if (null != (primaryGeneratorName = ORMCustomToolUtility.GetPrimaryGeneratorName(item.GetEvaluatedMetadata(ITEMMETADATA_ORMGENERATOR))) &&
                            string.Equals(item.GetEvaluatedMetadata(ITEMMETADATA_DEPENDENTUPON), sourceFileName, StringComparison.OrdinalIgnoreCase) &&
                            generators.TryGetValue(primaryGeneratorName, out generator) &&
                            pseudoItems.TryGetValue(outputFormat = generator.ProvidesOutputFormat, out pseudoItem))
                        {
                            generatorNameData = pseudoItem.CurrentGeneratorNames;
                            ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                            BitTracker processedForFormat = default(BitTracker);
                            if (targetSetsByFormatName != null)
                            {
                                if (targetSetsByFormatName.TryGetValue(outputFormat, out targetSet))
                                {
                                    processedForFormat = processedGeneratorTargets[outputFormat];
                                }
                            }

                            List <PseudoBuildInstance> originalInstances;
                            bool removeInstance = false;
                            if (string.IsNullOrEmpty(generatorNameData))
                            {
                                // The item is deleted, mark for removal
                                removeInstance = true;
                            }
                            else if (null != (originalInstances = pseudoItem.OriginalInstances))
                            {
                                for (int i = 0, count = originalInstances.Count; i < count && !removeInstance; ++i)
                                {
                                    PseudoBuildInstance instance = originalInstances[i];
                                    if (instance.IsRemoved)
                                    {
                                        continue;
                                    }

                                    GeneratorTarget[] targets = instance.OriginalGeneratorTargets;
                                    if (targetSet != null)
                                    {
                                        if (targets == null)
                                        {
                                            // Remove, if a target set is available then it must be used
                                            removeInstance = true;
                                        }
                                        else
                                        {
                                            int instanceIndex = targetSet.IndexOfInstance(targets, delegate(int ignoreInstance) { return(processedForFormat[ignoreInstance]); });
                                            if (instanceIndex == -1)
                                            {
                                                removeInstance = true;
                                            }
                                            else if (!processedForFormat[instanceIndex])
                                            {
                                                if (instance.OriginalGeneratorNames != generatorNameData)
                                                {
                                                    // This is a preexisting item, update its meta information
                                                    ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                                }
                                                processedForFormat[instanceIndex]       = true;
                                                processedGeneratorTargets[outputFormat] = processedForFormat;
                                                break;
                                            }
                                        }
                                    }
                                    else if (targets != null)
                                    {
                                        // Remove, formatter changed to one that does not use a generator target
                                        removeInstance = true;
                                    }
                                    else if (instance.OriginalGeneratorNames != generatorNameData)
                                    {
                                        // This is a preexisting item, update its meta information
                                        ORMCustomToolUtility.SetItemMetaData(item, ITEMMETADATA_ORMGENERATOR, generatorNameData);
                                    }

                                    if (removeInstance)
                                    {
                                        instance.IsRemoved = true;
                                    }
                                }
                            }

                            if (removeInstance)
                            {
                                if (removedItems == null)
                                {
#if VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, ProjectItemElement>();
#else // VISUALSTUDIO_10_0
                                    removedItems = new Dictionary <string, BuildItem>();
#endif // VISUALSTUDIO_10_0
                                }
                                removedItems[ORMCustomToolUtility.GetItemInclude(item)] = item;
                            }
                        }
                    }
                    if (removedItems != null)
                    {
                        EnvDTE.ProjectItems subItems = projectItem.ProjectItems;
#if VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, ProjectItemElement> removePair in removedItems)
                        {
                            ProjectItemElement      removeItem = removePair.Value;
                            ProjectElementContainer removeFrom;
                            if (null != (removeFrom = removeItem.Parent))
                            {
                                removeFrom.RemoveChild(removeItem);
                            }
#else // VISUALSTUDIO_10_0
                        foreach (KeyValuePair <string, BuildItem> removePair in removedItems)
                        {
                            project.RemoveItem(removePair.Value);
#endif // VISUALSTUDIO_10_0
                            try
                            {
                                EnvDTE.ProjectItem subItem = subItems.Item(removePair.Key);
                                if (subItem != null)
                                {
                                    subItem.Delete();
                                }
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                    }

#if !VISUALSTUDIO_10_0
                    // Empty item groups remove themselves from the project, we'll need
                    // to recreate below if the group is empty after the remove phase.
                    if (itemGroup.Count == 0)
                    {
                        itemGroup = null;
                    }
#endif
                }

                // Removes and changes are complete, proceed with adds for any new items
                string newItemDirectory          = null;
                string projectPath               = null;
                EnvDTE.ProjectItems projectItems = null;
                string tmpFile = null;
                // Adding a file to our special item group adds it to the build system. However,
                // it does not add it to the parallel project system, which is what displays in
                // the solution explorer. Therefore, we also explicitly add the item to the
                // project system as well. Unfortunately, this extra add automatically creates
                // a redundant item (usually in a new item group) for our adding item. Track anything
                // we add through the project system so that we can remove these redundant items from the
                // build system when we're done.
                Dictionary <string, string> sideEffectItemNames = null;
                try
                {
                    Action <IORMGenerator, string, ORMCustomToolUtility.GeneratorTargetSet, GeneratorTarget[]> addProjectItem = delegate(IORMGenerator generator, string allGenerators, ORMCustomToolUtility.GeneratorTargetSet targetSet, GeneratorTarget[] targetInstance)
                    {
                        if (itemGroup == null)
                        {
#if VISUALSTUDIO_10_0
                            itemGroup = project.AddItemGroup();
#else
                            itemGroup = project.AddNewItemGroup();
#endif
                            itemGroup.Condition = string.Concat(ITEMGROUP_CONDITIONSTART, _projectItemRelativePath, ITEMGROUP_CONDITIONEND);
                        }
                        if (newItemDirectory == null)
                        {
                            // Initialize general information
#if VISUALSTUDIO_10_0
                            projectPath = project.FullPath;
#else
                            projectPath = project.FullFileName;
#endif
                            newItemDirectory = Path.GetDirectoryName(new Uri(projectPath).MakeRelativeUri(new Uri((string)projectItem.Properties.Item("LocalPath").Value)).ToString());
                            projectItems     = projectItem.ProjectItems;
                        }

                        string defaultFileName  = generator.GetOutputFileDefaultName(sourceFileName);
                        string fileName         = targetInstance == null ? defaultFileName : ORMCustomToolUtility.GeneratorTargetSet.DecorateFileName(defaultFileName, targetInstance);
                        string fileRelativePath = Path.Combine(newItemDirectory, fileName);
                        string fileAbsolutePath = string.Concat(new FileInfo(projectPath).DirectoryName, Path.DirectorySeparatorChar, fileRelativePath);
#if VISUALSTUDIO_10_0
                        ProjectItemElement newBuildItem;
#else
                        BuildItem newBuildItem;
#endif
                        newBuildItem = generator.AddGeneratedFileItem(itemGroup, sourceFileName, fileRelativePath);

                        if (allGenerators != null)
                        {
                            ORMCustomToolUtility.SetItemMetaData(newBuildItem, ITEMMETADATA_ORMGENERATOR, allGenerators);
                        }

                        if (targetInstance != null)
                        {
                            ORMCustomToolUtility.SetGeneratorTargetMetadata(newBuildItem, targetInstance);
                        }

                        (sideEffectItemNames ?? (sideEffectItemNames = new Dictionary <string, string>()))[fileRelativePath] = null;
                        if (File.Exists(fileAbsolutePath))
                        {
                            try
                            {
                                projectItems.AddFromFile(fileAbsolutePath);
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                        else
                        {
                            if (tmpFile == null)
                            {
                                tmpFile = Path.GetTempFileName();
                            }
                            EnvDTE.ProjectItem newProjectItem = projectItems.AddFromTemplate(tmpFile, fileName);
                            string             customTool;
                            if (!string.IsNullOrEmpty(customTool = newBuildItem.GetMetadata(ITEMMETADATA_GENERATOR)))
                            {
                                newProjectItem.Properties.Item("CustomTool").Value = customTool;
                            }
                        }
                    };

                    foreach (KeyValuePair <string, PseudoBuildItem> keyedPseudoItem in pseudoItems)
                    {
                        pseudoItem = keyedPseudoItem.Value;
                        string allGenerators    = pseudoItem.CurrentGeneratorNames;
                        string primaryGenerator = ORMCustomToolUtility.GetPrimaryGeneratorName(allGenerators);
                        if (allGenerators == primaryGenerator)
                        {
                            allGenerators = null;
                        }
                        IORMGenerator generator    = generators[primaryGenerator];
                        string        outputFormat = generator.ProvidesOutputFormat;
                        ORMCustomToolUtility.GeneratorTargetSet targetSet = null;
                        if (targetSetsByFormatName != null)
                        {
                            targetSetsByFormatName.TryGetValue(outputFormat, out targetSet);
                        }

                        if (targetSet != null)
                        {
                            // OriginalInstances were already updated in the remove loop and processed
                            // instances were flagged. Find additional instances from the target set (created
                            // just now from the current model), not from the pseudoItem (created from the project
                            // files that possibly reflect a previous version of the model).
                            GeneratorTarget[][] instances = targetSet.Instances;
                            BitTracker          processed = processedGeneratorTargets[outputFormat];

                            for (int i = 0, count = instances.Length; i < count; ++i)
                            {
                                if (!processed[i])
                                {
                                    addProjectItem(generator, allGenerators, targetSet, instances[i]);
                                }
                            }
                        }
                        else if (pseudoItem.OriginalInstances == null)
                        {
                            addProjectItem(generator, allGenerators, null, null);
                        }
                        else
                        {
                            // Make sure there was an original instance that did not have a target set.
                            List <PseudoBuildInstance> originals = pseudoItem.OriginalInstances;
                            int i = 0, count = originals.Count;
                            for (; i < count; ++i)
                            {
                                if (originals[i].OriginalGeneratorTargets == null)
                                {
                                    break;
                                }
                            }

                            if (i == count)
                            {
                                addProjectItem(generator, allGenerators, null, null);
                            }
                        }
                    }
                }
                finally
                {
                    if (tmpFile != null)
                    {
                        File.Delete(tmpFile);
                    }
                }

                if (sideEffectItemNames != null)
                {
                    ORMCustomToolUtility.RemoveSideEffectItems(sideEffectItemNames, project, itemGroup);
                }

#if VISUALSTUDIO_10_0
                // Old group remove themselves when empty, but this is
                // not true in the new build system. Clean up as needed.
                if (itemGroup != null &&
                    itemGroup.Items.Count == 0)
                {
                    project.RemoveChild(itemGroup);
                }
#endif
                VSLangProj.VSProjectItem vsProjectItem = projectItem.Object as VSLangProj.VSProjectItem;
                if (vsProjectItem != null)
                {
                    vsProjectItem.RunCustomTool();
                }
            }
            base.OnClosed(e);
        }
Ejemplo n.º 22
0
 public static EnvDTE.ProjectItem GetProjectItemWithName(EnvDTE.ProjectItems items, string itemName)
 {
     return(GetAllProjectItemsRecursive(items).Cast <ProjectItem>().Where(i => i.Name == itemName).First());
 }
Ejemplo n.º 23
0
        private void ProcessProjectItems(IVsSolution solutionService, IVsHierarchy projectHierarchy, EnvDTE.ProjectItems projectItems)
        {
            if (projectItems != null)
            {
                foreach (EnvDTE.ProjectItem projectItem in projectItems)
                {
                    if (projectItem.SubProject != null)
                    {
                        ProcessProject(solutionService, projectItem.SubProject);
                    }
                    else
                    {
                        ProcessProjectItem(projectHierarchy, projectItem);

                        // Enter in recursion
                        ProcessProjectItems(solutionService, projectHierarchy, projectItem.ProjectItems);
                    }
                }
            }
        }