Beispiel #1
0
        public static bool DeleteProjectItem(EnvDTEProject envDTEProject, string path)
        {
            EnvDTEProjectItem projectItem = GetProjectItem(envDTEProject, path);

            if (projectItem == null)
            {
                return(false);
            }

            projectItem.Delete();
            return(true);
        }
Beispiel #2
0
        internal static async Task <bool> DeleteProjectItemAsync(EnvDTE.Project envDTEProject, string path)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            EnvDTE.ProjectItem projectItem = await GetProjectItemAsync(envDTEProject, path);

            if (projectItem == null)
            {
                return(false);
            }

            projectItem.Delete();
            return(true);
        }
        public static void DeleteItems(this IVsProject project, List <string> paths)
        {
            project.EnsureIsCheckout();
            foreach (string path in paths)
            {
                EnvDTE.ProjectItem item = project.GetProjectItem(path);
                if (item != null)
                {
                    if (File.Exists(path))
                    {
                        item.Delete();
                    }
                    else
                    {
                        item.Remove();
                    }
                }
            }

            var sliceCompileDependencies = paths.Select(
                p =>
            {
                return(Path.Combine(Path.GetDirectoryName(p),
                                    string.Format("SliceCompile.{0}.d", Path.GetFileNameWithoutExtension(p))));
            }).Distinct().ToList();

            foreach (var path in sliceCompileDependencies)
            {
                if (File.Exists(path))
                {
                    try
                    {
                        File.Delete(path);
                    }
                    catch (IOException)
                    {
                    }
                }
            }
        }
