Example #1
0
        private static ProjectItems GetOrCreateFolder(ProjectItems projectItems, string folderName, bool createIfNotExists)
        {
            if (projectItems == null)
            {
                return(null);
            }

            ProjectItem subFolder;

            if (projectItems.TryGetFolder(folderName, out subFolder))
            {
                // Get the sub folder
                return(subFolder.ProjectItems);
            }
            else if (createIfNotExists)
            {
                Property property = projectItems.Parent.Properties.Item("FullPath");

                Debug.Assert(property != null, "Unable to get full path property from the project item");
                // Get the full path of this folder on disk and add it
                string fullPath = Path.Combine(property.Value, folderName);

                try {
                    return(projectItems.AddFromDirectory(fullPath).ProjectItems);
                }
                catch (NotImplementedException) {
                    // This is the case for F#'s project system, we can't add from directory so we fall back
                    // to this impl
                    return(projectItems.AddFolder(folderName).ProjectItems);
                }
            }

            return(null);
        }
        // 'parentItem' can be either a Project or ProjectItem
        private static ProjectItem GetOrCreateFolder(object parentItem, string fullPath, string folderName, bool createIfNotExists)
        {
            if (parentItem == null)
            {
                return(null);
            }

            ProjectItems projectItems = GetProjectItems(parentItem);

            if (projectItems.TryGetFolder(folderName, out var subFolder))
            {
                return(subFolder);
            }

            if (!createIfNotExists)
            {
                return(null);
            }

            try
            {
                return(projectItems.AddFromDirectory(fullPath));
            }
            catch (NotImplementedException)
            {
                // This is the case for F#'s project system, we can't add from directory so we fall back to this impl
                return(projectItems.AddFolder(folderName));
            }
        }
 private static void CopyProjectItems(ProjectItems sourceItems, ProjectItems targetItems)
 {
     foreach (ProjectItem projectItem in sourceItems)
     {
         ProjectItem tempItem = null;
         try
         {
             tempItem = targetItems.Item(projectItem.Name);
         }
         catch (ArgumentException)
         {
             if (projectItem.Kind == "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}")
             {
                 if (projectItem.Name != "Properties")
                 {
                     tempItem = targetItems.AddFolder(projectItem.Name);
                 }
             }
             else if (projectItem.Name != "packages.config")
             {
                 tempItem = targetItems.AddFromFile(projectItem.Properties.Item("LocalPath").Value as string);
             }
         }
         if (tempItem != null)
         {
             CopyProjectItems(projectItem.ProjectItems, tempItem.ProjectItems);
         }
     }
 }
        private ProjectItem EnsureDirectoryExists(ProjectItems projectItems, string folderName)
        {
            ProjectItem projectItem;

            try
            {
                var projectPath   = projectItems.ContainingProject.Properties.Item("FullPath").Value.ToString();
                var directoryPath = Path.Combine(projectPath, folderName);
                if (Directory.Exists(directoryPath))
                {
                    projectItem = projectItems.AddFromDirectory(directoryPath);
                }
                else
                {
                    projectItem = projectItems.AddFolder(folderName);
                }
            }
            catch (Exception ex)
            {
                var item = GetProjectItems(projectItems, new Comparer(folderName, OperatorType.Equals)).FirstOrDefault(); //GetProjectItems(projectItems, true, false, new Conditioner(folderName, StringComparisonType.Equal)).FirstOrDefault();
                if (item == null)
                {
                    throw new Exception(string.Format("Unknown exception while trying to find directory {0}", folderName));
                }
                projectItem = item;
            }
            return(projectItem);
        }
Example #5
0
        public static ProjectItems GetOrCreateFolder(ProjectItems projectItems, string viewModelLocation)
        {
            var path = viewModelLocation.Split('/', '\\').Where(p => !String.IsNullOrEmpty(p)).ToList();

            for (var i = 0; i < path.Count; i++)
            {
                var projectItem = projectItems.OfType <ProjectItem>().FirstOrDefault(p => p.Name == path[i]);
                if (projectItem == null)
                {
                    try
                    {
                        projectItem = projectItems.AddFolder(path[i]);
                    }
                    catch
                    {
                        throw new Exception($"Could not add a folder '{path[i]}' in the project!");
                    }
                }
                else if (projectItem.Kind != ProjectItemKindPhysicalFolder)
                {
                    throw new Exception($"The location of the viewmodel is not valid! Path '{path[i]}'.");
                }
                projectItems = projectItem.ProjectItems;
            }
            return(projectItems);
        }
        /// <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;
            }
        }
Example #7
0
        private void AddFromFileWithFolders(ProjectItems root, string name, string dir)
        {
            string pathToNow = null;
            var    tmp       = name.Split('\\');

            for (int i = 0; i < tmp.Length - 1; i++)
            {
                string thisDir = tmp[i];
                pathToNow = pathToNow == null ? thisDir : Path.Combine(pathToNow, thisDir);

                var item = Find(root, thisDir);
                if (item == null)
                {
                    //AddExistingFolder(root.ContainingProject, pathToNow);

                    //item = Find(root, thisDir);
                    //if (item == null)
                    item = root.AddFolder(thisDir);
                }

                root = item.ProjectItems;
            }

            if (Find(root, tmp[tmp.Length - 1]) == null)
            {
                root.AddFromFile(Path.Combine(dir, name));
            }
        }
