/// <summary>
        /// Collapses the folder.
        /// </summary>
        /// <param name="hsa2">The hsa2.</param>
        /// <param name="asa2">The asa2.</param>
        /// <param name="folder">The folder.</param>
        private static void collapseFolder(VSProject2 hsa2, VSProject2 asa2, UIHierarchyItem folder)
        {
            foreach (UIHierarchyItem project in folder.UIHierarchyItems)
            {
                foreach (UIHierarchyItem projectItem in project.UIHierarchyItems)
                {
                    if (projectItem.Name == "References")
                    {
                        projectItem.UIHierarchyItems.Expanded = false;
                    }

                    else if (projectItem.Name.Equals(GENERETED_FILES_DIRECTORY) &&
                             (project.Name.Equals(hsa2.Project.Name) || project.Name.Equals(asa2.Project.Name)))
                    {
                        projectItem.UIHierarchyItems.Expanded = false;
                    }

                    collapseFolder(hsa2, asa2, projectItem);
                }

                if (project.Name == hsa2.Project.Name || project.Name == asa2.Project.Name)
                {
                    project.UIHierarchyItems.Expanded = false;
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Constructor
        /// </summary>
        public ProjectParser_CSharp(VSProject2 vsProject, string solutionRootFolder)
        {
            try
            {
                m_vsProject          = vsProject;
                m_solutionRootFolder = solutionRootFolder;
                m_dteProject         = Utils.call(() => vsProject.Project);

                // We get the project name...
                m_projectInfo.Name = Utils.call(() => (m_dteProject.Name));

                if (MakeItSoConfig.Instance.ignoreProject(m_projectInfo.Name) == true)
                {
                    Log.log("- project " + m_projectInfo.Name + "ignored");
                }
                else
                {
                    Log.log("- parsing project " + m_projectInfo.Name);

                    // and parse the project...
                    parseProject();
                    Log.log("  - done");
                }
            }
            catch (Exception ex)
            {
                Log.log(String.Format("  - FAILED ({0})", ex.Message));
            }
        }
 /// <summary>
 /// Adds the project reference.
 /// </summary>
 /// <param name="project">The project.</param>
 /// <param name="reference">The reference.</param>
 private static void addProjectReference(VSProject2 project, Project reference)
 {
     if (project.References.Item(reference.Name) == null)
     {
         project.References.AddProject(reference).CopyLocal = false;
     }
 }
예제 #4
0
        //public VsHelper(BaseCustomTool host)
        //{
        //    solution = host.GetSolution();
        //    project = host.GetProject();
        //}

        //internal Solution GetSolution()
        //{
        //    Solution solution = (Solution)_host.GetService(typeof(Solution));
        //    Debug.Assert(solution != null);
        //    return solution;
        //}

        //public Project GetProject()
        //{
        //    // TODO fix, this does not work
        //    //DTE2 dte2 = (DTE2) Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.9.0", String.Empty);
        //    //object dteObject = Marshal.GetActiveObject("VisualStudio.DTE.9.0");
        //    //string dteName = Information.TypeName(dteObject);
        //    //DTE dte = dteObject as DTE;
        //    //DTE2 dte2 = dteObject as DTE2;

        //    Solution solution = (Solution) this.GetService(typeof(Solution));
        //    Debug.Assert(solution != null);
        //    foreach (object obj in solution.Projects)
        //    {
        //        string typeName = Information.TypeName(obj);
        //        Console.WriteLine(typeName);
        //        EnvDTE.Project proj = (EnvDTE.Project)obj;
        //        Console.WriteLine(proj.FullName);
        //    }
        //    Project project = solution.Projects.Item(1).ProjectItems.ContainingProject;
        //    Debug.Assert(project != null);
        //    return project;
        //}

        /// <summary>
        /// Gets a list of the assemblies referenced by the project
        /// </summary>
        /// <param name="isInclusive">Include assemblies from C:\Windows or not</param>
        /// <returns></returns>
        public Assembly[] GetReferencedAssemblies(bool isInclusive)
        {
            List <Assembly> assemblies = new List <Assembly>();
            VSProject2      vsProject2 = project.Object as VSProject2;

            foreach (object obj in vsProject2.References)
            {
                try
                {
                    string     windir = Environment.GetEnvironmentVariable("windir");
                    Reference3 ref3   = obj as Reference3;
                    if (ref3 != null)
                    {
                        // filter out the standard assemblies (isInclusive)
                        if (isInclusive || (!isInclusive && !ref3.Path.StartsWith(windir)))
                        {
                            Assembly assembly = AssemblyHelper.LoadAssembly(ref3.Path);
                            assemblies.Add(assembly);
                        }
                    }
                }
                catch
                {
                    // TODO show an alert with the error message
                    throw;
                }
            }
            return(assemblies.ToArray());
        }
예제 #5
0
 public DocumentDetetionService(Document document, VSProject2 vsProject2, DTE2 dte2, IAssemblyDetectionProvider assemblyDetectionProvider)
 {
     _document = document;
     _vsProject2 = vsProject2;
     _dte2 = dte2;
     _assemblyDetectionProvider = assemblyDetectionProvider;
 }
예제 #6
0
        /// <summary>
        /// Performs any preparatory tasks that have to be done after a new unit test project has been created.
        /// </summary>
        /// <param name="unitTestProject">The <see cref="Project"/> of the unit test project that has just been created.</param>
        /// <param name="sourceMethod">The <see cref="CodeFunction2"/> of the source method that is to be unit tested.</param>
        protected override void OnUnitTestProjectCreated(Project unitTestProject, CodeFunction2 sourceMethod)
        {
            if (unitTestProject == null)
            {
                throw new ArgumentNullException("unitTestProject");
            }

            TraceLogger.LogInfo("MSTestv2SolutionManager.OnUnitTestProjectCreated: Adding reference to MSTestv2 assemblies through nuget.");

            base.OnUnitTestProjectCreated(unitTestProject, sourceMethod);

            this.EnsureNuGetReference(unitTestProject, "MSTest.TestAdapter", "1.1.18");
            this.EnsureNuGetReference(unitTestProject, "MSTest.TestFramework", "1.1.18");

            VSProject2 vsp = unitTestProject.Object as VSProject2;

            if (vsp != null)
            {
                Reference reference = vsp.References.Find(GlobalConstants.MSTestAssemblyName);
                if (reference != null)
                {
                    TraceLogger.LogInfo("MSTestv2SolutionManager.OnUnitTestProjectCreated: Removing reference to {0}", reference.Name);
                    reference.Remove();
                }
            }
        }
        public static string GetFileTypeFullName(string filePath, VSProject2 proj)
        {
            List <string> assembliesProjects   = new List <string>();
            List <string> assembliesReferences = new List <string>();

            var hash = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);

            FillProjectReferences(proj, assembliesProjects, assembliesReferences, hash);

            AppDomain childDomain = CreateChildDomain();

            try
            {
                childDomain.SetData(configFilePath, filePath);
                childDomain.SetData(configAssembliesProjects, assembliesProjects.ToArray());
                childDomain.SetData(configAssemblies, assembliesReferences.ToArray());
                childDomain.DoCallBack(new CrossAppDomainDelegate(GetFileTypeFullNameInAppDomain));

                return(childDomain.GetData(configResult)?.ToString());
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);
            }
            finally
            {
                AppDomain.Unload(childDomain);
            }

            return(string.Empty);
        }
예제 #8
0
        /// <summary>
        /// Constructor
        /// </summary>
        public ProjectParser_CSharp(VSProject2 vsProject, string solutionRootFolder)
        {
            try
            {
                m_vsProject = vsProject;
                m_solutionRootFolder = solutionRootFolder;
                m_dteProject = Utils.call(() => vsProject.Project);

                // We get the project name...
                m_projectInfo.Name = Utils.call(() => (m_dteProject.Name));

                if (MakeItSoConfig.Instance.ignoreProject(m_projectInfo.Name) == true)
                    Log.log("- project " + m_projectInfo.Name + "ignored");
                else
                {
                    Log.log("- parsing project " + m_projectInfo.Name);

                    // and parse the project...
                    parseProject();
                    Log.log("  - done");
                }
            }
            catch (Exception ex)
            {
                Log.log(String.Format("  - FAILED ({0})", ex.Message));
            }
        }
예제 #9
0
        private void AddProject(SolutionNode sn, Project proj)
        {
            ProjectNode pn = new ProjectNode();

            pn.Name = proj.Name;
            VSProject2 vsProj = proj.Object as VSProject2;

            foreach (Reference reference in vsProj.References)
            {
                ReferenceNode rn = new ReferenceNode();
                rn.Name = reference.Name;
                rn.Path = reference.Path;
                pn.ReferenceList.Add(rn);
            }

            foreach (ProjectItem item in proj.ProjectItems)
            {
                FileNode fn = new FileNode();
                fn.FileName = item.Name;
                //fn.FullName = item.Document.FullName;
                pn.FileList.Add(fn);
            }

            sn.ProjectList.Add(pn);
        }
예제 #10
0
파일: DetectionForm.cs 프로젝트: nhu/RefLoc
        public DetectionForm(Document document, VSProject2 vsProject2, DTE2 dte, IAssemblyDetectionProvider assemblyDetectionProvider)
        {
            _vsProject2 = vsProject2;
            DocumentDetetionService = new DocumentDetetionService(document, vsProject2, dte, assemblyDetectionProvider);

            InitializeComponent();
        }
 internal static void AddProjectReference(VSProject2 project, Project reference)
 {
     if (project.References.Item(reference.Name) == null)
     {
         project.References.AddProject(reference).CopyLocal = false;
     }
 }
예제 #12
0
        /// <summary>
        /// Parses the project passed in.
        /// </summary>
        private void parseProject(EnvDTE.Project project)
        {
            // We get the project name...
            string projectName = Utils.call(() => (project.Name));

            // We check if the project is loaded in the solution
            if (Utils.call(() => project.Object) == null && Utils.call(() => project.UniqueName) != "<MiscFiles>")
            {
                Log.log("Warning: " + projectName + " is currently unloaded in the solution! No conversion performed");
                return;
            }

            // We check if this project is a kind we know how to convert...
            string      strProjectType = Utils.call(() => (project.Kind));
            ProjectType eProjectType   = convertProjectTypeToEnum(strProjectType);

            switch (eProjectType)
            {
            // It's a C++ project...
            case ProjectType.CPP_PROJECT:
            {
                // We get the Visual Studio project, parse it and store the
                // parsed project in our collection of results...
                VCProject         vcProject = Utils.call(() => (project.Object as VCProject));
                ProjectParser_CPP parser    = new ProjectParser_CPP(vcProject, m_parsedSolution.RootFolderAbsolute);

                ProjectParser_ForCUDA cudaparser = new ProjectParser_ForCUDA(project.FileName, project.Name);

                // Remove cuda file.
                foreach (var info in cudaparser.Project.CompileInfos)
                {
                    parser.Project.removeFile(info.File);
                }

                m_parsedSolution.addProjectInfo(projectName, parser.Project);
                m_parsedSolution.addCudaProjectInfo(projectName, cudaparser.Project);
            }
            break;

                // Not support...
#if false
            // It's a C# project...
            case ProjectType.CSHARP_PROJECT:
            {
                // We get the Visual Studio project, parse it and store the
                // parsed project in our collection of results...
                VSProject2           vsProject = Utils.call(() => (project.Object as VSProject2));
                ProjectParser_CSharp parser    = new ProjectParser_CSharp(vsProject, m_parsedSolution.RootFolderAbsolute);
                m_parsedSolution.addProjectInfo(projectName, parser.Project);
            }
            break;
#endif
            }

            // We parse the project's items, to check whether there are any nested
            // projects...
            EnvDTE.ProjectItems projectItems = Utils.call(() => (project.ProjectItems));
            parseProjectItems(projectItems);
        }
        /// <summary>
        /// Adds the contract reference.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="sourceProject">The source project.</param>
        private static void addContractReference(VSProject2 target, Project sourceProject)
        {
            addProjectReference(target, sourceProject);

            if (!target.References.ContainsReference(typeof(IContract).Assembly.Location))
            {
                target.References.Add(typeof(IContract).Assembly.Location).CopyLocal = false;
            }
        }
예제 #14
0
 private static void AddMissingReferencesForProject(VSProject2 standardProject, ICollection <string> referenceFileNames)
 {
     foreach (var referenceFileName in referenceFileNames)
     {
         if (standardProject.References.Find(referenceFileName) == null)
         {
             standardProject.References.Add(referenceFileName);
         }
     }
 }
예제 #15
0
 public void AddReference(string assembly)
 {
     if (IsWebProject)
     {
         VSWebSite website = this.project.Object as VSWebSite;
         website.References.AddFromGAC(assembly);
     }
     else
     {
         VSProject2 prj = this.project.Object as VSProject2;
         prj.References.Add(assembly);
     }
 }
예제 #16
0
        /// <summary>
        /// Parses the project passed in.
        /// </summary>
        private void parseProject(EnvDTE.Project project)
        {
            // We get the project name...
            string projectName = Utils.call(() => (project.Name));

            if (MakeItSoConfig.Instance.ignoreProject(projectName))
            {
                Log.log("- Ignoring project: " + projectName);
                return;
            }

            // We check if this project is a kind we know how to convert...
            string      strProjectType = Utils.call(() => (project.Kind));
            ProjectType eProjectType   = convertProjectTypeToEnum(strProjectType);

            switch (eProjectType)
            {
            // It's a C++ project...
            case ProjectType.CPP_PROJECT:
            {
                // We get the Visual Studio project, parse it and store the
                // parsed project in our collection of results...
                VCProject         vcProject = Utils.call(() => (project.Object as VCProject));
                ProjectParser_CPP parser    = new ProjectParser_CPP(vcProject, m_parsedSolution.RootFolderAbsolute);
                m_parsedSolution.addProjectInfo(projectName, parser.Project);
            }
            break;

            // It's a C# project...
            case ProjectType.CSHARP_PROJECT:
            {
                // We get the Visual Studio project, parse it and store the
                // parsed project in our collection of results...
                VSProject2           vsProject = Utils.call(() => (project.Object as VSProject2));
                ProjectParser_CSharp parser    = new ProjectParser_CSharp(vsProject, m_parsedSolution.RootFolderAbsolute);
                m_parsedSolution.addProjectInfo(projectName, parser.Project);
            }
            break;
            }

            // We parse the project's items, to check whether there are any nested
            // projects...
            EnvDTE.ProjectItems projectItems = Utils.call(() => (project.ProjectItems));
            if (projectItems != null)
            {
                parseProjectItems(projectItems);
            }
        }
 private static void printReferences(VSProject2 vsp)
 {
     if (vsp == null)
     {
         return;
     }
     foreach (Reference r in vsp.References)
     {
         if (r.SourceProject == null)
         {
             continue;
         }
         WriteLine($@"	reference: {r.Name}");
         //WriteLine($@"		type: {r.SourceProject?.Name}");
     }
 }
예제 #18
0
        private static string GetTypeFullName(ProjectItem item)
        {
            string fileType = string.Empty;

            VSProject2 proj = item.ContainingProject?.Object as VSProject2;

            if (item != null && item.FileCount > 0 && proj != null)
            {
                fileType = CSharpCodeHelper.GetFileTypeFullName(item.FileNames[1], proj);
            }
            else if (item != null && item.FileCount > 0)
            {
                fileType = item.Name.Split('.').FirstOrDefault();
            }

            return(fileType);
        }
        private void CacheProjectReferences(VSProject2 vsProject)
        {
            foreach (Reference3 reference in vsProject.References)
            {
                if (_assembliesInstalledUnderVisualStudio.ContainsKey(reference.Identity.ToUpperInvariant()))
                {
                    // Ignore these DLLs - should be loaded using _assembliesInstalledUnderVisualStudio instead
                    continue;
                }

                if (reference.Resolved &&
                    !string.IsNullOrEmpty(reference.Path))
                {
                    _projectReferenceLookup.Add(reference.Identity, reference);
                }
            }
        }
        private void CacheProjectReferences(VSProject2 vsProject)
        {
            foreach (Reference3 reference in vsProject.References)
            {
                if (_assembliesInstalledUnderVisualStudio.ContainsKey(reference.Identity.ToUpperInvariant()))
                {
                    // Ignore these DLLs - should be loaded using _assembliesInstalledUnderVisualStudio instead
                    continue;
                }

                if (reference.Resolved
                    && !string.IsNullOrEmpty(reference.Path))
                {
                    _projectReferenceLookup.Add(reference.Identity, reference);
                }
            }
        }
예제 #21
0
        public virtual bool Build()
        {
            try
            {
                //  _applicationObject.ExecuteCommand("Build.BuildSelection", "");
                Project   = (Project)((Array)Dte.ActiveSolutionProjects).GetValue(0);
                VsProject = ((VSProject2)(Project.Object));

                if (!ExecuteBeforeBuild())
                {
                    return(false);
                }

                Solution      = (Solution2)Dte.Solution;
                SolutionBuild = (SolutionBuild2)Solution.SolutionBuild;

                //sb2.BuildProject(sb2.ActiveConfiguration.Name, prj.UniqueName, true);
                SolutionBuild.Build(true);
                //_dte.ExecuteCommand("Build.RebuildSolution");

                if (SolutionBuild.LastBuildInfo != 0)
                {
                    return(false);
                }

                if (!BuildManifest())
                {
                    return(false);
                }

                ExecuteAfterRelease();
                return(true);
            }
            catch (Exception ex)
            {
                OutputMessage(ex.Message);
                Logger.WriteExceptionLog(ex.Message + Environment.NewLine + ex.StackTrace);
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, Common.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
예제 #22
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            // Create a sln
            Solution3 newSln = DTEObject.Solution as Solution3;

            newSln.Create(@"C:\solutions", "mySln");

            // Add a proj
            string templatePath = newSln.GetProjectTemplate("ClassLibrary.zip", "CSharp");

            newSln.AddFromTemplate(templatePath, @"C:\solutions\NewProj", "mySln.NewProj", false);
            Project    proj   = newSln.Projects.Item(1);
            VSProject2 vsProj = proj.Object as VSProject2;

            vsProj.References.Add(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll");

            // Save the sln
            newSln.SaveAs(@"C:\solutions\mySln.sln");
            //newSln.Close(true);

            //ShowSlnInfo();
        }
예제 #23
0
 private bool Refresh()
 {
     if (IsWebProject)
     {
         VSWebSite website = this.project.Object as VSWebSite;
         if (website != null)
         {
             website.Refresh();
             return(true);
         }
     }
     else
     {
         VSProject2 project = this.project.Object as VSProject2;
         if (project != null)
         {
             project.Refresh();
             return(true);
         }
     }
     return(false);
 }
 internal static void CollapseFolder(VSProject2 hsa2, VSProject2 asa2, UIHierarchyItem folder)
 {
     foreach (UIHierarchyItem project in folder.UIHierarchyItems)
     {
         foreach (UIHierarchyItem projectItem in project.UIHierarchyItems)
         {
             if (projectItem.Name.Equals("References"))
             {
                 projectItem.UIHierarchyItems.Expanded = false;
             }
             else if (projectItem.Name.Equals("Generated Files") && (project.Name.Equals(hsa2.Project.Name) || project.Name.Equals(asa2.Project.Name)))
             {
                 projectItem.UIHierarchyItems.Expanded = false;
             }
             CollapseFolder(hsa2, asa2, projectItem);
         }
         if (project.Name.Equals(hsa2.Project.Name) || project.Name.Equals(asa2.Project.Name))
         {
             project.UIHierarchyItems.Expanded = false;
         }
     }
 }
예제 #25
0
        private void FillProjectReferences(VSProject2 proj)
        {
            if (proj.Project != null)
            {
                var outputFilePath = PropertiesHelper.GetOutputFilePath(proj.Project);

                if (!string.IsNullOrEmpty(outputFilePath))
                {
                    if (_hash.Add(Path.GetFileName(outputFilePath)) &&
                        outputFilePath.IndexOf("mscorlib", StringComparison.InvariantCultureIgnoreCase) == -1
                        )
                    {
                        AssembliesProjects.Add(outputFilePath);
                    }
                }
            }

            foreach (var item in proj.References.OfType <Reference>())
            {
                if (item.Type == prjReferenceType.prjReferenceTypeAssembly)
                {
                    if (_hash.Add(Path.GetFileName(item.Path)) &&
                        item.Path.IndexOf("mscorlib", StringComparison.InvariantCultureIgnoreCase) == -1
                        )
                    {
                        AssembliesReferences.Add(item.Path);
                    }

                    if (item.SourceProject != null &&
                        item.SourceProject.Object != null &&
                        item.SourceProject.Object is VSProject2 project2
                        )
                    {
                        FillProjectReferences(project2);
                    }
                }
            }
        }
예제 #26
0
        private static string GetTypeFullName(EnvDTE.Document document)
        {
            if (document == null)
            {
                return(string.Empty);
            }

            string fileType = string.Empty;

            VSProject2 proj = document?.ProjectItem?.ContainingProject?.Object as VSProject2;

            if (proj != null)
            {
                fileType = CSharpCodeHelper.GetFileTypeFullName(document.FullName, proj);
            }

            if (string.IsNullOrEmpty(fileType))
            {
                fileType = Path.GetFileNameWithoutExtension(document.FullName).Split('.').FirstOrDefault();
            }

            return(fileType);
        }
예제 #27
0
 private bool Refresh()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     if (IsWebProject)
     {
         VSWebSite website = this.project.Object as VSWebSite;
         if (website != null)
         {
             website.Refresh();
             return(true);
         }
     }
     else
     {
         VSProject2 project = this.project.Object as VSProject2;
         if (project != null)
         {
             project.Refresh();
             return(true);
         }
     }
     return(false);
 }
예제 #28
0
    public static bool Main(object arg)
    {
        ScriptEnginePackage sepkg    = (ScriptEnginePackage)arg;
        Solution            solution = sepkg.dte.Solution;

        ScriptHost.console.Clear();
        ScriptHost.console.WriteLine("Build: " + Assembly.GetExecutingAssembly().Location);
        ScriptHost.console.WriteLine("---------------------------------------------------------------------------------");
        ScriptHost.console.WriteLine(solution.FileName);
        //ScriptHost.console.WriteLine(solution.IsOpen.ToString());

        Project[] projects = solution.Projects.Cast <Project>().ToArray();
        foreach (Project project in projects)
        {
            String path = project.FileName;

            //
            // The "Miscellaneous Files" node is used to contain open files that are not associated
            // with the current project contents within the solution
            //
            // https://stackoverflow.com/questions/7160425/what-is-miscellaneous-files-inside-dte-vs2010-solution
            //
            if (project.Kind == Constants.vsProjectKindMisc)
            {
                continue;
            }

            String dir        = Path.GetDirectoryName(path);
            String scriptBase = Path.GetFileNameWithoutExtension(path);

            String script = Path.Combine(dir, scriptBase + "_proto.cs");

            CodeBuilder code = new CodeBuilder();

            code.AppendLine(
                @"//css_ref syncproj.exe
using System;

class Builder: SolutionProjectBuilder
{
    static void Main(String[] args)
    {");
            code.Indent(2);

            String name = project.Name;
            code.AppendLine("project(" + quoted(name) + ");");

            Configuration[] configurations = project.ConfigurationManager.Cast <Configuration>().ToArray();
            code.AppendLine("configurations(" + String.Join(",", configurations.Select(x => quoted(x.ConfigurationName)).Distinct()) + ");");
            code.AppendLine("platforms(" + String.Join(",", configurations.Select(x => quoted(x.PlatformName)).Distinct()) + ");");

            IVsHierarchy hierarchy;
            sepkg.vsSolution.GetProjectOfUniqueName(project.UniqueName, out hierarchy);
            Guid projectGuid;
            hierarchy.GetGuidProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid);

            code.AppendLine("uuid(" + quoted(projectGuid.ToString()) + ");");


            String[] paths = null;

            // C++ Project
            VCProject vcProject = project.Object as VCProject;
            if (vcProject != null)
            {
                VCFile[] files = ((IVCCollection)vcProject.Files).Cast <VCFile>().ToArray();
                paths = files.Select(x => x.RelativePath).ToArray();
            }

            // C# Project
            VSProject2 sharpProject = project.Object as VSProject2;
            if (sharpProject != null && vcProject == null)       //sharpProject gives too generic representation of C++ project, does not list all files
            {
                ProjectItem[] files = project.ProjectItems.Cast <ProjectItem>().ToArray();

                paths = new string[files.Length];
                for (int i = 0; i < files.Length; i++)
                {
                    Property[] properties = files[i].Properties.Cast <Property>().ToArray();
                    String[]   keys       = properties.Select(x => x.Name).ToArray();
                    paths[i] = properties.Where(x => x.Name == "FileName").Select(x => x.Value.ToString()).FirstOrDefault();
                }
            }


            code.AppendLine("files(");
            code.Indent();
            for (int i = 0; i < paths.Length; i++)
            {
                code.Append(code.IndentString + quoted(paths[i]));

                if (i != paths.Length - 1)
                {
                    code.Append(",");
                }

                code.Append("\r\n");
            }
            code.UnIndent();
            code.AppendLine(");");

            code.UnIndent();
            code.AppendLine("}");
            code.UnIndent();
            code.AppendLine("}");

            ScriptHost.console.WriteLine("Saving " + script + "...");
            File.WriteAllText(script, code.ToString());
        }
        return(false);
    }
예제 #29
0
        public static void UnresolveProject(Solution4 solution, Projects projects, Project project)
        {
            var solutionDirectoryPath = Path.GetDirectoryName(solution.FullName); // can be moved out side this method
            var projectDirectoryPath  = Path.GetDirectoryName(project.FullName);

            VSProject2 vsProject = project.Object as VSProject2;

            // load ivymodules
            List <KeyValuePair <IvyModule, string> > ivyModules = GetIvyModules(project);

            References references = vsProject.References;

            // http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/03d9d23f-e633-4a27-9b77-9029735cfa8d/
            string fullPath   = project.Properties.Item("FullPath").Value.ToString();
            string outputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
            string outputDir  = Path.Combine(fullPath, outputPath);

            // very important! we need to delete the output dir since it won't otherwise add references with and hintpath, instead it references the binary to their bin\Debug directory, took forever to understand!
            Directory.Delete(outputDir, true);

            foreach (Reference3 reference in references)
            {
                // do only check for assemlby references which has is a project reference and it its directory should not be a part of the solution. since we don't want to resolve our main project
                if (reference.Type == prjReferenceType.prjReferenceTypeAssembly && reference.SourceProject != null && !reference.SourceProject.FullName.Contains(solutionDirectoryPath))
                {
                    var referenceFileName = Path.GetFileName(reference.Path);

                    IvyModule foundIvyModule         = null;
                    string    foundIvyModulePath     = null;
                    Artifact  foundIvyModuleArtifact = null;

                    foreach (KeyValuePair <IvyModule, string> kvp in ivyModules)
                    {
                        IvyModule ivyModule     = kvp.Key;
                        string    ivyModulePath = kvp.Value;

                        foreach (Artifact artifact in ivyModule.Publications.ArtifactList)
                        {
                            if (artifact.Filename == referenceFileName)
                            {
                                foundIvyModule         = ivyModule;
                                foundIvyModulePath     = ivyModulePath;
                                foundIvyModuleArtifact = artifact;
                                break;
                            }
                        }

                        if (foundIvyModule != null)
                        {
                            break;
                        }
                    }

                    if (foundIvyModule == null)
                    {
                        Output.Instance.WriteLine("Could not find a matching ivy module for reference '" + reference.Name + "'");
                        continue;
                    }

                    // the calulated path to the binary reference
                    var referenceFile = new FileInfo(GetCalculatedReferencePath(projectDirectoryPath, foundIvyModule, foundIvyModuleArtifact, referenceFileName));

                    Output.Instance.WriteLine("Found a matching ivy module for reference '" + reference.Name + "', assumed path to the binary file is '" + referenceFile.FullName + "'");

                    if (!referenceFile.Exists)
                    {
                        Output.Instance.WriteLine("The reference file does not exist, assure that you'r following the patterns for dependencies.");
                        continue;
                    }

                    reference.Remove();
                    vsProject.References.Add(referenceFile.FullName);
                }
            }

            project.Save(project.FullName);

            if (!projectDirectoryPath.Contains(solutionDirectoryPath))
            {
                solution.Remove(project);
            }
        }
예제 #30
0
 internal ShellVSProject2(VSProject2 project) : base(project.Project)
 {
     _project = project;
 }
예제 #31
0
 internal ShellVSProject2(VSProject2 project) : base(project.Project)
 {
     _project = project;
 }
예제 #32
0
 public void AddReverenceToProject(Assembly assembly, VSProject2 vsProject2)
 {
     vsProject2.References.Add(assembly.Location);
 }
예제 #33
0
        public string GetSolutionDetails()
        {
            StringBuilder code = new StringBuilder();

            VSProject2    vsProject2  = project.Object as VSProject2;
            FileInfo      projectFile = new FileInfo(project.FileName);
            DirectoryInfo projectDir  = projectFile.Directory;

            code.AppendLine("/************/");
            code.AppendLine("/* Solution */");
            code.AppendLine("/************/");
            code.AppendLine("/* FileName: " + project.DTE.Solution.FileName + " */");
            code.AppendLine(String.Empty);

            code.AppendLine("/***********/");
            code.AppendLine("/* Project */");
            code.AppendLine("/***********/");
            code.AppendLine("/* Name: " + project.Name + " */");
            code.AppendLine("/* FileName: " + project.FileName + " */");
            code.AppendLine("/* FullName: " + project.FullName + " */");
            code.AppendLine("/* UniqueName: " + project.UniqueName + " */");
            code.AppendLine("/* FullName: " + projectDir.FullName + " */");
            code.AppendLine("/* TypeName: " + Information.TypeName(project.Object) + " */");
            code.AppendLine(String.Empty);

            if (vsProject2 != null)
            {
                code.AppendLine("/**************/");
                code.AppendLine("/* VSProject2 */");
                code.AppendLine("/**************/");
                code.AppendLine("/* VSProject2: " + vsProject2.ToString() + " */");
                code.AppendLine(String.Empty);

                code.AppendLine("/**************/");
                code.AppendLine("/* References */");
                code.AppendLine("/**************/");
                foreach (object obj in vsProject2.References)
                {
                    try
                    {
                        string     windir = Environment.GetEnvironmentVariable("windir");
                        Reference3 ref3   = obj as Reference3;
                        if (ref3 != null)
                        {
                            // filter out the standard assemblies
                            if (!ref3.Path.StartsWith(windir))
                            {
                                code.AppendLine("/* TypeName: " + Information.TypeName(obj) + " */");
                                code.AppendLine("/* Name: " + ref3.Name + " */");
                                code.AppendLine("/* Path: " + ref3.Path + " */");
                                code.AppendLine("/* AutoReferenced: " + ref3.AutoReferenced + " */");
                                code.AppendLine("/* Description: " + ref3.Description + " */");
                                code.AppendLine("/* Resolved: " + ref3.Resolved + " */");
                                code.AppendLine("/* Version: " + ref3.Version + " */");

                                code.AppendLine(AssemblyHelper.GetAssemblyDetails(ref3.Path));
                                code.AppendLine(String.Empty);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        code.AppendLine("/* Exception: " + ex.Message + " */");
                    }
                }
            }

            return(code.ToString());
        }
예제 #34
0
 public bool IsReferenceAlreadyAdded(string assemblyName, VSProject2 projecta)
 {
     return projecta.References.OfType<Reference>().Any(x => x.Name.Equals(assemblyName));
 }
 private static void AddMissingReferencesForProject(VSProject2 standardProject, ICollection<string> referenceFileNames)
 {
     foreach (var referenceFileName in referenceFileNames)
     {
         if (standardProject.References.Find(referenceFileName) == null)
         {
             standardProject.References.Add(referenceFileName);
         }
     }
 }
예제 #36
0
    static void Main(string[] args)
    {
        String                prjTemplDir    = Path.Combine(vsInstallPath, @"Common7\IDE\ProjectTemplates");
        List <String>         vsTemplates    = Directory.GetFiles(prjTemplDir, "*.vstemplate", SearchOption.AllDirectories).Select(x => x.Substring(prjTemplDir.Length + 1)).ToList();
        Regex                 re             = new Regex("^(.*?)" + Regex.Escape(@"\"));
        Func <String, String> untilBackSlash = (s) => { return(re.Match(s).Groups[1].ToString()); };
        List <String>         languages      = vsTemplates.Select(x => untilBackSlash(x)).ToList();
        List <String>         vsNames        = new List <string>();

        for (int i = 0; i < vsTemplates.Count; i++)
        {
            bool   keep = true;
            String lang = languages[i];
            if (lang != "CSharp" && lang != "VC" && lang != "Javascript")
            {
                keep = false;
            }

            if (
                vsTemplates[i].Contains("WebTemplate")  // has wizard
                ||
                vsTemplates[i].Contains("WapProj")      // hangs
                )
            {
                keep = false;
            }

            if (!keep)
            {
                vsTemplates.RemoveAt(i);
                languages.RemoveAt(i);
                i--;
                continue;
            }
            vsTemplates[i] = vsTemplates[i].Substring(languages[i].Length + 1);
            vsNames.Add(vsTemplates[i].Replace("\\", "_").Replace("1033_", "").Replace(".vstemplate", "").Replace(".", ""));
        }

        //var procs = System.Diagnostics.Process.GetProcesses().Where(x => x.ProcessName == "devenv").ToArray();
        //String devenvPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe";
        //Assembly asm = Assembly.LoadFile(devenvPath);

        DTE2 dte = null;

        try
        {
            //String[] allPaths = {
            //    Path.Combine(vsInstallPath, @"Common7\IDE\PublicAssemblies"),
            //    // VCProjectShim is here.
            //    Path.Combine(vsInstallPath, @"Common7\IDE\CommonExtensions\Microsoft\VC\Project")
            //};

            //AppDomain.CurrentDomain.AssemblyResolve += (s, asmArgs) =>
            //{
            //    String dllName = new AssemblyName(asmArgs.Name).Name + ".dll";

            //    foreach (String dir in allPaths)
            //    {
            //        string path = Path.Combine(dir, dllName);

            //        if (!File.Exists(path))
            //            continue;

            //        return Assembly.LoadFrom(path);
            //    }

            //    Console.WriteLine("Warning: Required assembly not found: " + dllName);
            //    return null;
            //};

            //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.10.0"), true);
            //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.12.0"), true);
            //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.16.0"), true);

            bool bNormalStart = false;

            MessageFilter.Register();
            if (bNormalStart)
            {
                dte = (DTE2)Activator.CreateInstance(Type.GetTypeFromProgID(vsId), true);
            }
            else
            {
                //Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService()
                bool     bAttached         = false;
                int      processId         = 0;
                Process2 processToAttachTo = null;

                for (int iTry = 0; iTry < 2; iTry++)
                {
                    dte = (DTE2)Marshal.GetActiveObject(debuggerVsId);

                    var       processes = dte.Debugger.LocalProcesses.Cast <EnvDTE.Process>().ToArray();
                    Debugger2 debugger2 = (Debugger2)dte.Debugger;

                    //
                    // https://varionet.wordpress.com/tag/debug/
                    // Attach2 sometimes triggers error: 8971001E, need to detach from all processes.
                    // Something to do debugging multiple processes?
                    //
                    debugger2.DetachAll();

                    int       c         = debugger2.Transports.Count;
                    Transport transport = debugger2.Transports.Item(1 /* Default transport */);
                    //foreach (var ix in transport.Engines)
                    //{
                    //    Engine e = ix as Engine;

                    //    String name = e.Name;
                    //    Console.WriteLine("'" + name + "'");
                    //}

                    // Otherwise will get timeout while trying to evaluate any com object in visual studio watch window
                    String debuggerType = "Managed (v3.5, v3.0, v2.0)";
                    //String debuggerType = "Managed (v4.6, v4.5, v4.0)";
                    //String debuggerType = "Managed";
                    Engine[] engines = new Engine[] { transport.Engines.Item(debuggerType) };

                    foreach (var process in processes)
                    {
                        String name = Path.GetFileNameWithoutExtension(Utils.call(() => (process.Name))).ToLower();
                        if (name != "devenv")
                        {
                            continue;
                        }

                        processId = Utils.call(() => (process.ProcessID));
                        String cmdArgs = GetProcessCommandLine(processId);

                        if (cmdArgs == null || !cmdArgs.Contains("-Embedding"))
                        {
                            continue;
                        }

                        processToAttachTo = process as Process2;
                        //Console.ReadKey();
                        Console.WriteLine("Attaching to: " + processId);
                        Utils.callVoidFunction(() => { processToAttachTo.Attach2(engines); });
                        // Apparently it takes some time for debugger to attach to process, otherwise missing breakpoints.
                        // Not sure if some sort of wait could be triggerred.
                        //System.Threading.Thread.Sleep(2000);
                        bAttached = true;
                        break;
                    }

                    if (bAttached)
                    {
                        break;
                    }

                    {
                        if (iTry == 1)
                        {
                            Console.WriteLine("Error: Failed to launch vs2017/2019.");
                            return;
                        }

                        // Analogue of
                        // Activator.CreateInstance(Type.GetTypeFromProgID(vsId), true);
                        // only with  experimental visual studio version.
                        Start_devenv_Embedded();
                    }
                }

                dte = (DTE2)GetDTE(processId, 120);
                //dte = null;
            }

            String edition = dte.Edition;
            Console.WriteLine("Edition: " + edition);
            Console.WriteLine("-----------------------------------------------");

            // Make it visible.
            if (!dte.MainWindow.Visible)
            {
                dte.MainWindow.Visible = true;
                dte.UserControl        = true;
            }

            Solution2 sln2 = (Solution2)dte.Solution;
            //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution2.sln");
            //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution.sln");
            //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution1.sln");
            //sln2.Close();

            // Add existing project to solution
            //String projPath = @"D:\PrototypingQuick\ProjectGen\Dll1\Dll1.vcxproj";
            //String projPath = @"D:\PrototypingQuick\ProjectGen\Dll1\Dll2.vcxproj";
            //sln2.AddFromFile(projPath);
            //sln2.SolutionBuild.Build();

            //Microsoft.VisualStudio.OLE.Interop.IServiceProvider serv = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte;
            //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile", "args");
            //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile");
            //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile", "thisIsArg1");
            //dte.ExecuteCommand("Tools.InvokeExecuteScript", @"D:\Prototyping\cppscriptcore\Tools\vsDev\bin\Debug\vsDev.dll");
            //int cmdCount = Utils.call(() => (dte.Commands.Count));


            //for( int i = 1; i <= cmdCount; i++)
            //{
            //    Command c = Utils.call(() => dte.Commands.Item(i));
            //    Console.WriteLine(Utils.call(() => c.Name));
            //    Console.WriteLine( "    " + Utils.call(() => c.ID));
            //    Console.WriteLine( "    " + Utils.call(() => c.Guid.ToString()) );
            //    Console.WriteLine();
            //}

            //Guid service = new Guid("89BE061A-1103-4D1D-8293-A51F8480E202");
            //Guid serviceApi = new Guid("89BE061A-1103-4D1D-8293-A51F8480E201");
            //IntPtr obj = IntPtr.Zero;
            //int r = serv.QueryService(ref service, ref serviceApi, out obj);

            //Console.WriteLine("[ Press any key to close ... ]");
            //Console.ReadKey();

            /*
             * // Generate huge amount of temporary projects.
             * Solution2 sln2 = (Solution2)dte.Solution;
             * String mainDir = @"d:\Prototyping\testsln";
             * String slnTempDir = Path.Combine(mainDir, "slnTemp");
             *
             *
             * for (int i = 0; i < vsTemplates.Count; i++)
             * {
             *  String name = vsNames[i];
             *  String dir = Path.Combine(mainDir, name);
             *  bool bKeepProject = true;
             *
             *  if (Directory.Exists(dir))
             *      Directory.Delete(dir, true);
             *
             *  Console.Write("Project '" + name + "... " );
             *  Directory.CreateDirectory(dir);
             *  sln2.Create(slnTempDir, name);
             *
             *  try
             *  {
             *      string csTemplatePath = sln2.GetProjectTemplate(vsTemplates[i], languages[i]);
             *      sln2.AddFromTemplate(csTemplatePath, dir, name, false);
             *      Console.WriteLine("ok." );
             *  }
             *  catch (Exception ex)
             *  {
             *      Console.WriteLine("Project '" + name + ": " + ex.Message);
             *      bKeepProject = false;
             *  }
             *  if(bKeepProject)
             *      sln2.SaveAs(Path.Combine(dir, name + ".sln"));
             *  sln2.Close(bKeepProject);
             *
             *  if (!bKeepProject)
             *      Directory.Delete(dir, true);
             * }
             */


            Solution sln = dte.Solution;

            /*
             * String slnPath = @"c:\Prototyping\testsln";
             * if( !sln.IsOpen )
             *  sln.Create(slnPath, "test");
             * Solution2 sln2 = (Solution2) sln;
             * Solution3 sln3 = (Solution3) sln;
             *
             * int nCount = sln.Projects.Count;
             *
             * dte.Events.SolutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
             * dte.Events.SolutionItemsEvents.ItemAdded += SolutionItemsEvents_ItemAdded;
             * dynamic events = dte.Events.GetObject("CSharpProjectItemsEvents");
             * //Events2 events2 = dte.Events as Events2;
             * //events2.ProjectItemsEvents.ItemAdded += Pievents_ItemAdded;
             * pievents = events as ProjectItemsEvents;
             * pievents.ItemAdded += Pievents_ItemAdded;
             *
             *
             * if (nCount <= 0)
             * {
             *  string csTemplatePath = sln2.GetProjectTemplate(@"Windows\1033\ConsoleApplication\csConsoleApplication.vstemplate", "CSharp");
             *  sln.AddFromTemplate(csTemplatePath, slnPath + "\\prj", "Foo", false);
             *  dte.ExecuteCommand("File.SaveAll");
             * }
             */

            //sln.Open(@"D:\PrototypingQuick\ConsoleApplication2\ConsoleApplication2.sln");
            while (sln.Projects.Count == 0)
            {
                Console.WriteLine("Please open solution in newly opened visual studio and then press enter to continue...");
                Console.ReadLine();
            }

            // Enumerate available configurations within a project
            Project p = sln2.Projects.Item(1);

            //
            // Get / set .NET framework version, https://blogs.msdn.microsoft.com/visualstudio/2010/02/25/how-to-retarget-a-project-using-dte/
            //
            // ".NETFramework,Version=v4.7.2"
            //
            String DotNetVersion = p.Properties.Item("TargetFrameworkMoniker").Value;


            var oConfs = p.ConfigurationManager.Cast <Configuration>().ToArray();
            var confs  = oConfs.Select(x => x.ConfigurationName + "|" + x.PlatformName).ToArray();

            foreach (String c in confs)
            {
                Console.WriteLine("- " + c);
            }

            // C#/C++ project properties scanning
            //Project p = sln.Projects.Item(1);
            //Dictionary<String, Object> d = new Dictionary<string, object>();
            //foreach (Property prop in p.Properties)
            //{
            //    try
            //    {
            //        d[prop.Name] = prop.Value;
            //    }
            //    catch (Exception)
            //    {
            //    }
            //}

            // C++ project model scanning
            //VCProject vcProject = p.Object as VCProject;
            //VCProject vcProject = (VCProject)p.Object;

            //if (vcProject == null)
            //{
            //    MessageFilter.Revoke();
            //    Console.WriteLine("Not a C++ project or vs2017 or later (registry moved to file problem).");
            //    Console.WriteLine("[Press any key to close]");
            //    Console.ReadLine();
            //    return;
            //}

            //VCProjectEngine peng2 = vcProject.VCProjectEngine as VCProjectEngine;
            //VCProjectEngineShim peng = peng2 as VCProjectEngineShim;
            //var sp = peng.VsServiceProvider;

            // Scan for all subprojects.
            List <Project> projects = GetProjects(sln);
            foreach (Project genProj in projects)
            {
#if !OLD_VS
                VSProject2 sharpProj = genProj.Object as VSProject2;
#else
                VSProject2 sharpProj = genProj.Object as VSProject2;
                //VSProject3 sharpProj = genProj.Object as VSProject3;
                //VSProject4 sharpProj = genProj.Object as VSProject4;
#endif
                VCProject cppProj = genProj.Object as VCProject;

                String name = genProj.Name;
                Console.Write("Project: " + name + " - language( ~" + genProj.Kind + "): ");
                if (sharpProj == null && cppProj == null)
                {
                    Console.WriteLine("Unknown");
                    continue;
                }

                if (sharpProj != null)
                {
                    Console.WriteLine("C#");
                }

                if (cppProj != null)
                {
                    Console.WriteLine("C++ ");
                }

                //foreach (Reference r in ((References)vsp2.References).Cast<Reference>())
                //{
                //    Console.WriteLine(r.Path);
                //    Console.WriteLine("CopyLocal = " + r.CopyLocal);
                //}
            }

            Console.WriteLine("[Press any key to close]");
            Console.ReadLine();

            // Get project GUID
            //IVsSolution service = GetService( dte, typeof(IVsSolution)) as IVsSolution;

            //String uname = p.UniqueName;
            //IVsHierarchy hierarchy;
            //service.GetProjectOfUniqueName(uname, out hierarchy);
            //Guid projectGuid;
            //hierarchy.GetGuidProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid);

            //Console.WriteLine("Project guid: " + projectGuid.ToString());

            // Add file in programming language independent manner.
            //p.ProjectItems.AddFromFile(@"D:\Prototyping\cppscriptcore\cppscript\cppscript.cpp");

            //if (vcProject != null)
            //{
            //foreach (object oFile in (IVCCollection)vcProject.Files)
            //{
            //    VCFile file = oFile as VCFile;
            //    Console.WriteLine(file.Name);
            //    Console.WriteLine(" " + file.RelativePath);

            //    foreach (var _conf in (IVCCollection)file.FileConfigurations)
            //    {
            //        VCFileConfiguration conf = _conf as VCFileConfiguration;
            //        Console.WriteLine(conf.Name);

            //        VCCLCompilerTool compilerTool = conf.Tool as VCCLCompilerTool;
            //        if (compilerTool == null)
            //            continue;

            //        Console.WriteLine("Defines: " + compilerTool.PreprocessorDefinitions);
            //    }
            //}


            //VCFilter f = null;
            //foreach (object oItem in (IVCCollection)vcProject.Items)
            //{
            //    VCFile file = oItem as VCFile;
            //    VCFilter fitem = oItem as VCFilter;

            //    if (fitem != null && fitem.Name == "Test1")
            //        f = fitem;
            //}

            //if( f == null )
            //    f = vcProject.AddFilter("Test1") as VCFilter;
            //f.AddFile(@"D:\Prototyping\cppscriptcore\cppscript\cppscript.cpp");


            // Recursive files / folder adding / C++ project
            //String fromDir = @"C:\Prototyping\vlc-3.0.2";

            //List<String> files = Directory.GetFiles(fromDir, "*.c", SearchOption.AllDirectories).ToList();
            //files.AddRange(Directory.GetFiles(fromDir, "*.h", SearchOption.AllDirectories));
            //files = files.Select(x => x.Substring(fromDir.Length + 1)).ToList();

            //Stopwatch sw = Stopwatch.StartNew();

            //foreach (String file in files)
            //{
            //    String[] pp = file.Split('\\');
            //    IVCCollection items = (IVCCollection)vcProject.Items;
            //    VCFilter parent = null;
            //    VCFilter filter = null;

            //    for (int i = 0; i < pp.Length - 1; i++)
            //    {
            //        filter = items.OfType<VCFilter>().Where(x => x.Name == pp[i]).FirstOrDefault();
            //        if (filter == null)
            //            if (i == 0)
            //                filter = (VCFilter)vcProject.AddFilter(pp[i]);
            //            else
            //                filter = (VCFilter)parent.AddFilter(pp[i]);

            //        parent = filter;
            //        items = (IVCCollection)parent.Items;
            //    }

            //    String fullpath = Path.Combine(fromDir, file);
            //    if (filter == null)
            //        vcProject.AddFile(fullpath);
            //    else
            //        filter.AddFile(fullpath);
            //}

            //sw.Stop();
            //Console.WriteLine(sw.ElapsedMilliseconds);
            //}

            MessageFilter.Revoke();
            //Console.WriteLine();
            //Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            Console.WriteLine("Stack trace: " + ex.StackTrace);
            Console.ReadKey();
        }
        finally
        {
            // Need to close solution, so devenv.exe would not remain hanging in memory.
            //if (dte != null)
            //    dte.Solution.Close();
        }
    }