Beispiel #1
0
    static void FindProjectInternal(ProjectItems items, List<Project> projectList)
    {
        if (items == null)
        {
            return;
        }

        foreach (ProjectItem item in items)
        {
            Project project;
            if (item.SubProject != null)
            {
                project = item.SubProject;
            }
            else
            {
                project = item.Object as Project;
            }
            if (project != null)
            {
                if (ProjectKind.IsSupportedProjectKind(project.Kind))
                {
                    projectList.Add(project);
                }
                FindProjectInternal(project.ProjectItems, projectList);
            }
        }
    }
 private void CheckThatTTOutputIsNotUnderSCC(DTE service, Project project, ProjectItems projectItems)
 {
     foreach (ProjectItem childItem in projectItems)
     {
         if (childItem.Name.EndsWith(".tt"))
         {
             //ok, tt-File found, check, if the child is under source control
             if (childItem.ProjectItems.Count > 0)
             {
                 foreach (ProjectItem ttOutputItem in childItem.ProjectItems)
                 {
                     string itemname = Helpers.GetFullPathOfProjectItem(ttOutputItem); // ttOutputHelpers.GetFullPathOfProjectItem(item);
                     if(service.SourceControl.IsItemUnderSCC(itemname))
                     {
                         Helpers.LogMessage(service, this, "Warning: File " + itemname + " should not be under source control");
                         if (MessageBox.Show("Warning: File " + itemname + " should not be under source control. " + Environment.NewLine + Environment.NewLine + "Exclude file from source control?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                         {
                             Helpers.ExcludeItemFromSCC(service, project, ttOutputItem);
                             solved++;
                         }
                         else
                         {
                             ignored++;
                         }
                     }
                 }
             }
         }
         CheckThatTTOutputIsNotUnderSCC(service, project, childItem.ProjectItems);
     }
 }
        private static IEnumerable<Project> GetAllProjects(ProjectItems projectItems)
        {
            if(projectItems == null)
                yield break;

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

                    foreach(var project in GetAllProjects(projectItem.SubProject))
                    {
                        yield return project;
                    }
                }
                else
                {
                    foreach(var project in GetAllProjects(projectItem.ProjectItems))
                    {
                        yield return project;
                    }
                }
            }
        }
 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);
         }
     }
 }
    static void FindProjectInternal(ProjectItems items, List<Project> projectList)
    {
        if (items == null)
        {
            return;
        }

        foreach (ProjectItem item in items)
        {
            try
            {
                var project = item.SubProject;
                if (project == null)
                {
                    project = item.Object as Project;
                }
                if (project != null)
                {
                    if (ProjectKind.IsSupportedProjectKind(project.Kind))
                    {
                        projectList.Add(project);
                    }
                    FindProjectInternal(project.ProjectItems, projectList);
                }
            }
            catch (NotImplementedException)
            {
            }
            catch (NullReferenceException)
            {
            }
        }
    }
        public IEnumerable<ProjectItem> GetAllProjectItemsRecursive(ProjectItems projectItems)
        {
            foreach (ProjectItem projectItem in projectItems)
            {
                if (projectItem == null)
                {
                    continue;
                }

                if (projectItem.ProjectItems != null)
                {
                    foreach (ProjectItem subItem in GetAllProjectItemsRecursive(projectItem.ProjectItems))
                    {
                        // INFO: We only want real files, not folders etc.
                        // http://msdn.microsoft.com/en-us/library/z4bcch80%28v=vs.80%29.aspx
                        if (subItem.Kind == "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}")
                        {
                            yield return subItem;
                        }
                    }
                }

                // INFO: We only want real files, not folders etc.
                // http://msdn.microsoft.com/en-us/library/z4bcch80%28v=vs.80%29.aspx
                if (projectItem.Kind == "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}")
                {
                    yield return projectItem;
                }
            }
        }
Beispiel #7
0
 private static void DrillDownInProjectItems(ProjectItems projectItems, Review review, ProcessProjectItemScanResult psr, out bool found)
 {
     found = false;
     ProjectItems projItems;
     ProjectItem projectItem = projectItems.Parent as ProjectItem;
     //Check if the parent itself matches before searching for the parent's children.
     if (projectItem.Name == review.File)
     {
         psr.Invoke(projectItem, review);
         found = true;
         return;
     }
     foreach (ProjectItem projItem in projectItems)
     {
         projItems = projItem.ProjectItems;
         if ((projItems != null
              && (projItems.Count > 0)))
         {
             //  recurse to get to the bottom of the tree
             DrillDownInProjectItems(projItems, review, psr, out found);
             if (found)
             {
                 return;
             }
         }
         else if (projItem.Name == review.File && projItem.ContainingProject.Name == review.Project)
         {
             //  call back to the user function delegated to
             //  handle a single project item
             psr.Invoke(projItem, review);
             found = true;
             return;
         }
     }
 }
 private static ProjectItem CheckProjectItemsRecursive(ProjectItems projectItems, string path)
 {
     foreach (ProjectItem projectItem in projectItems)
     {
         if (projectItem.ProjectItems != null && projectItem.ProjectItems.Count > 0)
         {
             var x = CheckProjectItemsRecursive(projectItem.ProjectItems, path);
             if (x != null)
             {
                 return x;
             }
         }
         for (short i = 1; i <= projectItem.FileCount; i++)
         {
             try
             {
                 var filename = projectItem.FileNames[i];
                 if (filename != null)
                 {
                     if (filename.ToLower() == path)
                     {
                         return projectItem;
                     }
                 }
             }
             catch(Exception ex)
             {
                 
             }
         }
     }
     return null;
 }
        private static void AddFiles(Project project, ProjectItems items, Document currentDoc)
        {
            foreach (ProjectItem subItem in items)
            {
                if (currentDoc == subItem)
                    continue;

                if (subItem.Kind == PhysicalFolderKind || subItem.Kind == VirtualFolderKind)
                    AddFiles (project, subItem.ProjectItems, currentDoc);
                else if (subItem.Kind == PhysicalFileKind)
                {
                    if (subItem.Name.EndsWith (".cs")) // HACK: Gotta be a better way to know if it's C#.
                    {
                        for (short i = 0; i < subItem.FileCount; i++)
                        {
                            string path = subItem.FileNames[i];
                            if (path == currentDoc.FullName)
                                continue;

                            project.Sources.Add (Either<FileInfo, string>.A (new FileInfo (path)));
                        }
                    }
                }
            }
        }
