/// <summary>
        ///     Returns the <see cref="HierarchyId"/> of the given document moniker, or
        ///     <see cref="HierarchyId.Nil"/> if the document moniker is not part of the project.
        /// </summary>
        public static HierarchyId GetHierarchyId(this IVsProject project, string documentMoniker)
        {
            Requires.NotNull(project, nameof(project));
            Requires.NotNullOrEmpty(documentMoniker, nameof(documentMoniker));

            var     priority = new VSDOCUMENTPRIORITY[1];
            int     isFound;
            uint    itemId;
            HResult result = project.IsDocumentInProject(documentMoniker, out isFound, priority, out itemId);

            if (result.Failed)
            {
                throw result.Exception;
            }

            // We only return items that are actually part of the project. CPS returns non-member from this API.
            if (isFound == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard && priority[0] != VSDOCUMENTPRIORITY.DP_Intrinsic)
            {
                return(HierarchyId.Nil);
            }

            HierarchyId id = itemId;

            Assumes.False(id.IsNilOrEmpty);

            return(id);
        }
Ejemplo n.º 2
0
        private ProjectItem GetProjectItem(string document, string codeBehind, string codeBehindFile)
        {
            // grabbed from Microsoft.VisualStudio.Web.Application.VsHierarchyItem.ctor(IVsHierarchy hier)
            IVsProject project = _hierarchy as IVsProject;

            if (project != null)
            {
                int  pfFound  = 0;
                uint vsitemid = uint.MaxValue;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                if (project.IsDocumentInProject(codeBehindFile, out pfFound, pdwPriority, out vsitemid) == NativeMethods.S_OK &&
                    (pfFound != 0) &&
                    (vsitemid != uint.MaxValue))
                {
                    var    propid = __VSHPROPID.VSHPROPID_ExtObject;
                    object pvar   = null;

                    _hierarchy.GetProperty(vsitemid, (int)propid, out pvar);

                    return(pvar as ProjectItem);
                }
            }

            return(null);
        }