Example #8
0
        /// <summary>
        ///getting the Full project path inorder to get the path of the ABP.dll
        ///in ABP.dll version number 1.0.1.5 it's uses the path 
        ///C:\Sestek.CallSteering\SestekCallSteering\Development\Sestek.CallSteering\Sestek.CallSteering.Web\App\Main\Views
        ///for the views.
        ///while in other versions it uses 
        ///C:\Sestek.CallSteering\SestekCallSteering\Development\Sestek.CallSteering\Sestek.CallSteering.Web\App\Main\views
        ///The difference in "View" world specialy in the first letter V
        /// </summary>
        /// <param name="parentItems"></param>
        /// <param name="deepFolder"></param>
        /// <returns>ProjectItem</returns>
        private ProjectItem AddAbpDeepFolder(ProjectItems parentItems, string deepFolder)
        {
            ProjectItem addedFolder = null;
            var projectPath = parentItems.ContainingProject.FullName;
            projectPath = projectPath.Remove(projectPath.IndexOf(".Web"));
            var tmpIndex = findIndex(projectPath, '\\');
            projectPath = projectPath.Remove(tmpIndex);

            projectPath += "packages\\";

            List<string> getFiles = Directory.GetDirectories(projectPath).Where(x=>x.Contains("Abp")).ToList();

            foreach (var file in getFiles)
            {
                //Checking ABP version
                var fileName = Path.GetFileName(file);
                var versionNumber = fileName.Substring(4);
                if (versionNumber == "1.0.1.5")
                {
                    deepFolder = deepFolder.Remove(deepFolder.IndexOf("views"), 5).Insert(deepFolder.IndexOf("views"), "Views");
                    break;
                }
            }

            foreach (var folder in deepFolder.Split('\\'))
            {
               
                var projectItem = FindProjectItem(parentItems, folder, ItemType.PhysicalFolder);
                addedFolder = projectItem ?? parentItems.AddFolder(folder);
                parentItems = addedFolder.ProjectItems;
            }   
            return addedFolder;
        }
Example #9
0
        // 'parentItem' can be either a Project or ProjectItem
        private static ProjectItem GetOrCreateFolder(
            Project project,
            object parentItem,
            string fullPath,
            string folderRelativePath,
            string folderName,
            bool createIfNotExists)
        {
            if (parentItem == null)
            {
                return(null);
            }

            ProjectItem subFolder;

            ProjectItems projectItems = GetProjectItems(parentItem);

            if (projectItems.TryGetFolder(folderName, out subFolder))
            {
                // Get the sub folder
                return(subFolder);
            }
            else if (createIfNotExists)
            {
                // The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that
                // does not belong to the project will throw. To work around that, we have to manually include
                // it into our project.
                if (project.IsJavaScriptProject() && Directory.Exists(fullPath))
                {
                    bool succeeded = IncludeExistingFolderToProject(project, folderRelativePath);
                    if (succeeded)
                    {
                        // IMPORTANT: after including the folder into project, we need to get
                        // a new ProjectItems snapshot from the parent item. Otherwise, reusing
                        // the old snapshot from above won't have access to the added folder.
                        projectItems = GetProjectItems(parentItem);
                        if (projectItems.TryGetFolder(folderName, out subFolder))
                        {
                            // Get the sub folder
                            return(subFolder);
                        }
                    }
                    return(null);
                }

                try
                {
                    return(projectItems.AddFromDirectory(fullPath));
                }
                catch (NotImplementedException)
                {
                    // This is the case for F#'s project system, we can't add from directory so we fall back
                    // to this impl
                    return(projectItems.AddFolder(folderName));
                }
            }

            return(null);
        }