Beispiel #10
0
        private List<string> FilesFromProjectItems(ProjectItems projectItems, string path)
        {
            if (projectItems == null)
                return null;

            List<string> result = new List<string>();

            foreach (ProjectItem item in projectItems)
            {
                if (item.Kind == ProjectItemKind.PhysicalFile)
                {
                    if (item.Name.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase) == true)
                    {
                        result.Add(item.FileNames[0]);
                    }
                }
                else if (item.Kind == ProjectItemKind.PhysicalFolder || item.Kind == ProjectItemKind.VirtualFolder)
                {
                    List<string> files = FilesFromProjectItems(item.ProjectItems, path + "\\" + item.Name );
                    result.AddRange(files);
                }
            }

            return result;
        }
        /// <summary>
        /// Generate a list of all files included in the Visual Studio solutions.
        /// </summary>
        /// <param name="projectName"></param>
        /// <param name="projectItems"></param>
        /// <param name="fileDetails"></param>
        private void CreateFileList(string projectName, ProjectItems projectItems, ref List<FileDetails> fileDetails)
        {
            foreach (ProjectItem projItem in projectItems)
            {
                if (projItem.ProjectItems != null && projItem.ProjectItems.Count > 0)
                {
                    // This is a sub project...
                    CreateFileList(projectName, projItem.ProjectItems, ref fileDetails);
                }

                if (projItem.Kind == Constants.vsProjectItemKindPhysicalFile)
                {
                    string entirePathAndFile = projItem.Properties.Item("FullPath").Value as string;

                    string fileName = Path.GetFileName(entirePathAndFile);
                    string path = Path.GetDirectoryName(entirePathAndFile);

                    FileDetails details = new FileDetails();

                    details.FileName = fileName;
                    details.Path = path;
                    details.Project = projectName;

                    fileDetails.Add(details);
                }
            }
        }
        /// <summary>
        /// Find the first project item with the given filename.
        /// </summary>
        /// <param name="projectItems">
        /// The list of project items to inspect recursively.
        /// </param>
        /// <param name="filename">
        /// The name of the project item to find.
        /// </param>
        /// <param name="recurse">
        /// Whether to recurse into project items.  Optional, true by default.
        /// </param>
        /// <returns>
        /// Returns the first project item with the given filename.
        /// </returns>
        public static ProjectItem FindProjectItem(ProjectItems projectItems, string filename, bool recurse = true)
        {
            if (projectItems == null)
            {
                return null;
            }

            foreach (ProjectItem item in projectItems)
            {
                if (string.Equals(item.Name, filename, StringComparison.OrdinalIgnoreCase))
                {
                    return item;
                }
                else if (recurse && item.ProjectItems != null)
                {
                    var subItem = ProjectUtilities.FindProjectItem(item.ProjectItems, filename);
                    if (subItem != null)
                    {
                        return subItem;
                    }
                }
            }

            return null;
        }
		static IEnumerable<ProjectItem> AllProjectItemsRecursive(ProjectItems projectItems)
		{
			if (projectItems == null)
				yield break;

			foreach (ProjectItem projectItem in projectItems)
			{
				if (projectItem.IsFolder() && projectItem.ProjectItems != null)
				{
					foreach (var folderProjectItem in AllProjectItemsRecursive(projectItem.ProjectItems))
					{
						yield return folderProjectItem;
					}
				}
				else if (projectItem.IsSolutionFolder())
				{
					foreach (var solutionProjectItem in AllProjectItemsRecursive(projectItem.SubProject.ProjectItems))
					{
						yield return solutionProjectItem;
					}
				}
				else
				{
					yield return projectItem;
				}
			}
		}
Beispiel #14
0
        public static ProjectItem FindProjectItem(ProjectItems items, string file)
        {
            var atom = file.Substring(0, file.IndexOf("\\") + 1);

            foreach (ProjectItem item in items)
            {
                if (atom.StartsWith(item.Name))
                {
                    // then step in
                    var 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)
                {
                    ProjectItem ritem = FindProjectItem(item.ProjectItems, file.Substring(file.IndexOf("\\") + 1));
                    if (ritem != null)
                        return ritem;
                }
            }
            return null;
        }
 /// <summary>
 /// Lookup the license header file within the given projectItems.
 /// </summary>
 /// <param name="projectItems"></param>
 /// <returns>A dictionary, which contains the extensions and the corresponding lines</returns>
 public static IDictionary<string, string[]> GetHeader (ProjectItems projectItems)
 {
   //Check for License-file within this level
   var headerFile = GetLicenseHeaderDefinitions (projectItems);
   if (!string.IsNullOrEmpty (headerFile))
     return LoadLicenseHeaderDefinition (headerFile); //Found a License header file on this level
   return null;
 }
    public ProjectItem AddDefinitionFileToOneProject (string fileName, ProjectItems projectItems)
    {
      var licenseHeaderDefinitionFileName = OpenFileDialogForExistingFile(fileName);

      if (licenseHeaderDefinitionFileName == string.Empty) return null;

      return AddFileToProject(projectItems, licenseHeaderDefinitionFileName);
    }
        private CodeElement FindType(ProjectItems projectItems, string typename)
        {
            var tokens = typename.Split('.');
            var path =new Queue<string>(tokens.ToList());
         

            while ( path.Count>0)
            {
                var itemName = path.Dequeue();
                var  found = false;
                Debug.WriteLine("Searching for " + itemName );
                if (projectItems == null) break;

                foreach (ProjectItem projectItem in projectItems)
                {
                    Debug.WriteLine("Checking " + projectItem.Name );
                    if (projectItem.Name.Equals(itemName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Debug.WriteLine("Found the project Item!!!");
                        found = true;

                        if (projectItem.ProjectItems != null && projectItem.ProjectItems.Count > 0)
                        {
                            Debug.WriteLine("Searching children");
                            // search the children of this projectitem
                            var foundHere = FindType(projectItem.ProjectItems, string.Join(".", path.ToArray()));

                            if (foundHere != null)
                            {
                                Debug.WriteLine("Found in children of " + projectItem.Name );

                                return foundHere;
                            }
                            Debug.WriteLine("Continuing looking");
                            
                            break;
                        }
                    }
                    else
                    {
                       var theType = FindType(projectItem, typename);

                        if (theType != null)
                        {
                            Debug.WriteLine("Found it!!!!" + theType.FullName );
                            return theType;
                        }
                    }
                    
                }
                if (!found)
                {
                    Debug.WriteLine("Didnt find this token" + itemName );
                    break;
                }
            }
            return null;
        }
        private void Generate(ProjectItems items)
        {
            if (items == null) return;

            foreach (ProjectItem item in items)
            {
                Generate(item);
            }
        }
Beispiel #19
0
 //private static void DoVcProject
 private static void DoProjectItems(
     ProjectItems projectItems
     )
 {
     foreach (ProjectItem projectItem in projectItems)
     {
         DoProjectItem(projectItem);
     }
 }
Beispiel #20
0
 internal static IEnumerable<ProjectItem> EnumerateCSharpFiles(ProjectItems list)
 {
     foreach (ProjectItem item in EnumerateItems(list))
     {
         if (item.Name.EndsWith(".cs"))
         {
             yield return item;
         }
     }
 }
 private static List<ProjectItem>Get(ProjectItems projectItems)
 {
     var items = new List<ProjectItem>();
     foreach (var projectItem in projectItems.Cast<ProjectItem>())
     {
         items.Add(projectItem);
         items.AddRange(Get(projectItem.ProjectItems));
     }
     return items;
 }
    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);
      }
    }
 private ProjectItem GetProjectItemByName(ProjectItems pitems, string name)
 {
     foreach (ProjectItem pitem in pitems)
     {
         if (pitem.Name.ToUpper() == name.ToUpper())
         {
             return pitem;
         }
     }
     throw new Exception("ProjectItem " + name + " not found");
 }
 public static ProjectItem GetProjectItemByName(ProjectItems pitems, string name)
 {
   foreach (ProjectItem pitem in pitems)
   {
     if (pitem.Name.ToUpper() == name.ToUpper())
     {
       return pitem;
     }
   }
   return null;
 }
        IList<Page> IVisualStudioService.GetPages(ProjectItems projectItems)
        {
            List<Page> pages = new List<Page>();

            foreach (ProjectItem item in projectItems)
            {
                pages.AddRange(GetPages(item));
            }

            return pages;
        }
Beispiel #26
0
		protected void WalkProjectItems( ProjectComponent project,  ProjectItems itemList )
		{
			if( itemList != null )
			{
				foreach( ProjectItem item in itemList )
				{
					VisitProject( project, item );
				
					WalkProjectItems( project, item.ProjectItems ); // Get children.
				}
			}
		}
        /// <summary>
        ///     Finds any item called "app.config" or "web.config" in the given list of project items and performs the given action for each.
        /// </summary>
        public virtual void FindConfigFiles(ProjectItems items, Action<ProjectItem> action)
        {
            DebugCheck.NotNull(items);
            DebugCheck.NotNull(action);

            foreach (ProjectItem projectItem in items)
            {
                if (projectItem.IsConfig())
                {
                    action(projectItem);
                }
            }
        }
        /// <summary>
        ///     Finds any item called "app.config" or "web.config" in the given list of project items and performs the given action for each.
        /// </summary>
        public virtual void FindConfigFiles(ProjectItems items, Action<ProjectItem> action)
        {
            Contract.Requires(items != null);
            Contract.Requires(action != null);

            foreach (ProjectItem projectItem in items)
            {
                if (projectItem.IsConfig())
                {
                    action(projectItem);
                }
            }
        }