Beispiel #4
0
        // The docs say you can't rely on the 'inputFilePath' value, but there's *no other way* to know the base file name or the project!
        public int Generate(
            string inputFilePath,
            string inputFileContents,
            string defaultNamespace,
            IntPtr[] outputFileContents,
            out uint outputByteCount,
            IVsGeneratorProgress progress)
        {
            outputByteCount = 0;
            List <string>             generatedFiles = new List <string>();
            List <EnvDTE.ProjectItem> generatedItems = new List <EnvDTE.ProjectItem>();

            this.InputFilePath     = inputFilePath;
            this.InputFileContents = inputFileContents;
            this.DefaultNamespace  = defaultNamespace;

            this.GetProject();

            foreach (var iter in this.GetIterations())
            {
                try
                {
                    // Get the file for this iteration.
                    // TODO: correct for full/relative paths?
                    string file = this.GetFileName(iter);

                    // Keep track of generated files, we may need to add them to the project.
                    generatedFiles.Add(file);

                    // Create the file...
                    using (FileStream stream = File.Create(file))
                    {
                        byte[] content = this.GenerateContent(iter);

                        stream.Write(content, 0, content.Length);
                        ////stream.Close();
                    }

                    // Ensure the new item is a child of the input file...
                    EnvDTE.ProjectItem childItem = this.ProjectItem.ProjectItems.AddFromFile(file);
                    generatedItems.Add(childItem);
                    this.AdjustChildItem(iter, childItem);
                }
                catch (Exception ex)
                {
                    if (ErrorHandler.IsCriticalException(ex))
                    {
                        throw;
                    }
                }
            }

            // Delete any child items that aren't ours...
            foreach (EnvDTE.ProjectItem childItem in this.ProjectItem.ProjectItems)
            {
                if (!childItem.Name.EndsWith(this.GetDefaultExtension()) &&
                    !generatedItems.Contains(childItem))
                {
                    childItem.Delete();
                }
            }

            // Finally, generate the summary content...
            byte[] summaryContent = this.GenerateSummaryContent();

            if (summaryContent == null || summaryContent.Length == 0)
            {
                outputFileContents[0] = IntPtr.Zero;
                outputByteCount       = 0;
            }
            else
            {
                IntPtr mem = Marshal.AllocCoTaskMem(summaryContent.Length);
                Marshal.Copy(summaryContent, 0, mem, summaryContent.Length);

                outputFileContents[0] = mem;
                outputByteCount       = (uint)summaryContent.Length;
            }

            return(VSConstants.S_OK);
        }
        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)
            {
                // Delete the removed items from the project
                if (_removedItems != null)
                {
                    EnvDTE.ProjectItems subItems = _projectItem.ProjectItems;
                    foreach (string itemName in _removedItems.Keys)
                    {
                        try
                        {
                            EnvDTE.ProjectItem subItem = subItems.Item(itemName);
                            if (subItem != null)
                            {
                                subItem.Delete();
                            }
                        }
                        catch (ArgumentException)
                        {
                            // Swallow
                        }
                    }
                }
                // throw away the original build item group
                if (_originalItemGroup != null)
                {
                    try
                    {
#if VISUALSTUDIO_10_0
                        _project.RemoveChild(_originalItemGroup);
#else
                        _project.RemoveItemGroup(_originalItemGroup);
#endif
                    }
                    catch (InvalidOperationException)
                    {
                        // Swallow
                    }
                }

#if VISUALSTUDIO_10_0
                Dictionary <string, ProjectItemElement> removeItems = new Dictionary <string, ProjectItemElement>();
#else
                Dictionary <string, BuildItem> removeItems = new Dictionary <string, BuildItem>();
#endif
                string tmpFile = null;
                try
                {
                    EnvDTE.ProjectItems projectItems = _projectItem.ProjectItems;
#if VISUALSTUDIO_10_0
                    string itemDirectory = (new FileInfo((string)_project.FullPath)).DirectoryName;
                    foreach (ProjectItemElement item in _itemGroup.Items)
#else
                    string itemDirectory = (new FileInfo((string)_project.FullFileName)).DirectoryName;
                    foreach (BuildItem item in this._itemGroup)
#endif
                    {
                        string filePath = string.Concat(itemDirectory, Path.DirectorySeparatorChar, item.Include);
                        string fileName = (new FileInfo(item.Include)).Name;
                        if (File.Exists(filePath))
                        {
                            try
                            {
                                projectItems.AddFromFile(filePath);
                            }
                            catch (ArgumentException)
                            {
                                // Swallow
                            }
                        }
                        else
                        {
                            if (tmpFile == null)
                            {
                                tmpFile = Path.GetTempFileName();
                            }
                            EnvDTE.ProjectItem projectItem = projectItems.AddFromTemplate(tmpFile, fileName);
                            string             customTool  = item.GetMetadata(ITEMMETADATA_GENERATOR);
                            if (!string.IsNullOrEmpty(customTool))
                            {
                                projectItem.Properties.Item("CustomTool").Value = customTool;
                            }
                        }
                        removeItems[item.Include] = null;
                    }
                }
                finally
                {
                    if (tmpFile != null)
                    {
                        File.Delete(tmpFile);
                    }
                }

#if VISUALSTUDIO_10_0
                foreach (ProjectItemGroupElement group in this._project.ItemGroups)
#else
                foreach (BuildItemGroup group in this._project.ItemGroups)
#endif
                {
                    if (group.Condition.Trim() == this._itemGroup.Condition.Trim())
                    {
                        continue;
                    }
#if VISUALSTUDIO_10_0
                    foreach (ProjectItemElement item in group.Items)
#else
                    foreach (BuildItem item in group)
#endif
                    {
                        if (removeItems.ContainsKey(item.Include))
                        {
                            removeItems[item.Include] = item;
                        }
                    }
                }
                foreach (string key in removeItems.Keys)
                {
#if VISUALSTUDIO_10_0
                    ProjectItemElement      removeItem;
                    ProjectElementContainer removeFrom;
                    if (null != (removeItem = removeItems[key]) &&
                        null != (removeFrom = removeItem.Parent))
                    {
                        removeFrom.RemoveChild(removeItem);
                    }
#else
                    BuildItem removeItem = removeItems[key];
                    if (removeItem != null)
                    {
                        _project.RemoveItem(removeItem);
                    }
#endif
                }

                VSLangProj.VSProjectItem vsProjectItem = _projectItem.Object as VSLangProj.VSProjectItem;
                if (vsProjectItem != null)
                {
                    vsProjectItem.RunCustomTool();
                }
            }
            else
            {
#if VISUALSTUDIO_10_0
                _project.RemoveChild(_itemGroup);
#else
                _project.RemoveItemGroup(_itemGroup);
#endif
            }
            base.OnClosed(e);
        }