Example #10
0
        private ProjectItem GetDirectoryItem(string target)
        {
            DTE         dte               = GetDTE();
            Array       projects          = dte?.ActiveSolutionProjects as Array;
            Project     currentProject    = projects?.GetValue(0) as Project;
            ProjectItem targetProjectItem = null;

            if (currentProject != null)
            {
                string rootDirectory = Path.GetDirectoryName(currentProject.FullName);
                Directory.CreateDirectory(Path.Combine(rootDirectory, target));

                Queue <string> paths           = new Queue <string>(target.Split('\\'));
                ProjectItems   currentItemList = currentProject.ProjectItems;
                bool           found           = false;

                while (paths.Any())
                {
                    string path = paths.Dequeue();

                    for (int index = 1; index <= currentItemList.Count; ++index)
                    {
                        if (currentItemList.Item(index).Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
                        {
                            if (!paths.Any())
                            {
                                targetProjectItem = currentItemList.Item(index);
                            }
                            else
                            {
                                currentItemList = currentItemList.Item(index).ProjectItems;
                            }

                            found = true;

                            break;
                        }
                    }

                    if (!found)
                    {
                        ProjectItem newItem = currentItemList.AddFolder(path);

                        if (!paths.Any())
                        {
                            targetProjectItem = newItem;
                        }
                        else
                        {
                            currentItemList = newItem.ProjectItems;
                        }
                    }
                }
            }

            return(targetProjectItem);
        }
        private ProjectItem GetOrCreateItem(ProjectItems items, string item)
        {
            ProjectItem parentProjectItem = DteHelperEx.FindItemByName(items, item, true);

            if (parentProjectItem == null)
            {
                parentProjectItem = items.AddFolder(item, SolutionFolderKind);
            }
            return(parentProjectItem);
        }
Example #12
0
        private ProjectItems WhereToAdd()
        {
            ProjectItems whereToAdd;

            if ((destFolder != String.Empty) && (destFolder != null))
            {
                //only works for a single foldername
                ProjectItem _folder = DteHelper.FindItemByName(this.Project.ProjectItems, destFolder, true);
                if (_folder != null)
                {
                    whereToAdd = _folder.ProjectItems;
                }
                else
                {
                    ProjectItems pitems = this.Project.ProjectItems;

                    string projectpath = Helpers.GetFullPathOfProjectItem(Project);

                    //folder doesnt exist
                    //create the folder
                    char[]   sep     = { '\\' };
                    string[] folders = destFolder.Split(sep);
                    for (int i = 0; i < folders.Length; i++)
                    {
                        projectpath += folders[i] + "\\";
                        //does the folder already exist?
                        _folder = DteHelper.FindItemByName(pitems, folders[i], true);
                        if (_folder != null)
                        {
                            //folder exists
                            pitems = _folder.ProjectItems;
                        }
                        else
                        {   //create folder
                            try
                            {
                                _folder = pitems.AddFolder(folders[i], EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                                pitems  = _folder.ProjectItems;
                            }
                            catch (Exception)
                            {
                                _folder = pitems.AddFromDirectory(projectpath);
                                pitems  = _folder.ProjectItems;
                            }
                        }
                    }
                    whereToAdd = _folder.ProjectItems;
                }
            }
            else
            {
                whereToAdd = this.Project.ProjectItems;
            }
            return(whereToAdd);
        }
        private void CopyFolder(DTE dte, string sourceFolder, string destFolder, ProjectItems parentProjectItems)
        {
            //first copy all files
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);
                if (File.Exists(dest))
                {
                    //if (MessageBox.Show("Project file " + name + " already exists. Overwrite?", "Overwrite file", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //Helpers.WriteToOutputWindow(dte, "Warning: File " + dest + " replaced.", false);
                        File.Copy(file, dest, true);
                    }
                }
                else
                {
                    File.Copy(file, dest, true);
                }


                try
                { //add file to project items
                    ProjectItem addItem = AddFromFile(parentProjectItems, dest);
                    addItem.Properties.Item("BuildAction").Value = 2;
                }
                catch (Exception)
                { //file already existed
                }
            }

            //second create the directories in the project if they are not there
            string[] sourcefolders = Directory.GetDirectories(sourceFolder);
            foreach (string sourcefolder in sourcefolders)
            {
                string name = Path.GetFileName(sourcefolder);
                string dest = Path.Combine(destFolder, name);

                //create folder in the project if it not exists
                ProjectItem projectFolder = null;
                try
                {
                    projectFolder = GetProjectItemByName(parentProjectItems, name);
                }
                catch (Exception)
                {
                }
                if (projectFolder == null)
                {
                    projectFolder = parentProjectItems.AddFolder(name, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                }
                CopyFolder(dte, sourcefolder, dest, projectFolder.ProjectItems);
            }
        }
    public static ProjectItem GetOrCreateFolder(this DTE dte)
    {
        ProjectItems projectItems = dte.GetSelectedProjectItems();

        if (projectItems.ContainingProject.TryFindProjectItemByName("Rules", out ProjectItem foundItem))
        {
            return(foundItem);
        }

        return(projectItems.AddFolder("Rules"));
    }
        private ProjectItem AddDeepFolder(ProjectItems parentItems, string deepFolder)
        {
            ProjectItem addedFolder = null;

            foreach (var folder in deepFolder.Split('\\'))
            {
                var projectItem = FindProjectItem(parentItems, folder, ItemType.PhysicalFolder);
                addedFolder = projectItem ?? parentItems.AddFolder(folder);
                parentItems = addedFolder.ProjectItems;
            }
            return(addedFolder);
        }
        private static ProjectItem GetOrCreateFolder(ProjectItems projectItems, string folder)
        {
            foreach (ProjectItem projectItem in projectItems)
            {
                if (projectItem.Kind == Constants.vsProjectItemKindPhysicalFolder && projectItem.Name == folder)
                {
                    return(projectItem);
                }
            }

            ProjectItem newFolder = projectItems.AddFolder(folder, Constants.vsProjectItemKindPhysicalFolder);

            return(newFolder);
        }
        private ProjectItems CreateAndGetFolders(Project project, string fileFolder)
        {
            var root            = GetRootFolder(project);
            var pathWithoutRoot = fileFolder.Replace(root, string.Empty);

            if (string.IsNullOrWhiteSpace(pathWithoutRoot))
            {
                return(project.ProjectItems);
            }
            var          folderTree        = pathWithoutRoot.Trim('\\').Split('\\');
            bool         createMode        = false;
            string       currentFolderPath = root;
            ProjectItems lastItemFound     = project.ProjectItems;

            foreach (var folder in folderTree)
            {
                if (createMode && lastItemFound != null)
                {
                    lastItemFound = lastItemFound.AddFolder(folder).ProjectItems;
                }
                else
                {
                    currentFolderPath += "\\" + folder;
                    var currentItemFound = _dte.Solution.FindProjectItem(currentFolderPath);
                    if (currentItemFound != null)
                    {
                        lastItemFound = currentItemFound.ProjectItems;
                    }
                    else
                    {
                        createMode    = true;
                        lastItemFound = lastItemFound.AddFolder(folder).ProjectItems;
                    }
                }
            }
            return(lastItemFound);
        }
 public override void Execute()
 {
     if (_createFolder)
     {
         _createdItem = DteHelper.FindItemByName(_targetCollection, _folderName, false);
         if (_createdItem == null)
         {
             _createdItem = _targetCollection.AddFolder(_folderName, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}");
         }
         _folderCollection = _createdItem.ProjectItems;
     }
     else
     {
         _folderCollection = _targetCollection;
     }
 }
Example #19
0
        private static void AddOrGetProjectFolderItem(ProjectItems projectItems, Stack <string> folderStack)
        {
            while (folderStack.Count > 0)
            {
                var currentFolder = folderStack.Pop();

                if (ContainsItem(currentFolder, projectItems))
                {
                    LastProjectItem = projectItems.Item(currentFolder);
                    AddOrGetProjectFolderItem(LastProjectItem.ProjectItems, folderStack);                     // recurse
                }
                else
                {
                    LastProjectItem = projectItems.AddFolder(currentFolder);
                    AddOrGetProjectFolderItem(LastProjectItem.ProjectItems, folderStack);                     // recurse
                }
            }
        }
        private ProjectItem AddOrCreateFolder(string folderName, ProjectItems parentCollection)
        {
            try
            {
                ProjectItem addedFolderProjectItem = parentCollection.AddFolder(folderName);
                string      relativePath           = GetPathRelativeToProject(TargetProject, addedFolderProjectItem.Properties.GetValue("FullPath", string.Empty));
                _logger.Log(String.Format(CultureInfo.CurrentCulture, Resources.FolderCreatedInTarget, relativePath, TargetProject.Name));

                return(addedFolderProjectItem);
            }
            catch (COMException comEx)
            {
                if (comEx.ErrorCode == -2147467259) //HRESULT 0x80004005
                {
                    return(IncludeExistingFolder(folderName, parentCollection));
                }
                throw;
            }
        }