Beispiel #29
0
 public static void AddItem(string ttInclude, string vsVersion, string netVersion, string ttIncludeName, string templatesFolder, HashSet<string> existingTTIncludes, ProjectItems templatesProjectItems)
 {
     var m = Regex.Match(ttInclude, @".(NET\d+).");
     if (!m.Success || m.Groups[1].Value == netVersion)
     {
         const string x64Key = @"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows";
         if (ttIncludeName.EndsWith(".x64"))
         {
             try
             {
                 if (Registry.LocalMachine.OpenSubKey(x64Key) == null)
                 {
                     return;
                 }
                 ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
             }
             catch
             {
                 return;
             }
         }
         else if (ttIncludeName.EndsWith(".x86"))
         {
             try
             {
                 if (Registry.LocalMachine.OpenSubKey(x64Key) != null)
                 {
                     return;
                 }
             }
             catch
             {
             }
             ttIncludeName = ttIncludeName.Substring(0, ttIncludeName.Length - 4);
         }
         var ttIncludeCopy = Path.Combine(templatesFolder, ttIncludeName);
         if (!existingTTIncludes.Contains(ttIncludeName))
         {
             templatesProjectItems.AddFromFile(ttIncludeCopy);
         }
         if (ttIncludeName.Contains("." + vsVersion + "." + netVersion + "."))
         {
             ttIncludeCopy = ttIncludeCopy.Substring(0, ttIncludeCopy.Length - 10) + ".merge.tt";
             ttIncludeName = Path.GetFileName(ttIncludeCopy);
             if (!existingTTIncludes.Contains(ttIncludeName))
             {
                 templatesProjectItems.AddFromFile(ttIncludeCopy);
             }
         }
     }
 }
        /// <summary>
        /// add all the item from the project that match one of the file includes
        /// </summary>
        private void AddNuSpecFilesCSharpVisualBasic(ProjectItems items, PackageInformation packageInfo, ProjectInformation projectInformation)
        {
            //-----get all the include able item here
            foreach (ProjectItem item in items)
            {
                //-----check if the item contains an item type property
                string itemType = ExtensionUtil.GetPropertyValue<string>(item.Properties, projectInformation.ItemType, null);
                if (!string.IsNullOrEmpty(itemType))
                {
                    object itemOutput = ExtensionUtil.GetPropertyValue<object>(item.Properties, projectInformation.ItemOutput, -1);
                    if (itemOutput != null && itemOutput.ToString() != "0")
                    {
                        string itemFullPath = ExtensionUtil.GetPropertyValue<string>(item.Properties, "FullPath", null);
                        if (!string.IsNullOrEmpty(itemFullPath))
                        {
                            try
                            {
                                string itemRelativePath = itemFullPath.Remove(0, Path.GetDirectoryName(packageInfo.ProjectFullName).Length + 1).Replace("\\", "/");
                                if (!itemRelativePath.Contains("/"))
                                    itemRelativePath = string.Format("/{0}", itemRelativePath);
                                LoggingManager.Instance.Logger.Debug(string.Format("checking item [{0}] for a possible fit", itemRelativePath));
                                FileInclude fileInclude = packageInfo.ProjectOptions.NuGetOptions.NuSpecOptions.Files.FileIncludes.FirstOrDefault(x =>
                                {
                                    string wildcard = string.Format("{0}/{1}", string.IsNullOrEmpty(x.Folder) ? "*" : x.Folder.Replace("\\", "/"), string.IsNullOrEmpty(x.Name) ? "*" : x.Name.Replace("\\", "/"));
                                    LoggingManager.Instance.Logger.Debug(string.Format("checking file include [{0}]", wildcard));
                                    return StringUtil.MatchesWildcard(itemRelativePath, wildcard);
                                });
                                if (fileInclude != null)
                                {
                                    packageInfo.NuSpecPackage.Files.Add(new Xml.NuGet.NuSpec.File() { Source = itemFullPath, Target = fileInclude.Target });
                                    LoggingManager.Instance.Logger.Debug(string.Format("added file [{0}] under [{1}]", itemFullPath, fileInclude.Target));
                                }
                                else
                                {
                                    LoggingManager.Instance.Logger.Info(string.Format("could not add file [{0}] because no fitting file include was found", itemFullPath));
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex is ThreadAbortException || ex is ThreadInterruptedException)
                                    throw;

                                LoggingManager.Instance.Logger.Error(string.Format("error occured while adding the item [{0}]", itemFullPath), ex);
                            }
                        }
                    }
                }
                //-----check sub items if any
                AddNuSpecFilesCSharpVisualBasic(item.ProjectItems, packageInfo, projectInformation);
            }
        }
Beispiel #31
0
        public static ProjectItem FindFolder(this ProjectItems items, string folderName)
        {
            var item = items.FindItem(folderName, StringComparer.OrdinalIgnoreCase);

            return(item.IsFolder() ? item : null);
        }
Beispiel #32
0
 protected override void AddFileToContainer(string fullPath, ProjectItems container)
 {
     // You can't add files to an Azure project
 }
Beispiel #33
0
        public void CreateLibraryFileFromProject(string fileName)
        {
            string file = ProjectItems.LoadFile("eWolfPodcasterCore.RawData.PodcastList.xml");

            File.WriteAllText(fileName, file);
        }
Beispiel #34
0
 static IEnumerable <ProjectItem> Items(ProjectItems ProjectItems)
 {
     return(ProjectItems.Cast <ProjectItem>().SelectMany(Items));
 }
Beispiel #35
0
 private static IEnumerable <string> EnumerateProjectItems(ProjectItems projectItems)
 {
     return(projectItems.Cast <ProjectItem>().SelectMany(p => EnumerateProjectItems(p)));
 }
Beispiel #36
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 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}";
            }
        }
Beispiel #38
0
 private static bool ContainsItem(string itemName, ProjectItems items)
 {
     return(items.Cast <ProjectItem>().Any(item => item.Name == itemName));
 }
Beispiel #39
0
        /// <summary>
        /// Get the list of all supported projects in the current solution. This method
        /// recursively iterates through all projects.
        /// </summary>
        public static IEnumerable <Project> GetAllProjects(this Solution solution)
        {
            if (solution == null || !solution.IsOpen)
            {
                yield break;
            }

            var projects = new Stack <Project>();

            foreach (Project project in solution.Projects)
            {
                if (!project.IsExplicitlyUnsupported())
                {
                    projects.Push(project);
                }
            }

            while (projects.Any())
            {
                Project project = projects.Pop();

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

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

                // ProjectItems property can be null if the project is unloaded
                if (projectItems != null)
                {
                    foreach (ProjectItem projectItem in projectItems)
                    {
                        try
                        {
                            if (projectItem.SubProject != null)
                            {
                                projects.Push(projectItem.SubProject);
                            }
                        }
                        catch (NotImplementedException)
                        {
                            // Some project system don't implement the SubProject property,
                            // just ignore those
                            continue;
                        }
                    }
                }
            }
        }
        public override void Execute()
        {
            if (string.IsNullOrEmpty(Content))
            {
                return;
            }

            DTE dte = base.GetService <DTE>(true);

            string fileWithContent = "";

            string testcontent = Content.Trim(new char[] { ' ', '\t', '\n', '\r' });

            if ((testcontent == "") || (testcontent == "dummy"))
            {
                //no content, check for sourcefile
                if (SourceFileName == null)
                {
                    return;
                }
                if (SourceFileName == "")
                {
                    return;
                }

                fileWithContent = this.SourceFileName;
                string templateBasePath = GetTemplateBasePath();
                if (!Path.IsPathRooted(fileWithContent))
                {
                    fileWithContent = Path.Combine(templateBasePath, fileWithContent);
                    fileWithContent = new FileInfo(fileWithContent).FullName;
                }
            }
            else
            {
                fileWithContent = Path.GetTempFileName();
                using (StreamWriter writer = new StreamWriter(fileWithContent, false))
                {
                    writer.Write(content);
                    writer.Close();
                }
            }

            if ((TargetFileName == null) || (TargetFileName == ""))
            {
                if (File.Exists(fileWithContent))
                {
                    TargetFileName = Path.GetFileName(fileWithContent);
                }
            }

            Project projectByName = Helpers.GetProjectByName(dte, projectName);

            if (projectByName != null)
            {
                ProjectItems whereToAdd = projectByName.ProjectItems;

                //check if item exists
                ProjectItem existingFile = null;
                try
                {
                    existingFile = Helpers.GetProjectItemByName(whereToAdd, TargetFileName);
                }
                catch (Exception)
                {
                }

                if (existingFile != null && !Overwrite)
                {
                    Helpers.LogMessage(dte, this, "File " + TargetFileName + " exists and will not be overwritten");
                    return;
                }

                //if targetfilename ends with .tt, we remove any file with the same start
                if (TargetFileName.EndsWith(".tt"))
                {
                    //is there any file with the same name, but different extension
                    foreach (ProjectItem pitem in whereToAdd)
                    {
                        if (Path.GetFileNameWithoutExtension(pitem.Name.ToUpper()) == Path.GetFileNameWithoutExtension(TargetFileName.ToUpper()))
                        {
                            string deletedFilepath = Helpers.GetFullPathOfProjectItem(pitem);  //pHelpers.GetFullPathOfProjectItem(item);
                            //delete the file
                            pitem.Remove();
                            File.Delete(deletedFilepath);
                            break;
                        }
                    }
                }

                ProjectItem _ProjectItem = Helpers.AddFromTemplate(whereToAdd, fileWithContent, this.TargetFileName);
            }
            else
            {
                //do nothing if project is not found
                //throw new Exception("Project with name " + projectName + " not found in solution");
            }
        }