Beispiel #6
0
        static void CopyFilesAndFoldersRecursively(IEnumerable <ProjectItemWrapper> sourceProjectItems, EnvDTE.ProjectItems destinationProjectItems, Context.CopyOrAddAsLink howToDealWithCSharpFiles, int level = 1)
        {
            if (!StaticAbortProcessing)
            {
                foreach (ProjectItemWrapper sourceItem in sourceProjectItems)
                {
                    string sourceItemName     = sourceItem.GetName();
                    string sourceItemFullPath = sourceItem.GetFullPath();

                    //---------------------
                    // If it is a folder:
                    //---------------------
                    if (FoldersHelper.IsAFolder(sourceItemFullPath))
                    {
                        // If it is NOT the "Properties" folder (which exists by default in all projects):
                        if (level != 1 || sourceItemName.ToLower() != "properties")
                        {
                            // Create a new folder with the same name in the destination project:
                            EnvDTE.ProjectItem newFolder = destinationProjectItems.AddFolder(sourceItemName);

                            // Log:
                            AddLogEntryOnUIThread(string.Format(@"Created folder ""{0}"".", sourceItemName));

                            // Continue the recursion:
                            CopyFilesAndFoldersRecursively(sourceItem.GetChildItems(), newFolder.ProjectItems, howToDealWithCSharpFiles, level + 1);
                        }
                    }
                    //---------------------
                    // If it is a file:
                    //---------------------
                    else
                    {
                        EnvDTE.ProjectItem newFile = null;
                        if (sourceItemFullPath.ToLower().EndsWith(".cs"))
                        {
                            //---------------------
                            // C# file:
                            //---------------------

                            // Check if the file exists (this can be the case for example if we previously copied a file such as "UserControl.xaml", which automatically copies its child "UserControl.xaml.cs"):
                            EnvDTE.ProjectItem existingItem = FindProjectItemOrNull(sourceItemName, destinationProjectItems);

                            // Copy the file or add it as link:
                            if (howToDealWithCSharpFiles == Context.CopyOrAddAsLink.Copy)
                            {
                                // Copy only if the file is not already there:
                                if (existingItem == null)
                                {
                                    newFile = destinationProjectItems.AddFromFileCopy(sourceItemFullPath);
                                }

                                // Log:
                                AddLogEntryOnUIThread(string.Format(@"Copied file ""{0}"".", sourceItemName));
                            }
                            else if (howToDealWithCSharpFiles == Context.CopyOrAddAsLink.AddAsLink)
                            {
                                // Delete the copied file in order to replace it with a linked file (this can happen for example if we previously copied a file such as "UserControl.xaml", which automatically copies its child "UserControl.xaml.cs", so we need to delete this child):
                                if (existingItem != null)
                                {
                                    existingItem.Delete();
                                }

                                // Add the file "as link":
                                newFile = destinationProjectItems.AddFromFile(sourceItemFullPath);

                                // Log:
                                AddLogEntryOnUIThread(string.Format(@"Added file ""{0}"" as link.", sourceItemName));
                            }
                            else
                            {
                                throw new NotSupportedException();
                            }
                        }
                        else if (sourceItemFullPath.ToLower().EndsWith(".xaml") ||
                                 DoesFileHaveOneOfTheseExtensions(sourceItemFullPath, ExtensionsOfFilesToCopy)) // JPG, PNG, etc.
                        {
                            //---------------------
                            // XAML file:
                            //---------------------

                            // Copy the file:
                            newFile = destinationProjectItems.AddFromFileCopy(sourceItemFullPath);

                            // Log:
                            AddLogEntryOnUIThread(string.Format(@"Copied file ""{0}"".", sourceItemName));
                        }

                        // Continue the recursion:
                        if (newFile != null)
                        {
                            CopyFilesAndFoldersRecursively(sourceItem.GetChildItems(), newFile.ProjectItems, howToDealWithCSharpFiles, level + 1);
                        }
                    }

                    if (StaticAbortProcessing)
                    {
                        break;
                    }
                }
            }
        }