Example #21
0
        private static ProjectItem CreateFolder(ProjectItems currentItems, string container)
        {
            var folderName = container;
            var index      = 1;

            // Keep looking for a unique name as long as we collide with some item.

            // NOTE(cyrusn): There shouldn't be a race condition here.  While it looks like a rogue
            // component could stomp on the name we've found once we've decided on it, they really
            // can't since we're running on the main thread.  And, if someone does stomp on us
            // somehow, then we really should just throw in that case.
            while (currentItems.FindItem(folderName, StringComparer.OrdinalIgnoreCase) != null)
            {
                folderName = container + index;
                index++;
            }

            return(currentItems.AddFolder(folderName));
        }
Example #22
0
        private static ProjectItem CreateFolder(ProjectItems currentItems, string container)
        {
            var folderName = container;
            int index = 1;

            // Keep looking for a unique name as long as we collide with some item.

            // NOTE(cyrusn): There shouldn't be a race condition here.  While it looks like a rogue
            // component could stomp on the name we've found once we've decided on it, they really
            // can't since we're running on the main thread.  And, if someone does stomp on us
            // somehow, then we really should just throw in that case.
            while (currentItems.FindItem(folderName, StringComparer.OrdinalIgnoreCase) != null)
            {
                folderName = container + index;
                index++;
            }

            return currentItems.AddFolder(folderName);
        }
Example #23
0
        ///// <summary>
        ///// Ensuures that a project of a given name exists in the solution
        ///// </summary>
        ///// <param name="store">Model from which to look for</param>
        ///// <param name="relativePath">Relative path where to create the new project if necessary (ending in the project name with .csproj)</param>
        ///// <param name="sourcePath">Source path of the template of the project</param>
        ///// <param name="updateAssemblyNameAndNamespace">Should we update the assembly name and namespace of the new project.</param>
        ///// <remarks>
        ///// Suppose you want to create add a new project named "MyProject.csproj" from a template (vs vsTemplate located in a sub folder of the location of the extension,
        ///// and you want to have similar namespaces:
        ///// <code>
        /////    StoreHostingProject.EnsureNamedProjectExistsInDslSolution(dsl.Store, "MyProject.csproj"
        /////                                          , Path.Combine(Path.GetDirectoryName(typeof(ATypeInMyExtension).Assembly.Location), @"Templates\MyProject\MyTemplate.vstemplate")
        /////                                          , true
        /////                                          );
        ///// </code>
        ///// </remarks>
        //public static void EnsureNamedProjectExistsInDslSolution(Store store, string relativePath, string sourcePath, bool updateAssemblyNameAndNamespace)
        //{
        //    // Verify that the relative path ends with csproj
        //    if (Path.GetExtension(relativePath) != ".csproj")
        //    {
        //        throw new ArgumentException("relativePath should be relative path of the .csproj file to create with respect to the solution, hence ending in .csproj", "relativePath");
        //    }

        //    Project project = Store2DTE.GetProjectForStore(store);
        //    Solution solution = project.DTE.Solution;
        //    Project newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.UniqueName == relativePath);
        //    if (newProject != null)
        //    {
        //        return;
        //    }

        //    string projectDirectory = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(project.FullName)), Path.GetFileNameWithoutExtension(relativePath));
        //    string projectPath = Path.Combine(projectDirectory, Path.GetFileName(relativePath));
        //    string projectSimpleName = Path.GetFileNameWithoutExtension(relativePath);

        //    // The project exist but is not in the solution: let's just add it.
        //    if (File.Exists(projectPath))
        //    {
        //        solution.AddFromFile(projectPath, false);
        //    }

        //    // The project does not exist: create it from a template
        //    else
        //    {
        //        newProject = project.DTE.Solution.AddFromTemplate(sourcePath, projectDirectory, Path.GetFileName(relativePath), false);

        //        // Well known workaround for C# and VB projects, AddFromTemplate returns null
        //        newProject = solution.Projects.OfType<Project>().FirstOrDefault(p => p.Name == projectSimpleName);

        //        // Update the assembly name and namespace if necessary
        //        if (updateAssemblyNameAndNamespace)
        //        {
        //            newProject.Properties.Item("AssemblyName").Value = project.Properties.Item("AssemblyName").Value.ToString().Replace("." + project.Name, "." + projectSimpleName);
        //            newProject.Properties.Item("DefaultNamespace").Value = project.Properties.Item("DefaultNamespace").Value.ToString() + "." + projectSimpleName;
        //        }

        //    }
        //}
        #endregion

        #region Adding a file or a link to a file
        /// <summary>
        /// Ensures that a file is present in the project
        /// </summary>
        /// <param name="store">Store containing a model</param>
        /// <param name="relativePath">relative path where the file should be located</param>
        /// <param name="sourcePath">Path of the file to copy if not already present in the solution</param>
        /// <example>
        /// if you have a file Adapter.tt, added to the VSIX, of type Content, and copied if newer, in a folder Temmplates of the extension project, you can add
        /// it to the GeneratedCode folder of the DSL by the following code:
        /// <code>
        ///    StoreHostingProject.EnsureFileInProject(dsl.Store, @"GeneratedCode\Adapter.tt",
        ///                                            Path.Combine(Path.GetDirectoryName(typeof(MyExtensionAuthoring).Assembly.Location), @"Templates\Adapter.tt"));
        /// </code>
        /// </example>
        public static void EnsureFileCopiedInDslProject(Store store, string relativePath, string sourcePath)
        {
            Contract.Requires(store != null);
            Contract.Requires(relativePath != null);
            Contract.Requires(sourcePath != null);

            Project project = Store2DTE.GetProjectForStore(store);

            string[] pathSegments = relativePath.Split('\\');

            ProjectItems parent = project.ProjectItems;

            // Find the folder (or create it if necessary)
            for (int i = 0; i < pathSegments.Length - 1; ++i)
            {
                ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]);
                if (folder == null)
                {
                    folder = parent.AddFolder(pathSegments[i]);
                }

                parent = folder.ProjectItems;
            }

            // Find the file and create it if necessary
            ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]);

            if (file == null)
            {
                string fileDirectory = Path.Combine(Path.GetDirectoryName(project.FullName), Path.GetDirectoryName(relativePath));
                string filePath      = Path.Combine(fileDirectory, Path.GetFileName(relativePath));

                // Case where the file is already there, but not added to the project
                if (File.Exists(filePath))
                {
                    parent.AddFromFile(filePath);
                }
                else
                {
                    parent.AddFromFileCopy(sourcePath);
                }
            }
        }