Beispiel #41
0
 protected virtual void AddFileToContainer(string fullPath, string folderPath, ProjectItems container)
 {
     container.AddFromFileCopy(fullPath);
 }
Beispiel #42
0
        public static void AddNewItem(string templateName, string name, string extension, string destinationPath)
        {
            var project = GetActiveProject();

            if (project != null)
            {
                DTE dte      = VsAppShell.Current.GetGlobalService <DTE>();
                var solution = (Solution2)dte.Solution;

                // Construct name of the compressed template
                var compressedTemplateName = Path.ChangeExtension(templateName, "zip");
                var templatePath           = Path.Combine(GetProjectItemTemplatesFolder(), compressedTemplateName);

                // We will be extracting template contents into a temp folder
                var uncompressedTemplateFolder = Path.Combine(Path.GetTempPath(), templateName);
                var uncompressedTemplateName   = Path.ChangeExtension(compressedTemplateName, "vstemplate");
                var tempTemplateFile           = Path.Combine(uncompressedTemplateFolder, uncompressedTemplateName);

                // Extract template files overwriting any existing ones
                using (ZipArchive zip = ZipFile.OpenRead(templatePath)) {
                    foreach (ZipArchiveEntry entry in zip.Entries)
                    {
                        if (!Directory.Exists(uncompressedTemplateFolder))
                        {
                            Directory.CreateDirectory(uncompressedTemplateFolder);
                        }
                        string destFilePath = Path.Combine(uncompressedTemplateFolder, entry.FullName);
                        if (!string.IsNullOrEmpty(entry.Name))
                        {
                            entry.ExtractToFile(destFilePath, true);
                        }
                        else
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
                        }
                    }

                    // Given path to the project or a folder in it, generate unique file name
                    var fileName = GetUniqueFileName(destinationPath, name, extension);

                    // Locate folder in the project
                    var projectFolder = Path.GetDirectoryName(project.FullName);
                    if (destinationPath.StartsWith(projectFolder, StringComparison.OrdinalIgnoreCase))
                    {
                        ProjectItems projectItems = project.ProjectItems;

                        if (destinationPath.Length > projectFolder.Length)
                        {
                            var relativePath = destinationPath.Substring(projectFolder.Length + 1);

                            // Go into folders and find project item to insert the file in
                            while (relativePath.Length > 0)
                            {
                                int    index = relativePath.IndexOf('\\');
                                string folder;
                                if (index >= 0)
                                {
                                    folder       = relativePath.Substring(0, index);
                                    relativePath = relativePath.Substring(index + 1);
                                }
                                else
                                {
                                    folder       = relativePath;
                                    relativePath = string.Empty;
                                }
                                try {
                                    var item = projectItems.Item(folder);
                                    projectItems = item.ProjectItems;
                                } catch (COMException) {
                                    return;
                                }
                            }
                        }
                        projectItems?.AddFromTemplate(tempTemplateFile, Path.GetFileName(fileName));
                    }
                }
            }
        }
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///	 Gets a VshierarchyItem for the designer file if possible.
        ///	 Will create new file if specified and not existing.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        protected virtual VsHierarchyItem GetDesignerItem(VsHierarchyItem itemCode, bool create)
        {
            VsHierarchyItem itemDesigner = null;

            if (itemCode != null)
            {
                // Calculate codebehind and designer file paths
                string codeBehindFile = itemCode.FullPath();
                string designerFile   = null;
                if (_isPartialClassDisabled)
                {
                    designerFile = codeBehindFile;
                }
                else if (!string.IsNullOrEmpty(codeBehindFile))
                {
                    designerFile = codeBehindFile.Insert(codeBehindFile.LastIndexOf("."), ".designer");
                }

                // Try to locate existing designer file
                if (!string.IsNullOrEmpty(designerFile))
                {
                    itemDesigner = VsHierarchyItem.CreateFromMoniker(designerFile, _hierarchy);
                    if (itemDesigner != null)
                    {
                        return(itemDesigner);
                    }
                }

                // Create empty designer file if requested
                if (create && !string.IsNullOrEmpty(designerFile))
                {
                    ProjectItem projectItemCode = itemCode.ProjectItem();
                    if (projectItemCode != null)
                    {
                        ProjectItems projectItems = projectItemCode.Collection;
                        if (projectItems != null)
                        {
                            try
                            {
                                using (StreamWriter sw = File.CreateText(designerFile))
                                {
                                    sw.WriteLine(" ");
                                }

                                projectItems.AddFromFileCopy(designerFile);
                            }
                            catch
                            {
                            }

                            itemDesigner = VsHierarchyItem.CreateFromMoniker(designerFile, _hierarchy);
                            if (itemDesigner != null)
                            {
                                return(itemDesigner);
                            }
                        }
                    }
                }
            }

            return(itemDesigner);
        }
        /// <summary>
        /// Lookup the license header file within the given projectItems.
        /// </summary>
        /// <param name="projectItems"></param>
        /// <returns>A dictionary, which contains the extensions and the corresponding lines</returns>
        public static IDictionary <string, string[]> SearchItemsDirectlyGetHeaderDefinition(ProjectItems projectItems)
        {
            // Check for License-file within this level
            var headerFileName = SearchItemsDirectlyGetHeaderDefinitionFileName(projectItems);

            if (!string.IsNullOrEmpty(headerFileName))
            {
                return(LoadHeaderDefinition(headerFileName)); // Found a License header file on this level
            }
            return(null);
        }
Beispiel #45
0
        private async Task DeleteProjectItemAsync(Project project, string deleteFileName)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            ProjectItems prjItems   = project.ProjectItems;
            ProjectItem  deleteItem = prjItems.OfType <ProjectItem>()
                                      .Where(c =>
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                return(c.Name.ToLower() == deleteFileName.ToLower());
            })
                                      .FirstOrDefault();