Ejemplo n.º 3
0
        public static bool GetProjectAndFileInfoForPath(
            IVsProject vsProject, string originalPath, out IVsHierarchy projectHierarchy, out Project project, out uint fileItemId,
            out bool isDocInProject)
        {
            isDocInProject   = false;
            fileItemId       = 0;
            projectHierarchy = null;
            project          = null;

            var priority          = new VSDOCUMENTPRIORITY[1];
            var isDocInProjectInt = 0;

            uint foundItemId = 0;
            var  hr          = vsProject.IsDocumentInProject(originalPath, out isDocInProjectInt, priority, out foundItemId);

            if (NativeMethods.Succeeded(hr) && isDocInProjectInt == 1)
            {
                projectHierarchy = vsProject as IVsHierarchy;
                if (projectHierarchy != null)
                {
                    project = GetProject(projectHierarchy);
                }
                fileItemId     = foundItemId;
                isDocInProject = true;
            }
            return(isDocInProject);
        }
        public static void SetupGenerated(IVsProject project, EnvDTE.Configuration configuration, String filter, List <string> files, bool generatedFilesPerConfiguration)
        {
            List <string> missing = new List <string>();

            foreach (String file in files)
            {
                if (!Directory.Exists(Path.GetDirectoryName(file)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                }

                if (!File.Exists(file))
                {
                    File.Create(file).Dispose();
                }

                int  found;
                uint id;
                VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
                project.IsDocumentInProject(file, out found, priority, out id);
                if (found == 0)
                {
                    missing.Add(file);
                }
            }

            Package.Instance.VCUtil.AddGeneratedFiles(DTEUtil.GetProject(project as IVsHierarchy), configuration, filter, missing, generatedFilesPerConfiguration);
        }
Ejemplo n.º 5
0
 public static bool ContainsFile(this Project project, string path)
 {
     if (string.Equals(project.Kind, VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
         string.Equals(project.Kind, VsConstants.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
         string.Equals(project.Kind, VsConstants.FsharpProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
     {
         // For Wix and Nemerle projects, IsDocumentInProject() returns not found
         // even though the file is in the project. So we use GetProjectItem()
         // instead. Nemerle is a high-level statically typed programming language for .NET platform
         // Note that pszMkDocument, the document moniker, passed to IsDocumentInProject(), must be a path to the file
         // for certain file-based project systems such as F#. And, not just a filename. For these project systems as well,
         // do the following
         ProjectItem item = project.GetProjectItem(path);
         return(item != null);
     }
     else
     {
         IVsProject vsProject = (IVsProject)project.ToVsHierarchy();
         if (vsProject == null)
         {
             return(false);
         }
         int  pFound;
         uint itemId;
         int  hr = vsProject.IsDocumentInProject(path, out pFound, new VSDOCUMENTPRIORITY[0], out itemId);
         return(ErrorHandler.Succeeded(hr) && pFound == 1);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Check whether the project contains a document.
        /// </summary>
        /// <param name="project">IVsProject</param>
        /// <param name="pszMkDocument">full path of document</param>
        /// <returns>true if project contains document</returns>
        public static uint IsDocumentInProject2(this IVsProject project, string pszMkDocument)
        {
            int  found;
            uint itemId;

            VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
            project.IsDocumentInProject(pszMkDocument, out found, prio, out itemId);
            return(found != 0 ? itemId : 0);
        }
Ejemplo n.º 7
0
        private static ProjectItem RetrieveProjectItem(string documentPath)
        {
            int  itemFound;
            uint itemId;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

            DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;

            if (dte == null)
            {
                throw new InvalidOperationException("Cannot get the global service from package. DTE is null. Document path is " + documentPath);
            }

            Array ary = dte.ActiveSolutionProjects as Array;

            if (ary == null)
            {
                throw new InvalidOperationException("Cannot get the active solution projects. Document path is " + documentPath);
            }

            Project project = ary.GetValue(0) as Project;

            if (project == null)
            {
                throw new InvalidOperationException("Cannot get the first project. Document path is " + documentPath);
            }

            IVsProject vsProject = VsHelper.ToVsProject(project);

            if (project == null)
            {
                throw new InvalidOperationException("Cannot convert project to VS project. Document path is " + documentPath);
            }

            vsProject.IsDocumentInProject(documentPath, out itemFound, pdwPriority, out itemId);

            if (itemFound == 0 || itemId == 0)
            {
                throw new InvalidOperationException("VsProject.IsDocumentInProject failed to find the document in the project. Document path is " + documentPath);
            }

            IServiceProvider oleSp;

            vsProject.GetItemContext(itemId, out oleSp);
            if (oleSp == null)
            {
                throw new InvalidOperationException("Cannot get item context. Document path is " + documentPath);
            }

            ServiceProvider sp   = new ServiceProvider(oleSp);
            ProjectItem     item = sp.GetService(typeof(ProjectItem)) as ProjectItem;

            return(item);
        }
        /// <summary>
        /// Looks through the <paramref name="project"/> and all subitems / subprojects to find the project hosting the active configuration section designer window.
        /// </summary>
        /// <param name="project">the parent project.</param>
        /// <param name="docPriority">Specifies the priority level of a document within a project.</param>
        /// <param name="configurationSectionModelFile">the project item represented by inputFilePath, if found (ex: MyProject\ConfigurationSection.csd).</param>
        /// <param name="inputFilePath">the file path of the project item.</param>
        /// <returns><c>true</c> if found; otherwise <c>false</c>.</returns>
        public static bool TryFindProjectItemWithFilePath(Project project, VSDOCUMENTPRIORITY[] docPriority, string inputFilePath, out ProjectItem configurationSectionModelFile)
        {
            Diagnostics.DebugWrite("VsHelper.TryFindProjectItemWithFilePath (VH.TFP).");
            bool projectFound = false;

            configurationSectionModelFile = null;

            // Nothing useful for this project. Process the next one.
            if (string.IsNullOrEmpty(project.FileName) || !File.Exists(project.FileName))
            {
                Diagnostics.DebugWrite("VH.TFP >> Nothing useful found in this current dte.Solution.Projects item. Continuing loop...");
                return(false);
            }

            // obtain a reference to the current project as an IVsProject type
            IVsProject vsProject = VsHelper.ToVsProject(project);

            Diagnostics.DebugWrite("VH.TFP >> IVsProject vsProject = VsHelper.ToVsProject( project='{0}' )", project.Name);

            int  iFound = 0;
            uint itemId = 0;

            // this locates, and returns a handle to our source file, as a ProjectItem
            vsProject.IsDocumentInProject(inputFilePath, out iFound, docPriority, out itemId);
            Diagnostics.DebugWrite("VH.TFP >> vsProject.IsDocumentInProject(inputFilePath, out iFound={0}, pdwPriority, out itemId={1}).", iFound, itemId);

            // TODO: [abm] Below here, project build failed! Error was "type is not of VsProject". This only occured on a brand new
            // project with brand new csd. After failed rebuild attempt of project, it all worked.
            // Find out why and fix (or create warning message) to guide future users! Not yet reproducible...

            // if this source file is found in this project
            if (iFound != 0 && itemId != 0)
            {
                Diagnostics.DebugWrite("VH.TFP >> (iFound != 0 && itemId != 0) == TRUE!!!");
                Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSp = null;
                vsProject.GetItemContext(itemId, out oleSp);
                if (oleSp != null)
                {
                    Diagnostics.DebugWrite("VH.TFP >> vsProject.GetItemContext( itemId, out oleSp ) >> oleSp != null! Getting ServiceProvider sp...");
                    ServiceProvider sp = new ServiceProvider(oleSp);
                    // convert our handle to a ProjectItem
                    configurationSectionModelFile = sp.GetService(typeof(ProjectItem)) as ProjectItem;

                    if (configurationSectionModelFile != null)
                    {
                        Diagnostics.DebugWrite("VH.TFP >>  configurationSectionModelFile = sp.GetService( typeof( ProjectItem ) ) as ProjectItem is NOT null! Setting this._project to the project we were working on...");
                        // We now have what we need. Stop looking.
                        projectFound = true;
                    }
                }
            }
            return(projectFound);
        }
        public static EnvDTE.ProjectItem GetProjectItem(this IVsProject project, string path)
        {
            int  found;
            uint item;
            var  priority = new VSDOCUMENTPRIORITY[1];

            ErrorHandler.ThrowOnFailure(project.IsDocumentInProject(path, out found, priority, out item));
            if (found == 0 || (priority[0] != VSDOCUMENTPRIORITY.DP_Standard && priority[0] != VSDOCUMENTPRIORITY.DP_Intrinsic))
            {
                return(null);
            }
            return(project.GetProjectItem(item));
        }
Ejemplo n.º 10
0
        public void AddGeneratedFile(IVsProject project, VCFilter filter, string path, EnvDTE.Configuration config)
        {
            int  found;
            uint id;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            project.IsDocumentInProject(path, out found, priority, out id);
            if (found == 0)
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                }

                VCFile file = null;
                if (config == null)
                {
                    file = filter.AddFile(path);
                }
                else
                {
                    filter = FindOrCreateFilter(filter, config.PlatformName);
                    filter = FindOrCreateFilter(filter, config.ConfigurationName);
                    file   = filter.AddFile(path);
                    foreach (VCFileConfiguration c in file.FileConfigurations)
                    {
                        if (!c.ProjectConfiguration.ConfigurationName.Equals(config.ConfigurationName) ||
                            !c.ProjectConfiguration.Platform.Name.Equals(config.PlatformName))
                        {
                            c.ExcludedFromBuild = true;
                        }
                    }
                }

                try
                {
                    //
                    // Remove the file otherwise it will be considered up to date.
                    //
                    File.Delete(path);
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 11
0
        public static bool ContainsFile(this Project project, string name)
        {
            IVsProject vsProject = (IVsProject)project.ToVsHierarchy();

            if (vsProject == null)
            {
                return(false);
            }
            int  pFound;
            uint itemId;
            int  hr = vsProject.IsDocumentInProject(name, out pFound, new VSDOCUMENTPRIORITY[0], out itemId);

            return(ErrorHandler.Succeeded(hr) && pFound == 1);
        }
 /// <summary>
 /// Pres the content of the generate.
 /// </summary>
 /// <param name="vsProject">The vs project.</param>
 /// <param name="inputFileName">The input file path.</param>
 /// <exception cref="System.ApplicationException">
 /// Unable to retrieve Visual Studio ProjectItem
 /// or
 /// Unable to retrieve Visual Studio ProjectItem
 /// </exception>
 protected void PreGenerateCode(IVsProject vsProject, string inputFileName)
 {
     _newFileNames.Clear();
     int iFound;
     uint itemId;
     vsProject.IsDocumentInProject(inputFileName, out iFound, new VSDOCUMENTPRIORITY[1], out itemId);
     if (iFound == 0 || itemId == 0)
         throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
     IServiceProvider sp;
     vsProject.GetItemContext(itemId, out sp);
     if (sp == null)
         throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
     var item = (new ServiceProvider(sp).GetService(typeof(ProjectItem)) as ProjectItem);
     foreach (string i in this)
     {
         try
         {
             var inputFileName2 = GetFileName(i);
             _newFileNames.Add(inputFileName2);
             var path = Path.Combine(inputFileName.Substring(0, inputFileName.LastIndexOf(Path.DirectorySeparatorChar)), inputFileName2);
             var inputFileContent2 = string.Empty;
             if (File.Exists(path))
                 try { inputFileContent2 = File.ReadAllText(path); }
                 catch (Exception) { inputFileContent2 = string.Empty; }
             var s = File.Create(path);
             try
             {
                 var data = GenerateChildCode(path, inputFileContent2);
                 s.Write(data, 0, data.Length);
                 s.Close();
                 item.ProjectItems.AddFromFile(path);
             }
             catch (Exception)
             {
                 s.Close();
                 if (File.Exists(path))
                     File.Delete(path);
             }
         }
         catch (Exception ex) { throw ex; }
     }
     foreach (ProjectItem childItem in item.ProjectItems)
         if (!(childItem.Name.EndsWith(GetDefaultExtension()) || _newFileNames.Contains(childItem.Name)))
             childItem.Delete();
 }
Ejemplo n.º 13
0
        private ProjectItem _getTemplateProjectItem()
        {
            Project dteProject = _getTemplateProject();

            IVsProject vsProject = _dteProjectToVsProject(dteProject);

            int  iFound = 0;
            uint itemId = 0;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
            int result = vsProject.IsDocumentInProject(_host.TemplateFile, out iFound, pdwPriority, out itemId);

            if (result != VSConstants.S_OK)
            {
                throw new Exception("Unexpected error calling IVsProject.IsDocumentInProject");
            }
            if (iFound == 0)
            {
                throw new Exception("Cannot retrieve ProjectItem for template file");
            }
            if (itemId == 0)
            {
                throw new Exception("Cannot retrieve ProjectItem for template file");
            }

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider itemContext = null;
            result = vsProject.GetItemContext(itemId, out itemContext);
            if (result != VSConstants.S_OK)
            {
                throw new Exception("Unexpected error calling IVsProject.GetItemContext");
            }
            if (itemContext == null)
            {
                throw new Exception("IVsProject.GetItemContext returned null");
            }

            ServiceProvider itemContextService = new ServiceProvider(itemContext);
            ProjectItem     templateItem       = (ProjectItem)itemContextService.GetService(typeof(ProjectItem));

            Debug.Assert(templateItem != null, "itemContextService.GetService returned null");

            return(templateItem);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Finds the item in the solution matching the specified file path.
        /// </summary>
        /// <param name="filePath">The absolute file path of a file that exists in the solution.</param>
        /// <returns><see langword="null"/> if the file wasn't found in the solution.</returns>
        public static async Task <PhysicalFile?> FromFileAsync(string filePath)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IEnumerable <IVsHierarchy> projects = await VS.Solutions.GetAllProjectHierarchiesAsync();

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];

            foreach (IVsHierarchy hierarchy in projects)
            {
                IVsProject proj = (IVsProject)hierarchy;
                proj.IsDocumentInProject(filePath, out int isFound, priority, out uint itemId);

                if (isFound == 1)
                {
                    return(await FromHierarchyAsync(hierarchy, itemId) as PhysicalFile);
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
        private void InvalidateParentItems(string[] oldFileNames, string[] newFileNames)
        {
            int pfFound;

            VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];
            uint        pItemid;
            List <uint> itemIds = new List <uint>();

            for (int i = 0; i < newFileNames.Length; i++)
            {
                if (Path.GetFileName(newFileNames[i]) == Path.GetFileName(oldFileNames[i]))
                {
                    continue;
                }
                ErrorHandler.ThrowOnFailure(innerProject.IsDocumentInProject(newFileNames[i], out pfFound, pdwPriority, out pItemid));
                if (pfFound == 0)
                {
                    continue;
                }
                itemIds.Add(pItemid);
            }
            InvalidateParentItems(itemIds);
        }
Ejemplo n.º 16
0
        //--------------------------------------------------------------------------------------------
        /// <summary>
        ///     Locates the item in the provided hierarchy using the provided moniker
        ///     and return a VsHierarchyItem for it
        /// </summary>
        //--------------------------------------------------------------------------------------------
        internal static VsHierarchyItem CreateFromMoniker(string moniker, IVsHierarchy hier)
        {
            VsHierarchyItem item = null;

            if (!string.IsNullOrEmpty(moniker) && hier != null)
            {
                IVsProject proj = hier as IVsProject;
                if (proj != null)
                {
                    int  hr;
                    int  isFound = 0;
                    uint itemid  = VSConstants.VSITEMID_NIL;
                    VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
                    hr = proj.IsDocumentInProject(moniker, out isFound, priority, out itemid);
                    if (ErrorHandler.Succeeded(hr) && isFound != 0 && itemid != VSConstants.VSITEMID_NIL)
                    {
                        item = new VsHierarchyItem(itemid, hier);
                    }
                }
            }

            return(item);
        }
Ejemplo n.º 17
0
        public static bool ContainsFile(this Project project, string path)
        {
            if (string.Equals(project.Kind, VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(project.Kind, VsConstants.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
            {
                // For Wix project, IsDocumentInProject() returns not found
                // even though the file is in the project. So we use GetProjectItem()
                // instead.
                ProjectItem item = project.GetProjectItem(path);
                return(item != null);
            }
            IVsProject vsProject = (IVsProject)project.ToVsHierarchy();

            if (vsProject == null)
            {
                return(false);
            }
            int  pFound;
            uint itemId;
            int  hr = vsProject.IsDocumentInProject(path, out pFound, new VSDOCUMENTPRIORITY[0], out itemId);

            return(ErrorHandler.Succeeded(hr) && pFound == 1);
        }
Ejemplo n.º 18
0
        public override void OnExecute(CommandEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            // Cache items to avoid problems when selection changes by opening editor
            List <SvnItem> items = new List <SvnItem>(e.Selection.GetSelectedSvnItems(false));

            foreach (SvnItem item in items)
            {
                if (!item.Exists)
                {
                    continue;
                }

                bool selectInSolutionExplorer = false;

                try
                {
                    switch (e.Command)
                    {
                    case AnkhCommand.ItemOpenVisualStudio:
                        IProjectFileMapper mapper = e.GetService <IProjectFileMapper>();

                        if (mapper.IsProjectFileOrSolution(item.FullPath))
                        {
                            selectInSolutionExplorer = true;
                            break;
                        }
                        if (item.IsDirectory)
                        {
                            goto case AnkhCommand.ItemOpenWindows;
                        }

                        VsShellUtilities.OpenDocument(e.Context, item.FullPath);
                        break;

                    case AnkhCommand.ItemOpenTextEditor:
                    {
                        IVsUIHierarchy hier;
                        IVsWindowFrame frame;
                        uint           id;

                        if (!item.IsFile)
                        {
                            continue;
                        }

                        VsShellUtilities.OpenDocument(e.Context, item.FullPath, VSConstants.LOGVIEWID_TextView, out hier, out id, out frame);
                    }
                    break;

                    case AnkhCommand.ItemOpenWindows:
                        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(item.FullPath);
                        psi.Verb = "open";
                        System.Diagnostics.Process.Start(psi);
                        break;
                    }
                }
                catch (IOException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (COMException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (InvalidOperationException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (System.ComponentModel.Win32Exception ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (selectInSolutionExplorer)
                {
                    IVsUIHierarchyWindow hierWindow = VsShellUtilities.GetUIHierarchyWindow(e.Context, new Guid(ToolWindowGuids80.SolutionExplorer));

                    IVsProject project = VsShellUtilities.GetProject(e.Context, item.FullPath) as IVsProject;

                    if (hierWindow != null)
                    {
                        int  found;
                        uint id;
                        VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
                        if (project != null && VSErr.Succeeded(project.IsDocumentInProject(item.FullPath, out found, prio, out id)) && found != 0)
                        {
                            hierWindow.ExpandItem(project as IVsUIHierarchy, id, EXPANDFLAGS.EXPF_SelectItem);
                        }
                        else if (string.Equals(item.FullPath, e.Selection.SolutionFilename, StringComparison.OrdinalIgnoreCase))
                        {
                            hierWindow.ExpandItem(e.GetService <IVsUIHierarchy>(typeof(SVsSolution)), VSItemId.Root, EXPANDFLAGS.EXPF_SelectItem);
                        }

                        // Now try to activate the solution explorer
                        IVsWindowFrame solutionExplorer;
                        Guid           solutionExplorerGuid = new Guid(ToolWindowGuids80.SolutionExplorer);
                        IVsUIShell     shell = e.GetService <IVsUIShell>(typeof(SVsUIShell));

                        if (shell != null)
                        {
                            shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorerGuid, out solutionExplorer);

                            if (solutionExplorer != null)
                            {
                                solutionExplorer.Show();
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            // SwitchDomainForRazorEngine();
            byte[] resultBytes;
            try
            {
                var model = new RazorModel();
                //set file name and namespace for model using
                model.DefaultNameSpace = wszDefaultNamespace;
                var info = new FileInfo(wszInputFilePath);
                if (info.Exists)
                {
                    model.FileName = info.Name;
                }
                int                  iFound;
                uint                 itemId;
                ProjectItem          item;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(project);
                // this locates, and returns a handle to our source file, as a ProjectItem
                vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId);

                // if our source file was found in the project (which it should have been)
                if (iFound != 0 && itemId != 0)
                {
                    IServiceProvider oleSp;
                    vsProject.GetItemContext(itemId, out oleSp);
                    if (oleSp != null)
                    {
                        ServiceProvider sp = new ServiceProvider(oleSp);
                        // convert our handle to a ProjectItem
                        item = sp.GetService(typeof(ProjectItem)) as ProjectItem;
                    }
                    else
                    {
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                    }
                }
                else
                {
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                }

                var generator = new RazorGenerator(wszInputFilePath, bstrInputFileContents, model);
                generator.Init();
                //get extension from header file
                if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension))
                {
                    _extenstion = generator.RazorTemplate.OutPutExtension;
                }
                //generate code
                var result = generator.Render();
                resultBytes = Encoding.UTF8.GetBytes(result);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_OK);
            }
            catch (TemplateCompilationException tex)
            {
                //Display error in result template
                foreach (var compilerError in tex.CompilerErrors)
                {
                    pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint)compilerError.Line,
                                                     (uint)compilerError.Column);
                }
                var message = MRazorUtil.GetError(tex);
                resultBytes = Encoding.UTF8.GetBytes(message);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            catch (Exception ex)
            {
                var messageBuilder = new StringBuilder(ex.Message);
                messageBuilder.AppendLine();
                if (ex.Source != null)
                {
                    messageBuilder.Append(ex.Source);
                }
                messageBuilder.Append(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    messageBuilder.AppendLine();
                    messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace);
                }
                resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString());
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            //finally
            //{
            //    //unload domain for unload dll loaded from InputDllFolder
            //    if (_domain != null) AppDomain.Unload(_domain);
            //}
        }
Ejemplo n.º 20
0
    public static bool GetProjectAndFileInfoForPath(
        IVsProject vsProject, string originalPath, out IVsHierarchy projectHierarchy, out Project project, out uint fileItemId,
        out bool isDocInProject) {
      isDocInProject = false;
      fileItemId = 0;
      projectHierarchy = null;
      project = null;

      var priority = new VSDOCUMENTPRIORITY[1];
      var isDocInProjectInt = 0;

      uint foundItemId = 0;
      var hr = vsProject.IsDocumentInProject(originalPath, out isDocInProjectInt, priority, out foundItemId);
      if (NativeMethods.Succeeded(hr) && isDocInProjectInt == 1) {
        projectHierarchy = vsProject as IVsHierarchy;
        if (projectHierarchy != null) {
          project = GetProject(projectHierarchy);
        }
        fileItemId = foundItemId;
        isDocInProject = true;
      }
      return isDocInProject;
    }
Ejemplo n.º 21
0
        /// <summary>
        /// Adds a new item in the project
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        // FXCOP: False positive
        public HierarchyNode AddItem(string name)
        {
            Guard.ArgumentNotNullOrEmptyString(name, "name");
            if (!CanAddItem(name))
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              Properties.Resources.InvalidFileName,
                              name));
            }
            FileInfo fileInfo  = null;
            string   subFolder = string.Empty;

            if (System.IO.Path.IsPathRooted(name))
            {
                fileInfo = new FileInfo(name);
            }
            else
            {
                fileInfo = new FileInfo(System.IO.Path.Combine(ProjectDir, name));
                int subFolderIndex = name.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
                if (subFolderIndex != -1)
                {
                    subFolder = name.Substring(0, subFolderIndex);
                }
            }
            if (fileInfo.Name.Equals(fileInfo.Extension, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              Properties.Resources.CannotCreateItemWithEmptyName));
            }
            if (!File.Exists(fileInfo.FullName))
            {
                Directory.CreateDirectory(fileInfo.Directory.FullName);
                File.Create(fileInfo.FullName).Dispose();
            }
            uint itemId = VSConstants.VSITEMID_NIL;
            int  found  = 1;
            VSDOCUMENTPRIORITY docPri = VSDOCUMENTPRIORITY.DP_Standard;
            int hr = project.IsDocumentInProject(fileInfo.FullName, out found, new VSDOCUMENTPRIORITY[] { docPri }, out itemId);

            Marshal.ThrowExceptionForHR(hr);
            if (found == 0)
            {
                VSADDRESULT   result        = VSADDRESULT.ADDRESULT_Cancel;
                uint          folderId      = this.ItemId;
                HierarchyNode subFolderNode = FindSubFolder(subFolder);
                if (subFolderNode != null)
                {
                    folderId = subFolderNode.ItemId;
                }
                hr = project.AddItem(folderId,
                                     VSADDITEMOPERATION.VSADDITEMOP_OPENFILE,
                                     fileInfo.Name, 1, new string[] { fileInfo.FullName },
                                     IntPtr.Zero, new VSADDRESULT[] { result });
                Marshal.ThrowExceptionForHR(hr);
            }
            hr = project.IsDocumentInProject(fileInfo.FullName, out found, new VSDOCUMENTPRIORITY[] { docPri }, out itemId);
            Marshal.ThrowExceptionForHR(hr);
            if (found == 1)
            {
                return(new HierarchyNode(this, itemId));
            }
            return(null);
        }