Example #24
0
        /// <summary>
        /// Ensures a link on a file is created in a project
        /// </summary>
        /// <param name="store">Store containing a model</param>
        /// <param name="uniqueProjectName">Unique project name of the project to which to add a link a a file</param>
        /// <param name="relativePathOfFileToCreate">Relative path to the link to create in the project described by <paramref name="relativePathOfFileToCreate"/></param>
        /// <param name="originalFileToLink">Path to the original file to link</param>
        public static void EnsureFileLinkInProject(Store store, string uniqueProjectName, string relativePathOfFileToCreate, string originalFileToLink)
        {
            Contract.Requires(store != null);
            Contract.Requires(relativePathOfFileToCreate != null);
            Contract.Requires(originalFileToLink != null);

            Project project = Store2DTE.GetProjectForStore(store);

            if (!string.IsNullOrWhiteSpace(uniqueProjectName))
            {
                project = project.DTE.Solution.Projects.OfType <Project>().FirstOrDefault(p => p.UniqueName == uniqueProjectName);
            }
            if (project == null)
            {
                return;
            }

            string[] pathSegments = relativePathOfFileToCreate.Split('\\');

            ProjectItems parent = project.ProjectItems;

            // Find the folder (or create it if necessary)
            for (int i = 0; i < pathSegments.Length - 1; ++i)
            {
                ProjectItem folder = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[i]);
                if (folder == null)
                {
                    folder = parent.AddFolder(pathSegments[i]);
                }

                parent = folder.ProjectItems;
            }

            // Find the file and create a link on the originalFileToLink it if necessary
            ProjectItem file = parent.OfType <ProjectItem>().FirstOrDefault(projectItem => projectItem.Name == pathSegments[pathSegments.Length - 1]);

            if (file == null)
            {
                parent.AddFromFile(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project.FullName), originalFileToLink)));
            }
        }
        private void LinkAllFiles(ProjectItems sourceItems, ProjectItems targetItems)
        {
            Dictionary <string, string> targetNames = new Dictionary <string, string>();

            foreach (ProjectItem item in targetItems)
            {
                targetNames.Add(item.Name, item.Name);
            }

            foreach (ProjectItem item in sourceItems)
            {
                if (targetNames.ContainsKey(item.Name))
                {
                    // do nothing
                }
                else if (item.Kind == Constants.vsProjectItemKindPhysicalFolder)
                {
                    try
                    {
                        ProjectItem targetItem = targetItems.AddFolder(item.Name);
                        LinkAllFiles(item.ProjectItems, targetItem.ProjectItems);
                    }
                    catch (COMException comEx)
                    {
                        if (comEx.ErrorCode == -2147467259) //HRESULT 0x80004005
                        {
                            ProjectItem targetItem = IncludeExistingFolder(item.Name, targetItems);
                            LinkAllFiles(item.ProjectItems, targetItem.ProjectItems);
                        }
                    }
                }
                else if (item.Kind == Constants.vsProjectItemKindPhysicalFile)
                {
                    for (short i = 0; i < item.FileCount; i++)
                    {
                        targetItems.AddFromFile(item.get_FileNames(i));
                    }
                }
            }
        }
        private static void AddFromItemTypeName(Project project, ProjectItems items, string path, string itemTypeName,
                                                NewItemDynamicParameters p, Solution2 sln)
        {
            if ("folder" == itemTypeName.ToLowerInvariant())
            {
                if (project.Object is SolutionFolder)
                {
                    var folder = project.Object as SolutionFolder;
                    folder.AddSolutionFolder(path);
                }
                else
                {
                    items.AddFolder(path, Constants.vsProjectItemKindPhysicalFolder);
                }
            }
            else
            {
                if (!itemTypeName.ToLowerInvariant().EndsWith(".zip"))
                {
                    itemTypeName += ".zip";
                }

                p.Category = GetSafeCategoryValue(p.Category, project.CodeModel);

                //todo: validate p.Category against available item/project tmps

                if (project.Object is SolutionFolder)
                {
                    SolutionFolder folder = project.Object as SolutionFolder;
                    NewTemplateItemInSolutionFolder(path, itemTypeName, sln, p, folder);
                }
                else
                {
                    var t = sln.GetProjectItemTemplate(itemTypeName, p.Category);
                    items.AddFromTemplate(t, path);
                }
            }
        }
        private static void IncludeFiles(DirectoryInfo folder, ProjectItems items, bool isSolutionFolder, string folderKind, string recursiveFolderName)
        {
            dte.StatusBar.Text = $"Creating Folder {recursiveFolderName}";

            foreach (var item in folder.GetFileSystemInfos())
            {
                if (item is FileInfo)
                {
                    try
                    {
                        dte.StatusBar.Text = $"Adding file: {item.FullName}";
                        items.AddFromFile(item.FullName);
                    }
                    catch (Exception)
                    {
                        throw new Exception($"Cannot add file: {item.FullName}");
                    }
                }
                else if (item is DirectoryInfo info)
                {
                    if (isSolutionFolder)
                    {
                        var solutionFolder    = (SolutionFolder)((Project)items.Parent).Object;
                        var newSolutionFolder = solutionFolder.AddSolutionFolder(item.Name).ProjectItems;
                        IncludeFiles(info, newSolutionFolder, isSolutionFolder, folderKind, recursiveFolderName + @"\" + item.Name);
                    }
                    else
                    {
                        var newItems = items.AddFolder(item.Name, folderKind).ProjectItems;
                        IncludeFiles(info, newItems, isSolutionFolder, folderKind, recursiveFolderName + @"\" + item.Name);
                    }
                }
            }

            dte.StatusBar.Text = $"Created Folder {recursiveFolderName}";
        }
Example #28
0
        public ProjectItem FindProjectItemFolderByEntity(Project project, string entityNameSpace)
        {
            ProjectItems answer     = project.ProjectItems;
            ProjectItem  answerItem = null;
            string       answerPath = new FileInfo(project.FullName).Directory.FullName + @"\";

            if (string.IsNullOrEmpty(entityNameSpace) == false)
            {
                string[] dirs = entityNameSpace.Split('.');
                for (int i = 0; i < dirs.Length; i++)
                {
                    string      folderName = dirs[i];
                    ProjectItem folderItem = GetProjectItemInItemsByName(answer, folderName);
                    if (folderItem == null) // اگر پوشه وجود نداشت
                    {
                        string folderPath = answerPath + folderName;
                        if (System.IO.Directory.Exists(folderPath) == false)
                        {
                            answer.AddFolder(folderName);
                        }
                        else
                        {
                            answer.AddFromDirectory(folderPath);
                        }
                    }
                    answerItem = GetProjectItemInItemsByName(answer, folderName);
                    answer     = answerItem.ProjectItems;
                    answerPath = answerItem.FileNames[1];
                }
            }
            else
            {
                return(null);
            }
            return(answerItem);
        }
Example #29
0
		private void AddFromFileWithFolders(ProjectItems root, string name, string dir)
		{
			string pathToNow = null;
			var tmp = name.Split('\\');
			for (int i = 0; i < tmp.Length - 1; i++)
			{
				string thisDir = tmp[i];
				pathToNow = pathToNow == null ? thisDir : Path.Combine(pathToNow, thisDir);

				var item = Find(root, thisDir);
				if (item == null)
				{
					//AddExistingFolder(root.ContainingProject, pathToNow);

					//item = Find(root, thisDir);
					//if (item == null)
					item = root.AddFolder(thisDir);
				}

				root = item.ProjectItems;
			}

			if (Find(root, tmp[tmp.Length - 1]) == null)
				root.AddFromFile(Path.Combine(dir, name));
		}
Example #30
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;
            }
        }