#pragma warning disable VSTHRD109 // 使用非同步方法時請切換而非判斷提示
            ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning restore VSTHRD109 // 使用非同步方法時請切換而非判斷提示

            try
            {
                deleteItem.Remove();
            }
            catch (Exception ex) { }

            if (deleteItem != null)
            {
                var    deletePhysicalName = deleteItem.Properties.Item("FullPath");
                string fullPath           = deletePhysicalName.Value.ToString();
                try
                {
                    string deletePath = Path.GetDirectoryName(fullPath);
                    try
                    {
                        File.Delete(fullPath);
                    }
                    catch { }
                    //真的移除掉該實體檔案
                    switch (deleteFileName.ToLower())
                    {
                    case "web.config":
                        File.Delete(Path.Combine(deletePath, "Web.Debug.config"));
                        File.Delete(Path.Combine(deletePath, "Web.Release.config"));
                        break;

                    case "global.asax":
                        File.Delete(Path.Combine(deletePath, "global.asax.cs"));
                        break;

                    case "app_start":
                        File.Delete(Path.Combine(deletePath, "RouteConfig.cs"));
                        File.Delete(Path.Combine(deletePath, "WebApiConfig.cs"));
                        Directory.Delete(deletePath);
                        break;

                    case "properties":
                        File.Delete(Path.Combine(deletePath, "AssemblyInfo.cs"));
                        break;

                    case "views":
                        File.Delete(Path.Combine(deletePath, "web.config"));
                        break;
                    }
                }
                catch (Exception ex) { }
            }
        }
        private string[] GetFilesFromHierarchy(string filename, string[] additionalBuffers)
        {
            int          itemid;
            IVsHierarchy hier = ShellDocumentManager.GetHierarchyForFile(serviceProvider, filename, out itemid);

            if (itemid != __VSITEMID.VSITEMID_NIL && hier != null)
            {
                object o;
                hier.GetProperty(itemid, __VSHPROPID.VSHPROPID_ExtObject, out o);
                ProjectItem projectItem = o as ProjectItem;

                if (projectItem != null)
                {
                    ArrayList items = new ArrayList();
                    if (DoesFileNeedCheckout(filename))
                    {
                        items.Add(filename);
                    }
                    if (projectItem.ProjectItems != null)
                    {
                        foreach (ProjectItem childItem in projectItem.ProjectItems)
                        {
                            if (DoesFileNeedCheckout(childItem.get_FileNames(0)))
                            {
                                items.Add(childItem.get_FileNames(0));
                            }
                        }
                    }

                    /* asurt 100273
                     *  after much trauma, we're going to not do this anymore...
                     *
                     * // also add the project above it
                     * //
                     * if (projectItem.ContainingProject != null) {
                     *  string containingFileName = projectItem.ContainingProject.FileName;
                     *
                     *  try {
                     *      if (containingFileName != null && containingFileName.Length > 0 && System.IO.File.Exists(containingFileName)) {
                     *          if (DoesFileNeedCheckout(containingFileName))
                     *              items.Add(containingFileName);
                     *      }
                     *  }
                     *  catch {
                     *  }
                     * }
                     */

                    // if needed add the LicX file to the list of files to be checked out.
                    //
                    if (additionalBuffers != null && additionalBuffers.Length > 0 && projectItem.ContainingProject != null)
                    {
                        foreach (string bufferName in additionalBuffers)
                        {
                            ProjectItems pitems = projectItem.ContainingProject.ProjectItems;

                            foreach (ProjectItem item in pitems)
                            {
                                System.IO.FileInfo fi = new System.IO.FileInfo(item.get_FileNames(0));
                                if ((String.Compare(bufferName, fi.Name, true, CultureInfo.InvariantCulture) == 0) || (String.Compare(bufferName, fi.FullName, true, CultureInfo.InvariantCulture) == 0))
                                {
                                    items.Add(fi.FullName);
                                }
                            }
                        }
                    }

                    string[] fileItems = new string[items.Count];
                    items.CopyTo(fileItems, 0);
                    return(fileItems);
                }
            }


            return(new string[] { filename });
        }
Beispiel #47
0
        /// <summary>
        /// Finds the assembly information project item.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <returns></returns>
        private ProjectItem FindAssemblyInfoProjectItem(ProjectItems items)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            return(FindProjectItem(items, "assemblyinfo"));
        }
        private static bool RemoveDeletedItems(string extractedFolder, ProjectItems projectItems, string projectFolder)
        {
            bool itemChanged = false;

            //Handle file & folder deletes
            foreach (ProjectItem projectItem in projectItems)
            {
                string name = projectItem.FileNames[0];
                if (string.IsNullOrEmpty(name))
                {
                    continue;
                }

                if (CrmDeveloperExtensions2.Core.StringFormatting.FormatProjectKind(projectItem.Kind) == VSConstants.GUID_ItemType_PhysicalFile.ToString())
                {
                    name = Path.GetFileName(name);
                    // Do not delete the mapping file
                    if (name == CrmDeveloperExtensions2.Core.ExtensionConstants.SolutionPackagerMapFile)
                    {
                        continue;
                    }
                    // Do not delete the config file
                    if (name == CrmDeveloperExtensions2.Core.Resources.Resource.ConfigFileName)
                    {
                        continue;
                    }
                    if (File.Exists(Path.Combine(extractedFolder, name)))
                    {
                        continue;
                    }

                    projectItem.Delete();
                    itemChanged = true;
                }

                if (CrmDeveloperExtensions2.Core.StringFormatting.FormatProjectKind(projectItem.Kind) == VSConstants.GUID_ItemType_PhysicalFolder.ToString())
                {
                    name = new DirectoryInfo(name).Name;
                    if (name == projectFolder || name == "Properties")
                    {
                        continue;
                    }

                    if (!Directory.Exists(Path.Combine(extractedFolder, name)))
                    {
                        projectItem.Delete();
                        itemChanged = true;
                    }
                    else
                    {
                        if (projectItem.ProjectItems.Count <= 0)
                        {
                            continue;
                        }

                        bool subItemChanged = RemoveDeletedItems(Path.Combine(extractedFolder, name),
                                                                 projectItem.ProjectItems, projectFolder);
                        if (subItemChanged)
                        {
                            itemChanged = true;
                        }
                    }
                }
            }

            return(itemChanged);
        }
Beispiel #49
0
 /// <summary>
 /// Checks if the project contains the specified
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public bool ContainsFile(string filename)
 {
     return(ProjectItems.Any(p => p.Filename == filename));
 }
        private void InitTestprojectStructure()
        {
            //mock exist file *.cs with name equal to name method
            mainMethodFileProjectItem = Substitute.For <ProjectItem>();
            mainMethodFileProjectItem.Name.Returns("TestMethodName.cs");

            methodWrapperFileProjectItem = Substitute.For <ProjectItem>();
            methodWrapperFileProjectItem.Name.Returns("TestMethodNameWrapper.cs");

            methodTestsFileProjectItem = Substitute.For <ProjectItem>();
            methodTestsFileProjectItem.Name.Returns("TestMethodNameTests.cs");

            List <ProjectItem> methodFiles = new List <ProjectItem>()
            {
                mainMethodFileProjectItem, methodWrapperFileProjectItem, methodTestsFileProjectItem
            };

            ProjectItems specialMethodFolderProjectItems = Substitute.For <ProjectItems>();

            specialMethodFolderProjectItems.GetEnumerator().Returns(methodFiles.GetEnumerator());

            specialMethodFolderProjectItems.Item("TestMethodName.cs").Returns(mainMethodFileProjectItem);
            specialMethodFolderProjectItems.Item("TestMethodNameWrapper.cs").Returns(methodWrapperFileProjectItem);
            specialMethodFolderProjectItems.Item("TestMethodNameTests.cs").Returns(methodTestsFileProjectItem);

            //mock folder with method
            specialMethodFolder = Substitute.For <ProjectItem>();
            specialMethodFolder.Name.Returns("TestMethodName");
            specialMethodFolder.ProjectItems.Returns(specialMethodFolderProjectItems);

            List <ProjectItem> methodFolders = new List <ProjectItem>()
            {
                specialMethodFolder
            };

            ProjectItems serverMethodsFolderItems = Substitute.For <ProjectItems>();

            serverMethodsFolderItems.GetEnumerator().Returns(methodFolders.GetEnumerator());
            serverMethodsFolderItems.Item("TestMethodName").Returns(specialMethodFolder);

            //mock main methods folder "ServerMethods"
            ProjectItem serverMethodsFolderProjectItem = Substitute.For <ProjectItem>();

            serverMethodsFolderProjectItem.Name.Returns("ServerMethods");
            serverMethodsFolderProjectItem.ProjectItems.Returns(serverMethodsFolderItems);

            List <ProjectItem> projectFolders = new List <ProjectItem>()
            {
                serverMethodsFolderProjectItem
            };

            ProjectItems projectItems = Substitute.For <ProjectItems>();

            projectItems.Item("ServerMethods").Returns(serverMethodsFolderProjectItem);
            projectItems.GetEnumerator().Returns(projectFolders.GetEnumerator());

            Project project = Substitute.For <Project>();

            project.UniqueName.Returns("ProjectName");
            project.ProjectItems.Returns(projectItems);

            DTE2 dte2 = Substitute.For <DTE2>();

            dte2.ActiveSolutionProjects.Returns(new Project[] { project });
            this.serviceProvider.GetService(Arg.Any <Type>()).Returns(dte2);
        }
Beispiel #51
0
        public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem)
        {
            projectItem = GetProjectItem(projectItems, name, _folderKinds);

            return(projectItem != null);
        }
        /// <summary>
        /// Generates the specified Source File in the received Project with the options
        /// provided and gets the Namespace ready to add code in it.
        /// </summary>
        /// <param name="targetProject">Project where the Source File is going to be placed.</param>
        /// <param name="targetProjectFolder">Project folder where the source file is going to be placed.
        /// Null indicates to place the source file as child of targetProject.</param>
        /// <param name="sourceFileName">Source File name to use.</param>
        /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param>
        /// <param name="sourceNamespace">Namespace used in the Source File.</param>
        /// <param name="isServiceReady">Specifies if it is Service-Ready (serialization is going to be used).</param>
        /// <param name="sourceFileItem">(out parameter) Source File ProjectItem.</param>
        /// <returns></returns>
        public static CodeNamespace GenerateSourceAndGetNamespace(Project targetProject, ProjectItem targetProjectFolder,
                                                                  string sourceFileName, string sourceFileHeaderComment, string sourceNamespace,
                                                                  bool isServiceReady, out ProjectItem sourceFileItem)
        {
            // Validate source file name
            if (sourceFileName.EndsWith(Resources.CSharpFileExtension) == false)
            {
                sourceFileName += Resources.CSharpFileExtension;
            }

            // Validate source file header comment
            if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false)
            {
                if (sourceFileHeaderComment.IndexOf("*/") >= 0)
                {
                    throw new ApplicationException(Resources.Error_HeaderCommentInvalidChars);
                }
            }

            // ProjectItems collection where to place the source file
            ProjectItems projectItems = targetProject.ProjectItems;

            if (targetProjectFolder != null)
            {
                // Place inside received project folder
                projectItems = targetProjectFolder.ProjectItems;
            }

            // Properties collection of the target
            EnvDTE.Properties targetProperties = targetProject.Properties;
            if (targetProjectFolder != null)
            {
                targetProperties = targetProjectFolder.Properties;
            }

            // Source file
            sourceFileItem = null;

            #region If source file exists in the target, clear it and get the reference
            foreach (ProjectItem projItem in projectItems)
            {
                string projItemFileName = projItem.Properties.Item(Resources.ProjectItem_FileName).Value.ToString();

                if (sourceFileName.ToLower() == projItemFileName.ToLower())
                {
                    // Source file already exists
                    sourceFileItem = projItem;

                    if (sourceFileItem.FileCodeModel.CodeElements != null &&
                        sourceFileItem.FileCodeModel.CodeElements.Count > 0)
                    {
                        // Clear source file

                        CodeElement firstElement = sourceFileItem.FileCodeModel.CodeElements.Item(1);

                        CodeElement lastElement = sourceFileItem.FileCodeModel.CodeElements.Item(
                            sourceFileItem.FileCodeModel.CodeElements.Count);

                        EditPoint startPoint = firstElement.StartPoint.CreateEditPoint();
                        EditPoint endPoint   = lastElement.EndPoint.CreateEditPoint();

                        while (startPoint.AtStartOfDocument != true)
                        {
                            startPoint.LineUp();
                        }

                        while (endPoint.AtEndOfDocument != true)
                        {
                            endPoint.LineDown();
                        }

                        startPoint.Delete(endPoint);
                    }

                    break;
                }
            }
            #endregion

            #region If source file NOT exists in the target, create it and get the reference
            if (sourceFileItem == null)
            {
                // New source file, get target path
                string targetPath = targetProperties.Item(Resources.Properties_LocalPath).Value.ToString();

                // Check if the new source file already exists in the file system (and it is not added to the solution)
                if (File.Exists(targetPath + sourceFileName))
                {
                    // Rename the existent source file
                    string backupSourceFileName = (sourceFileName + Resources.BackupFileExtension);
                    File.Move((targetPath + sourceFileName), (targetPath + backupSourceFileName));

                    // Add warning
                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                      string.Format(Resources.Warning_SourceFileAlreadyExists, sourceFileName, backupSourceFileName),
                                                      targetProject, sourceFileName, null, null);
                }

                // Add source file to target
                sourceFileItem = projectItems.AddFromTemplate(TemplateClass.FilePath, sourceFileName);
            }
            #endregion

            #region Generate imports
            var importList = new List <SourceCodeImport>();
            importList.Add(new SourceCodeImport(Resources.NamespaceSystem));
            importList.Add(new SourceCodeImport(Resources.NamespaceSystemCollectionsGeneric));
            importList.Add(new SourceCodeImport(Resources.NamespaceSystemText));

            if (isServiceReady)
            {
                importList.Add(new SourceCodeImport(Resources.NamespaceSystemRuntimeSerialization));
            }

            importList = importList.OrderBy(d => d.ImportNamespace).ToList();
            #endregion Generate imports

            // Add imports to the source code
            VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);

            // Get Source file code start
            EditPoint objEditPoint = sourceFileItem.FileCodeModel.CodeElements.Item(1).StartPoint.CreateEditPoint();
            objEditPoint.StartOfDocument();

            // Add header comment
            if (string.IsNullOrWhiteSpace(sourceFileHeaderComment) == false)
            {
                sourceFileHeaderComment = (Environment.NewLine + sourceFileHeaderComment + Environment.NewLine);

                objEditPoint.Insert(
                    string.Format(Resources.CSharpCommentMultiline, sourceFileHeaderComment) +
                    Environment.NewLine);
            }

            // Add EntitiesToDTOs signature
            string timestamp = DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss");
            objEditPoint.Insert(string.Format(Resources.EntitiesToDTOsSignature, AssemblyHelper.Version, timestamp));
            objEditPoint.Insert(Environment.NewLine);

            // Add blank line before source file namespace
            objEditPoint.EndOfDocument();
            objEditPoint.Insert(Environment.NewLine);

            // Add namespace
            CodeNamespace objNamespace = sourceFileItem.FileCodeModel
                                         .AddNamespace(sourceNamespace, AppConstants.PLACE_AT_THE_END);

            return(objNamespace);
        }
Beispiel #53
0
        /// <summary>
        /// Gets the available assemblies & classes of which unit test items can be created against.
        /// </summary>
        /// <param name="referencedProjects">The solution projects which are referenced by the unit test project.</param>
        /// <returns>List of ComboboxItems containing the project assembly & class info.</returns>
        private static List <ComboBoxItem> GetSourceProjectItems(ICollection <string> referencedProjects)
        {
            List <ComboBoxItem> classItems = new List <ComboBoxItem>();
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE;

            if (dte == null)
            {
                return(classItems);
            }
            Projects projects = dte.Solution.Projects;

            ComboBoxItem itemEmpty = new ComboBoxItem {
                Content = string.Empty, Tag = string.Empty
            };

            classItems.Add(itemEmpty);

            foreach (Project project in projects)
            {
                if (!referencedProjects.Contains(project.Name))
                {
                    continue;
                }

                string assemblyName = project.Properties.Item("AssemblyName").Value.ToString();

                ProjectItems activeProjectItems = project.ProjectItems;
                if (activeProjectItems.Count <= 0)
                {
                    continue;
                }

                foreach (ProjectItem projectItem in activeProjectItems)
                {
                    if (!projectItem.FileNames[0].EndsWith((".cs")))
                    {
                        continue;
                    }

                    foreach (CodeElement element in projectItem.FileCodeModel.CodeElements)
                    {
                        if (element.Kind != vsCMElement.vsCMElementNamespace)
                        {
                            continue;
                        }

                        foreach (CodeElement childElement in element.Children)
                        {
                            if (childElement.Kind != vsCMElement.vsCMElementClass)
                            {
                                continue;
                            }

                            ComboBoxItem item = new ComboBoxItem {
                                Content = childElement.FullName, Tag = assemblyName
                            };
                            classItems.Add(item);
                        }
                    }
                }
            }

            return(classItems);
        }