Example #31
0
        /// <summary>
        /// Adds 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 AddFilesAndFolders(ProjectItems source, ProjectItems target, ProjectType targetProjectType, int levels, IEnumerable<string> fileFilter)
        {
            Argument.IsNotNull("source", source);
            Argument.IsNotNull("target", target);

            string targetParentName = target.Parent.GetObjectName();

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

            if (levels == 0)
            {
                return;
            }

            levels--;

            foreach (ProjectItem sourceItem in source)
            {
                var sourceItemName = sourceItem.Name;

                if (sourceItem.IsLinkedFile())
                {
                    Log.Debug("Skipping item '{0}' because it is a linked file (so has another root project)", sourceItem.GetObjectName());

                    continue;
                }

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

                    continue;
                }

                ProjectItem existingTargetItem = null;
                foreach (ProjectItem targetItem in target)
                {
                    if (string.Equals(targetItem.Name, sourceItemName))
                    {
                        existingTargetItem = targetItem;
                        break;
                    }
                }

                bool isFolder = sourceItem.IsFolder();
                bool containsSubItems = isFolder || sourceItem.ContainsChildItems();

                if (existingTargetItem == null)
                {
                    if (!isFolder)
                    {
                        if (sourceItem.IsXamlFile() && ((targetProjectType == ProjectType.NET40) || (targetProjectType == ProjectType.NET45)))
                        {
                            Log.Debug("File '{0}' is a xaml file and the target project is NET40 or NET45. There is a bug in Visual Studio that does not allow to link xaml files in NET40, so a copy is created.", sourceItem.FileNames[0]);

                            // string targetFile = sourceItem.GetTargetFileName(target);
                            // File.Copy(sourceItem.FileNames[0], targetFile);
                            existingTargetItem = target.AddFromFileCopy(sourceItem.FileNames[0]);
                        }
                        else
                        {
                            Log.Debug("Adding link to file '{0}'", sourceItem.FileNames[0]);

                            try
                            {
                                // Linked file
                                existingTargetItem = target.AddFromFile(sourceItem.FileNames[0]);
                            }
                            catch (Exception ex)
                            {
                                var messageService = ServiceLocator.Default.ResolveType<IMessageService>();
                                messageService.ShowError(ex);
                            }
                        }
                    }
                    else
                    {
                        Log.Debug("Adding folder '{0}'", sourceItem.FileNames[0]);

                        string targetDirectory = sourceItem.GetTargetFileName(target.ContainingProject);
                        existingTargetItem = Directory.Exists(targetDirectory) ? target.AddFromDirectory(targetDirectory) : target.AddFolder(sourceItem.Name);
                    }

                    if (existingTargetItem != null)
                    {
                        Log.Debug("Added item '{0}'", existingTargetItem.Name);
                    }
                }

                bool isResourceFile = sourceItem.IsResourceFile();
                if (isResourceFile)
                {
                    SynchronizeResourceFileProperties(sourceItem, existingTargetItem, targetProjectType);
                }

                if (containsSubItems && !isResourceFile)
                {
                    AddFilesAndFolders(sourceItem.ProjectItems, existingTargetItem.ProjectItems, targetProjectType, levels, fileFilter);
                }
            }

            Log.Debug("Added files and folders to target '{0}'", targetParentName);
        }