Beispiel #54
0
        /// <summary>
        /// Walks qualified project items and processes all of their qualified items.
        /// </summary>
        private void ProcessProjectItems(List <FileModel> model, ProcessorFlags flags, CodeModelFilterFlags filter, LanguageSettings languageSet,
                                         ProjectItems projectItems, bool isWebProject, ref bool isRoot, ProjectItem parentItem, string parentName)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Parent item is applicable or meant to be used for actual files only, i.e. file combos like .cs and .designer.cs, etc.
            if (parentItem != null)
            {
                if ((string.Compare(parentItem.Kind, Constants.vsProjectItemKindPhysicalFile, StringComparison.OrdinalIgnoreCase) != 0) &&
                    (string.Compare(parentItem.Kind, Constants.vsProjectItemKindSolutionItems, StringComparison.OrdinalIgnoreCase) != 0))
                {
                    parentItem = null;
                }
            }
            var parentSubType    = FileSubType.None;
            var parentSubTypeSet = false;

            if (!string.IsNullOrEmpty(parentName) && !parentName.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
            {
                parentName = parentName + "\\";
            }

            // Save the current language and determine the new current language
            if (isWebProject)
            {
                var webLanguageSet = GetWebFolderLanguage(isRoot, projectItems);

                // Fallback scenario - use default project language so that non-code files can be resolved
                if (webLanguageSet?.Type != LanguageType.Unknown)
                {
                    languageSet = webLanguageSet;                     // language should be restored for other items once we walk up the stack
                }
            }

            // Root processing is finished after language is checked for the root project items
            isRoot = false;
            var projectName = string.Empty;

            foreach (ProjectItem projectItem in projectItems)
            {
                // Skip project references as they can't contribute any files
                var isReferences = projectItem.Object is VSLangProj.References;
                var isReference  = projectItem.Object is VSLangProj.Reference;
                if (isReferences || isReference)
                {
                    continue;
                }

                // LightSwitch type projects with virtual references node workaround
                if (!string.IsNullOrEmpty(projectItem.Name) &&
                    projectItem.Name.Equals(REFERENCES_NODE, StringComparison.OrdinalIgnoreCase) &&
                    (string.Compare(projectItem.Kind, Constants.vsProjectItemKindVirtualFolder, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    continue;
                }

                if ((string.Compare(projectItem.Kind, Constants.vsProjectItemKindPhysicalFile, StringComparison.OrdinalIgnoreCase) == 0) ||
                    (string.Compare(projectItem.Kind, Constants.vsProjectItemKindSolutionItems, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    if (!parentSubTypeSet)
                    {
                        parentSubTypeSet = true;

                        if (parentItem != null)
                        {
                            parentSubType = _fileTypeResolver.GetSubType(parentItem, languageSet, isWebProject);
                        }
                    }

                    var itemSubType = _fileTypeResolver.GetSubType(projectItem, languageSet, isWebProject);

                    // Check if this is a code file
                    var add = !flags.HasFlag(ProcessorFlags.IncludeCodeFilesOnly) || _fileTypeResolver.IsCodeSubType(itemSubType);

                    // Check for .Designer file
                    if (add &&
                        !flags.HasFlag(ProcessorFlags.IncludeDesignerFiles) &&
                        _fileTypeResolver.IsDesignerItem(projectItem, itemSubType, languageSet, isWebProject))
                    {
                        add = false;
                    }

                    // Used to collect skipped files here as well... something to keep an eye out out for
                    if (add)
                    {
                        var fileName = projectItem.get_FileNames(1);
                        if (string.IsNullOrEmpty(fileName))
                        {
                            add = false;
                        }

                        if (add)
                        {
                            // Try getting a misc/simple subtype for unknown and solution projects
                            if ((languageSet?.Type == LanguageType.Unknown) && (itemSubType == FileSubType.None))
                            {
                                itemSubType = _fileTypeResolver.GetExtensionSubType(projectItem, languageSet, isWebProject);
                            }

                            if (string.IsNullOrEmpty(projectName))
                            {
                                projectName = projectItem.ContainingProject?.Name;
                            }

                            var itemModel = new FileModel
                            {
                                ProjectItem       = projectItem,
                                FileName          = projectItem.Name,
                                ParentProjectItem = parentItem,
                                ParentName        = parentName,
                                ParentSubType     = parentSubType,
                                ItemSubType       = itemSubType,
                                FileNameWithPath  = fileName,
                                ProjectName       = projectName
                            };

                            if (flags.HasFlag(ProcessorFlags.IncludeFileCodeModel))
                            {
                                var members = _fileProcessor.GetMembers(projectItem, flags, filter);
                                if (members != null)
                                {
                                    itemModel.Members.AddRange(members);
                                }
                            }

                            model.Add(itemModel);
                        }
                    }

                    ProjectItems currentProjectItems = projectItem.ProjectItems;
                    if ((currentProjectItems != null) && (currentProjectItems.Count > 0))
                    {
                        ProcessProjectItems(
                            model, flags, filter, languageSet,
                            currentProjectItems, false, ref isRoot, projectItem, parentName);
                    }
                }
                else
                {
                    if ((string.Compare(projectItem.Kind, Constants.vsProjectItemKindPhysicalFolder, StringComparison.OrdinalIgnoreCase) == 0) ||
                        (string.Compare(projectItem.Kind, Constants.vsProjectItemKindVirtualFolder, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        ProjectItems currentProjectItems = projectItem.ProjectItems;
                        if ((currentProjectItems != null) && (currentProjectItems.Count > 0))
                        {
                            ProcessProjectItems(
                                model, flags, filter, languageSet,
                                currentProjectItems, isWebProject, ref isRoot, projectItem, parentName + projectItem.Name);
                        }
                    }
                }
            }             // foreach (projectItem)
        }
Beispiel #55
0
        private static bool RemoveDeletedItems(string extractedFolder, ProjectItems projectItems)
        {
            bool itemChanged = false;

            //Handle file & folder deletes
            foreach (ProjectItem projectItem in projectItems)
            {
                string name = projectItem.FileNames[0];
                switch (projectItem.Kind.ToUpper())
                {
                case "{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}":
                    name = Path.GetFileName(name);
                    // Do not delete the mapping file
                    if (name == "mapping.xml")
                    {
                        continue;
                    }
                    // Do not delete the config file
                    if (name == "CRMDeveloperExtensions.config")
                    {
                        continue;
                    }
                    if (File.Exists(extractedFolder + "\\" + name))
                    {
                        continue;
                    }

                    projectItem.Delete();
                    itemChanged = true;
                    break;

                case "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}":
                    name = new DirectoryInfo(name).Name;
                    if (name == "_Solutions")
                    {
                        continue;
                    }

                    if (!Directory.Exists(extractedFolder + "\\" + name))
                    {
                        projectItem.Delete();
                        itemChanged = true;
                    }
                    else
                    {
                        if (projectItem.ProjectItems.Count <= 0)
                        {
                            continue;
                        }

                        bool subItemChanged = RemoveDeletedItems(extractedFolder + "\\" + name,
                                                                 projectItem.ProjectItems);
                        if (subItemChanged)
                        {
                            itemChanged = true;
                        }
                    }
                    break;
                }
            }

            return(itemChanged);
        }
Beispiel #56
0
        public static ProjectItem BuildDteProjectItem(IEnumerable <Type> fromClassTypes, string projectItemName, ProjectItems subProjectItems = null)
        {
            var namespaceName = fromClassTypes
                                .Select(t => t.Namespace)
                                .Distinct()
                                .Single();

            var classes = fromClassTypes
                          .Select(BuildDteClass)
                          .ToList();

            var moqFileCodeModel    = new Mock <FileCodeModel>();
            var moqProjectItem      = new Mock <ProjectItem>();
            var moqProjCodeElements = new Mock <CodeElements>();

            var moqMembers = new Mock <CodeElements>();

            moqMembers.Setup(x => x.GetEnumerator()).Returns(() => classes.GetEnumerator());

            var moqCodeNamespace = new Mock <CodeNamespace>();

            moqCodeNamespace.SetupGet(x => x.Members).Returns(moqMembers.Object);
            moqCodeNamespace.SetupGet(x => x.Name).Returns(namespaceName);

            moqProjCodeElements.Setup(x => x.GetEnumerator()).Returns(() => new[] { moqCodeNamespace.Object }.GetEnumerator());
            moqFileCodeModel.SetupGet(x => x.CodeElements).Returns(moqProjCodeElements.Object);
            moqProjectItem.SetupProperty(x => x.Name, projectItemName);
            moqProjectItem.SetupGet(x => x.FileCodeModel).Returns(moqFileCodeModel.Object);
            moqProjectItem.SetupGet(x => x.ProjectItems).Returns(subProjectItems);

            return(moqProjectItem.Object);
        }
        /// <include file='doc\InstallerDesign.uex' path='docs/doc[@for="InstallerDesign.GetProjectInstallerDocument"]/*' />
        /// <devdoc>
        /// Gets the document that contains the installers for the project.
        /// </devdoc>
        public static IDesignerHost GetProjectInstallerDocument(IComponent component)
        {
            ProjectItem currentProjItem = (ProjectItem)component.Site.GetService(typeof(ProjectItem));

            if (currentProjItem == null)
            {
                throw new Exception(SR.GetString(SR.InstallerDesign_CouldntGetService));
            }

            Project project = currentProjItem.ContainingProject;

            ProjectItems projItems         = project.ProjectItems;
            ProjectItem  installationClass = null;

            string projectKind = project.Kind;
            string projectInstallerItemName     = null;
            string projectInstallerTemplateName = null;

            if (new Guid(projectKind).Equals(CSharpProjectGuid))
            {
                // c# has a special name for the installer wizard
                projectInstallerTemplateName = "\\NewInstaller.vsz";
            }
            else
            {
                // all other project types will have the same name
                projectInstallerTemplateName = "\\Installer.vsz";
            }

            int fileCount = currentProjItem.FileCount;

            if (fileCount == 0)
            {
                throw new Exception(SR.GetString(SR.InstallerDesign_NoProjectFilename));
            }
            string extension = Path.GetExtension(currentProjItem.get_FileNames(0));

            projectInstallerItemName = "ProjectInstaller" + extension;

            try {
                installationClass = projItems.Item(projectInstallerItemName);
            }
            catch (Exception) {
                // if file isn't in the project, we'll get an ArgumentException.
            }

            // If we could't find an existing ProjectInstaller.xx, we'll try to add
            // one from the template.
            if (installationClass == null)
            {
                string templateFileName = GetItemTemplatesDir(projectKind) + projectInstallerTemplateName;
                try {
                    // AddFromTemplate will try to copy the template file into ProjectInstaller.xx.
                    // If ProjectInstaller.xx already exists, it will bring up a dialog that says:
                    //      A file with the name 'C:\myproject\ProjectInstaller.xx'
                    //      already exists.  Do you want to replace it?
                    // If you answer yes, you're good to go.  The existing file will be overwritten
                    // with the template.  If you answer no, AddFromTemplate will throw a COMException
                    // with hresult = 0x80070050 (file already exists).
                    installationClass = projItems.AddFromTemplate(templateFileName, projectInstallerItemName);
                }
                catch (COMException e) {
                    // if the errorcode is HRESULT_FROM_WIN32(ERROR_FILE_EXISTS) (which is 0x80070050)
                    // then ProjectInstaller.xx exists and the user does not want to overwrite it.
                    // We could try to use the existing file, but that might cause more problems then
                    // want to get into.  Just inform the user that we can't add the installer.
                    if (e.ErrorCode == unchecked ((int)0x80070050))
                    {
                        throw new Exception(SR.GetString(SR.InstallerDesign_UnableToAddProjectInstaller));
                    }
                    else
                    {
                        // unexpected -> bubble up
                        throw;
                    }
                }
                catch (FileNotFoundException) {
                    // The template was not found.  This probably means that the current project type
                    // doesn't provide a template for installers.  Nothing to do but report the error.
                    throw new FileNotFoundException(SR.GetString(SR.InstallerDesign_CoulndtFindTemplate), templateFileName);
                }
            }

            try {
                installationClass.Properties.Item("SubType").Value = "Component";
                Window window = installationClass.Open(vsViewKindDesigner);
                window.Visible = true;
                IDesignerHost host = (IDesignerHost)window.Object;

                // make sure the project has a reference to System.Configuration.Install.dll.
                // This is done as a side-effect of calling GetType.
                host.GetType(typeof(ComponentInstaller).FullName);

                return(host);
            } catch (Exception e) {
                throw new Exception(SR.GetString(SR.InstallerDesign_CouldntShowProjectInstaller), e);
            }
        }
Beispiel #58
0
        public static Project BuildDteProject(IEnumerable <Type> fromClassTypes, string projectName, ProjectItems subProjectItems = null)
        {
            var moqProject      = new Mock <Project>();
            var moqProjectItems = new Mock <ProjectItems>();

            moqProject.SetupGet(x => x.ProjectItems).Returns(moqProjectItems.Object);

            var byNamespace = fromClassTypes
                              .GroupBy(x => x.Namespace)
                              .ToDictionary(
                g => g.Key,
                g => g.ToList()
                );

            var projectItems = new List <ProjectItem>();

            foreach (string namespaceName in byNamespace.Keys)
            {
                var projectItem = BuildDteProjectItem(byNamespace[namespaceName], projectName, subProjectItems);
                projectItems.Add(projectItem);
            }

            moqProjectItems.Setup(x => x.GetEnumerator()).Returns(() => projectItems.GetEnumerator());

            return(moqProject.Object);
        }
Beispiel #59
0
        private bool ProcessDownloadedSolution(DirectoryInfo extractedFolder, string baseFolder, ProjectItems projectItems)
        {
            bool itemChanged = false;

            //Handle file adds
            foreach (FileInfo file in extractedFolder.GetFiles())
            {
                if (File.Exists(baseFolder + "\\" + file.Name))
                {
                    if (FileEquals(baseFolder + "\\" + file.Name, file.FullName))
                    {
                        continue;
                    }
                }

                File.Copy(file.FullName, baseFolder + "\\" + file.Name, true);
                projectItems.AddFromFile(baseFolder + "\\" + file.Name);
                itemChanged = true;
            }

            //Handle folder adds
            foreach (DirectoryInfo folder in extractedFolder.GetDirectories())
            {
                if (!Directory.Exists(baseFolder + "\\" + folder.Name))
                {
                    Directory.CreateDirectory(baseFolder + "\\" + folder.Name);
                }

                var  newProjectItems = projectItems;
                bool subItemChanged  = ProcessDownloadedSolution(folder, baseFolder + "\\" + folder.Name, newProjectItems);
                if (subItemChanged)
                {
                    itemChanged = true;
                }
            }

            return(itemChanged);
        }
 internal static ProjectItem GetItemByFullFileName(ProjectItems items, string fullFileNameOfItemToGet)
 {
     return(GetItemByFullFileName(items, fullFileNameOfItemToGet, false));
 }