Example #32
0
                private ProjectItem GetOrCreateParentItem(string filePath)
                {
                    if (string.IsNullOrEmpty(filePath))
                    {
                        return(templateProjectItem);
                    }

                    string projectDirectory = Path.GetDirectoryName(templateProjectItem.ContainingProject.FullName);
                    string fileDirectory    = Path.GetDirectoryName(filePath);

                    if (fileDirectory.ToLower() == projectDirectory.ToLower())
                    {
                        return(templateProjectItem);
                    }

                    ProjectItem result = templateProjectItem;

                    string         relativeFilePath = fileDirectory.Substring(projectDirectory.Length + 1);
                    Queue <string> pathParts        = new Queue <string>(relativeFilePath.Split('\\'));
                    ProjectItems   currentItemList  = templateProjectItem.ContainingProject.ProjectItems;

                    while (pathParts.Any())
                    {
                        bool   found    = false;
                        string pathPart = pathParts.Dequeue();

                        for (int index = 1; index <= currentItemList.Count; ++index)
                        {
                            ProjectItem item = currentItemList.Item(index);

                            if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder && item.Name == pathPart)
                            {
                                if (!pathParts.Any())
                                {
                                    result = item;
                                }
                                else
                                {
                                    currentItemList = item.ProjectItems;
                                }

                                found = true;

                                break;
                            }
                        }

                        if (!found)
                        {
                            ProjectItem newItem = currentItemList.AddFolder(pathPart);

                            if (!pathParts.Any())
                            {
                                result = newItem;
                            }
                            else
                            {
                                currentItemList = newItem.ProjectItems;
                            }
                        }
                    }

                    return(result);
                }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Execute(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            DTE dte = (DTE)await this.ServiceProvider.GetServiceAsync(typeof(DTE));

            foreach (SelectedItem item in dte.SelectedItems)
            {
                ProjectItem pi       = item.ProjectItem;
                string      tarsPath = null;
                switch (pi.ContainingProject.CodeModel.Language)
                {
                case CodeModelLanguageConstants.vsCMLanguageCSharp:
                    tarsPath = this.tars2csPath;
                    break;

                case CodeModelLanguageConstants.vsCMLanguageVC:
                    break;

                default:
                    break;
                }
                if (tarsPath != null)
                {
                    string srcFile = pi.FileNames[0];
                    string tmpFile = Path.GetTempPath() + pi.GetHashCode() + ".tars";
                    File.Copy(srcFile, tmpFile, true);
                    string targetPath = srcFile + "_";
                    string path       = Path.GetTempPath() + pi.GetHashCode();
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                    Directory.CreateDirectory(path);
                    ProjectItems pis = pi.Collection;
                    try
                    {
                        pis.Item(pi.Name + "_").Delete();
                    }
                    catch
                    {
                    }
                    if (Directory.Exists(targetPath))
                    {
                        Directory.Delete(targetPath, true);
                    }
                    pi = pis.AddFolder(pi.Name + "_");
                    ProcessStartInfo psi = new ProcessStartInfo(tarsPath, $"--base-package= \"{tmpFile}\"");
                    psi.UseShellExecute       = false;
                    psi.CreateNoWindow        = true;
                    psi.WorkingDirectory      = path;
                    psi.RedirectStandardError = true;
                    using (Process p = Process.Start(psi))
                    {
                        if (p?.WaitForExit(10 * 1000) == true)
                        {
                            IVsOutputWindowPane outputPane = (IVsOutputWindowPane)await this.ServiceProvider.GetServiceAsync(typeof(SVsGeneralOutputWindowPane));

                            outputPane.OutputString(p.StandardError.ReadToEnd());
                            //string targetPath = Path.GetDirectoryName(srcFile);
                            this.AddLinks(pi, path, targetPath);
                        }
                    }
                    Directory.Delete(path, true);
                    File.Delete(tmpFile);
                }
            }
        }
 private ProjectItem GetOrCreateItem(ProjectItems items, string item)
 {
     ProjectItem parentProjectItem = DteHelperEx.FindItemByName(items, item, true);
     if (parentProjectItem == null)
     {
         parentProjectItem = items.AddFolder(item, SolutionFolderKind);
     }
     return parentProjectItem;
 }
 /// <summary>
 /// returns the given folder or creates the folder
 /// </summary>
 /// <param name="projectItems"></param>
 /// <param name="p"></param>
 /// <param name="p_3"></param>
 /// <returns></returns>
 internal static ProjectItem GetProjectFolder(ProjectItems projectItems, string folderName, bool createIfMissing)
 {
     ProjectItem folderItem = GetProjectItemByName(projectItems, folderName);
     if (folderItem == null)
     {
         if (createIfMissing)
         {
             folderItem = projectItems.AddFolder(folderName, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
         }
     }
     return folderItem;
 }
        private static void AddFromItemTypeName(Project project, ProjectItems items, string path, string itemTypeName,
                                                NewItemDynamicParameters p, Solution2 sln)
        {
            if ("folder" == itemTypeName.ToLowerInvariant())
            {
                if (project.Object is SolutionFolder)
                {
                    var folder = project.Object as SolutionFolder;
                    folder.AddSolutionFolder(path);
                }
                else
                {
                    items.AddFolder(path, Constants.vsProjectItemKindPhysicalFolder);
                }
            }
            else
            {
                if (!itemTypeName.ToLowerInvariant().EndsWith(".zip"))
                {
                    itemTypeName += ".zip";
                }

                p.Category = GetSafeCategoryValue(p.Category, project.CodeModel);

                //todo: validate p.Category against available item/project tmps

                if (project.Object is SolutionFolder)
                {
                    SolutionFolder folder = project.Object as SolutionFolder;
                    NewTemplateItemInSolutionFolder(path, itemTypeName, sln, p, folder);
                }
                else
                {
                    var t = sln.GetProjectItemTemplate(itemTypeName, p.Category);
                    items.AddFromTemplate(t, path);
                }
            }
        }
        internal static ProjectItem GetFolder(string pathToParent, ProjectItems _projectItems, string folderName, bool createIfNotExists)
        {
            ProjectItem res = GetProjectItemByName(_projectItems, folderName);
            if (res == null)
            {
                if (createIfNotExists)
                {
                    //folder not in the project, so we try to create one
                    try
                    {
                        res = _projectItems.AddFolder(folderName, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
                    }
                    catch (Exception)
                    {

                        //the folder could not be created, maybe the folder exists, but isnot part of the project
                        string folderpath = Path.Combine(pathToParent, folderName);
                        if (Directory.Exists(folderpath))
                        {
                            //ok, folder is there, lets include it in the project
                            res = IncludeFolderInProject(pathToParent, _projectItems, folderName);
                        }
                    }
                }
            }
            return res;
        }
    private void CopyFolder(DTE dte, string sourceFolder, string destFolder, ProjectItems parentProjectItems)
    {
      //first copy all files
      string[] files = Directory.GetFiles(sourceFolder);
      foreach (string file in files)
      {
        string name = Path.GetFileName(file);
        string dest = Path.Combine(destFolder, name);
        if (File.Exists(dest))
        {
          //if (MessageBox.Show("Project file " + name + " already exists. Overwrite?", "Overwrite file", MessageBoxButtons.YesNo) == DialogResult.Yes)
          {
            //Helpers.WriteToOutputWindow(dte, "Warning: File " + dest + " replaced.", false);
            File.Copy(file, dest, true);
          }
        }
        else
        {
          File.Copy(file, dest, true);
        }


        try
        { //add file to project items
          ProjectItem addItem = AddFromFile(parentProjectItems, dest);
          addItem.Properties.Item("BuildAction").Value = 2;
        }
        catch (Exception)
        { //file already existed
        }
      }

      //second create the directories in the project if they are not there
      string[] sourcefolders = Directory.GetDirectories(sourceFolder);
      foreach (string sourcefolder in sourcefolders)
      {
        string name = Path.GetFileName(sourcefolder);
        string dest = Path.Combine(destFolder, name);

        //create folder in the project if it not exists
        ProjectItem projectFolder = null;
        try
        {
          projectFolder = GetProjectItemByName(parentProjectItems, name);
        }
        catch (Exception)
        {
        }
        if (projectFolder == null)
        {
          projectFolder = parentProjectItems.AddFolder(name, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
        }
        CopyFolder(dte, sourcefolder, dest, projectFolder.ProjectItems);
      }
    }
 /// <summary>
 /// Add the folder to the specified ProjectItem.
 /// </summary>
 /// <param name="parent"> The parent to which to add the folder. </param>
 /// <param name="folder"> The name of the folder to add. </param>
 /// <returns> Returns the ProjectItems of the newly created folder. </returns>
 protected virtual ProjectItems AddFolder(ProjectItems parent, string folder)
 {
     return(parent.AddFolder(folder).ProjectItems);
 }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(DestinationType destination)
        {
            string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);

            ProjectItems rootItems = null;

            switch (destination)
            {
            case DestinationType.Solution:
            {
            }
            break;

            case DestinationType.SolutionFolder:
            case DestinationType.Project:
            {
                // figure out if a project or project-folder was clicked
                try
                {
                    IntPtr             hierarchyPointer, selectionContainerPointer;
                    Object             selectedObject = null;
                    IVsMultiItemSelect multiItemSelect;
                    uint projectItemId;

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

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

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

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

                    dynamic dyn = selectedObject;
                    rootItems = (ProjectItems)(dyn.ProjectItems);
                }
                catch (Exception)
                {
                    // what the heck was clicked ???
                }
            }
            break;
            }

            string basePath;

            switch (destination)
            {
            default:
            case DestinationType.Solution:
            case DestinationType.SolutionFolder:
            {
                Solution2 sol2 = (Solution2)dte.Solution;
                basePath = Path.GetDirectoryName(sol2.FullName);
            }
            break;

            case DestinationType.Project:
            {
                basePath = Path.GetDirectoryName(rootItems.ContainingProject.FullName);
            }
            break;
            }

            try
            {
                DirectoryInfo folder = GetFolder(basePath, destination);
                if (folder == null)
                {
                    return;
                }

                const string folderKindVirtual  = @"{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}";
                const string folderKindPhysical = @"{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";

                string folderKind = folderKindVirtual;

                bool isSolutionFolder = false;
                switch (destination)
                {
                case DestinationType.Solution:
                {
                    Solution2 solution = (Solution2)dte.Solution;
                    rootItems        = solution.AddSolutionFolder(folder.Name).ProjectItems;
                    isSolutionFolder = true;
                }
                break;

                case DestinationType.SolutionFolder:
                {
                    var solutionFolder = (SolutionFolder)((Project)rootItems.Parent).Object;
                    rootItems        = solutionFolder.AddSolutionFolder(folder.Name).ProjectItems;
                    isSolutionFolder = true;
                }
                break;

                case DestinationType.Project:
                {
                    if (rootItems != null)
                    {
                        try
                        {
                            // try virtual folder first (C/C++ projects)
                            rootItems = rootItems.AddFolder(folder.Name, folderKind).ProjectItems;
                        }
                        catch (Exception)
                        {
                            // try physical folder (.net language projects)
                            folderKind = folderKindPhysical;
                            rootItems  = rootItems.AddFolder(folder.Name, folderKind).ProjectItems;
                        }
                    }
                }
                break;
                }

                IncludeFiles(folder, rootItems, isSolutionFolder, folderKind, folder.Name);
            }
            catch (Exception ex)
            {
                dte.StatusBar.Text = $"Error while Creating Folders: {ex.Message}";
            }
        }
        private ProjectItem AddOrCreateFolder(string folderName, ProjectItems parentCollection)
        {
            try
            {
                ProjectItem addedFolderProjectItem = parentCollection.AddFolder(folderName, Constants.vsProjectItemKindPhysicalFolder);
                string relativePath = GetPathRelativeToProject(TargetProject, addedFolderProjectItem.Properties.GetValue("FullPath", string.Empty));
                logger.Log(String.Format(CultureInfo.CurrentCulture, Resources.FolderCreatedInTarget, relativePath, TargetProject.Name));

                return addedFolderProjectItem;
            }
            catch (COMException comEx)
            {
                if (comEx.ErrorCode == -2147467259) //HRESULT 0x80004005
                {
                    return IncludeExistingFolder(folderName, parentCollection);
                }
                throw;
            }
        }