Пример #1
0
        /// <summary>
        /// This is called after the single file generator has been invoked to create or update the code file.
        /// </summary>
        /// <param name="fileNode">The node associated to the generator</param>
        /// <param name="data">data to update the file with</param>
        /// <param name="size">size of the data</param>
        /// <param name="fileName">Name of the file to update or create</param>
        /// <returns>full path of the file</returns>
        protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName)
        {
            string filePath             = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName);
            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user?
            if (rdt == null)
            {
                ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL);
            }

            IVsHierarchy hier;
            uint         cookie;
            uint         itemid;
            IntPtr       docData = IntPtr.Zero;

            ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie));
            if (docData != IntPtr.Zero)
            {
                Marshal.Release(docData);
                IVsTextStream srpStream = null;
                if (srpStream != null)
                {
                    int oldLen = 0;
                    int hr     = srpStream.GetSize(out oldLen);
                    if (ErrorHandler.Succeeded(hr))
                    {
                        IntPtr dest = IntPtr.Zero;
                        try
                        {
                            dest = Marshal.AllocCoTaskMem(data.Length);
                            Marshal.Copy(data, 0, dest, data.Length);
                            ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2));
                        }
                        finally
                        {
                            if (dest != IntPtr.Zero)
                            {
                                Marshal.Release(dest);
                            }
                        }
                    }
                }
            }
            else
            {
                using (FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    generatedFileStream.Write(data, 0, size);
                }

                EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem;
                if (projectItem != null && (this.projectMgr.FindChild(fileNode.FileName) == null))
                {
                    projectItem.ProjectItems.AddFromFile(filePath);
                }
            }
            return(filePath);
        }
Пример #2
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Returns the current contents of a document
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public string GetDocumentText()
        {
            string            text    = null;
            IVsPersistDocData docData = null;

            try
            {
                // Get or create the buffer
                IVsTextLines buffer = GetRunningDocumentTextBuffer();
                if (buffer == null)
                {
                    docData = CreateDocumentData();
                    buffer  = docData as IVsTextLines;
                }

                // get the text from the buffer
                if (buffer != null)
                {
                    IVsTextStream textStream = buffer as IVsTextStream;
                    if (textStream != null)
                    {
                        int length;
                        int hr = textStream.GetSize(out length);
                        if (ErrorHandler.Succeeded(hr))
                        {
                            if (length > 0)
                            {
                                IntPtr pText = Marshal.AllocCoTaskMem((length + 1) * 2);
                                try
                                {
                                    hr = textStream.GetStream(0, length, pText);
                                    if (ErrorHandler.Succeeded(hr))
                                    {
                                        text = Marshal.PtrToStringUni(pText);
                                    }
                                }
                                finally
                                {
                                    Marshal.FreeCoTaskMem(pText);
                                }
                            }
                            else
                            {
                                text = string.Empty;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (docData != null)
                {
                    docData.Close();
                }
            }

            return(text);
        }
        // From https://github.com/rsdn/nemerle/blob/master/snippets/VS2010/Nemerle.VisualStudio/LanguageService/NemerleLanguageService.cs#L565
        private void GoToLocation(string filename, TextSpan textSpan, string caption, bool asReadonly)
        {
            uint           itemID;
            IVsUIHierarchy hierarchy;
            IVsWindowFrame docFrame;
            IVsTextView    textView;

            try
            {
                VsShellUtilities.OpenDocument(_serviceProvider, filename, VSConstants.LOGVIEWID_Code,
                                              out hierarchy, out itemID, out docFrame, out textView);
            }
            catch
            {
                // File might not exist, etc.
                return;
            }

            if (asReadonly)
            {
                IVsTextLines buffer;
                ErrorHandler.ThrowOnFailure(textView.GetBuffer(out buffer));
                IVsTextStream stream = (IVsTextStream)buffer;
                stream.SetStateFlags((uint)BUFFERSTATEFLAGS.BSF_USER_READONLY);
            }

            if (caption != null)
            {
                ErrorHandler.ThrowOnFailure(docFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption));
            }

            ErrorHandler.ThrowOnFailure(docFrame.Show());

            if (textView != null)
            {
                var wpfTextView = docFrame.GetWpfTextView();
                var line        = wpfTextView.TextBuffer.CurrentSnapshot.GetLineFromPosition(textSpan.Start);
                var span        = new Microsoft.VisualStudio.TextManager.Interop.TextSpan
                {
                    iStartLine  = line.LineNumber,
                    iStartIndex = textSpan.Start - line.Start.Position,
                    iEndLine    = line.LineNumber,
                    iEndIndex   = textSpan.Start - line.Start.Position
                };

                try
                {
                    ErrorHandler.ThrowOnFailure(textView.SetCaretPos(span.iStartLine, span.iStartIndex));
                    ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(span));
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message);
                }
            }
        }
Пример #4
0
        /// <include file='doc\ShellTextBuffer.uex' path='docs/doc[@for="ShellTextBuffer.ShellTextBuffer"]/*' />
        /// <devdoc>
        ///     Creates a new shell text buffer.
        /// </devdoc>
        public ShellTextBuffer(IVsTextStream textStream, IServiceProvider serviceProvider)
        {
            this.textStream      = textStream;
            this.serviceProvider = serviceProvider;

            string fileName = FileName;

            this.loaded = fileName != null && fileName.Length > 0;

            SinkTextBufferEvents(true);
        }
Пример #5
0
        /// <include file='doc\ShellTextBuffer.uex' path='docs/doc[@for="ShellTextBuffer.Dirty"]/*' />
        /// <devdoc>
        ///      Marks this buffer as being modified.
        /// </devdoc>
        //public override void Dirty() {
        //    this.IsDirty = true;
        //}

        /// <include file='doc\ShellTextBuffer.uex' path='docs/doc[@for="ShellTextBuffer.Dispose"]/*' />
        /// <devdoc>
        ///     Disposes of this object.
        /// </devdoc>
        public override void Dispose()
        {
            // Disconnect us from the shell
            //
            SinkTextBufferEvents(false);

            if (checkoutService != null)
            {
                checkoutService.Dispose();
                checkoutService = null;
            }

            if (textStream != null)
            {
                textStream = null;
            }

            if (serviceProvider != null)
            {
                serviceProvider = null;
            }

            base.Dispose();
        }
Пример #6
0
        /// <summary>
        /// Returns the buffer contents for a moniker.
        /// </summary>
        /// <returns>Buffer contents</returns>
        private string GetBufferContents(string fileName, out IVsTextStream srpStream)
        {
            Guid   CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}");
            string bufferContents     = "";

            srpStream = null;

            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (rdt != null)
            {
                IVsHierarchy      hier;
                IVsPersistDocData persistDocData;
                uint   itemid, cookie;
                bool   docInRdt = true;
                IntPtr docData  = IntPtr.Zero;
                int    hr       = NativeMethods.E_FAIL;
                try
                {
                    //Getting a read lock on the document. Must be released later.
                    hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie);
                    if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero)
                    {
                        Guid iid = VSConstants.IID_IUnknown;
                        cookie   = 0;
                        docInRdt = false;
                        ILocalRegistry localReg = this.projectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry;
                        ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData));
                    }

                    persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                }
                finally
                {
                    if (docData != IntPtr.Zero)
                    {
                        Marshal.Release(docData);
                    }
                }

                //Try to get the Text lines
                IVsTextLines srpTextLines = persistDocData as IVsTextLines;
                if (srpTextLines == null)
                {
                    // Try getting a text buffer provider first
                    IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider;
                    if (srpTextBufferProvider != null)
                    {
                        hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines);
                    }
                }

                if (ErrorHandler.Succeeded(hr))
                {
                    srpStream = srpTextLines as IVsTextStream;
                    if (srpStream != null)
                    {
                        // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it
                        IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate;
                        if (srpBatchUpdate != null)
                        {
                            ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0));
                        }

                        int lBufferSize = 0;
                        hr = srpStream.GetSize(out lBufferSize);

                        if (ErrorHandler.Succeeded(hr))
                        {
                            IntPtr dest = IntPtr.Zero;
                            try
                            {
                                // Note that GetStream returns Unicode to us so we don't need to do any conversions
                                dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2);
                                ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest));
                                //Get the contents
                                bufferContents = Marshal.PtrToStringUni(dest);
                            }
                            finally
                            {
                                if (dest != IntPtr.Zero)
                                {
                                    Marshal.FreeCoTaskMem(dest);
                                }
                            }
                        }
                    }
                }
                // Unlock the document in the RDT if necessary
                if (docInRdt && rdt != null)
                {
                    ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie));
                }

                if (ErrorHandler.Failed(hr))
                {
                    // If this failed then it's probably not a text file.  In that case,
                    // we just read the file as a binary
                    bufferContents = File.ReadAllText(fileName);
                }
            }
            return(bufferContents);
        }
Пример #7
0
        /// <summary>
        /// Returns the buffer contents for a moniker.
        /// </summary>
        /// <returns>Buffer contents</returns>
        private string GetBufferContents(string fileName, out IVsTextStream srpStream)
        {
            Guid CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}");
            string bufferContents = "";
            srpStream = null;

            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
            if (rdt != null)
            {
                IVsHierarchy hier;
                IVsPersistDocData persistDocData;
                uint itemid, cookie;
                bool docInRdt = true;
                IntPtr docData = IntPtr.Zero;
                int hr = NativeMethods.E_FAIL;
                try
                {
                    //Getting a read lock on the document. Must be released later.
                    hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie);
                    if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero)
                    {
                        Guid iid = VSConstants.IID_IUnknown;
                        cookie = 0;
                        docInRdt = false;
                        ILocalRegistry localReg = this.projectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry;
                        ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData));
                    }

                    persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                }
                finally
                {
                    if (docData != IntPtr.Zero)
                    {
                        Marshal.Release(docData);
                    }
                }

                //Try to get the Text lines
                IVsTextLines srpTextLines = persistDocData as IVsTextLines;
                if (srpTextLines == null)
                {
                    // Try getting a text buffer provider first
                    IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider;
                    if (srpTextBufferProvider != null)
                    {
                        hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines);
                    }
                }

                if (ErrorHandler.Succeeded(hr))
                {
                    srpStream = srpTextLines as IVsTextStream;
                    if (srpStream != null)
                    {
                        // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it
                        IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate;
                        if (srpBatchUpdate != null)
                            srpBatchUpdate.FlushPendingUpdates(0);

                        int lBufferSize = 0;
                        hr = srpStream.GetSize(out lBufferSize);

                        if (ErrorHandler.Succeeded(hr))
                        {
                            IntPtr dest = IntPtr.Zero;
                            try
                            {
                                // Note that GetStream returns Unicode to us so we don't need to do any conversions
                                dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2);
                                ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest));
                                //Get the contents
                                bufferContents = Marshal.PtrToStringUni(dest);
                            }
                            finally
                            {
                                if (dest != IntPtr.Zero)
                                    Marshal.FreeCoTaskMem(dest);
                            }
                        }
                    }

                }
                // Unlock the document in the RDT if necessary
                if (docInRdt && rdt != null)
                {
                    ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie));
                }

                if (ErrorHandler.Failed(hr))
                {
                    // If this failed then it's probably not a text file.  In that case,
                    // we just read the file as a binary
                    bufferContents = File.ReadAllText(fileName);
                }

            }
            return bufferContents;
        }
        /// <include file='doc\DesignerEditorFactory.uex' path='docs/doc[@for="DesignerEditorFactory.CreateEditorInstance"]/*' />
        /// <devdoc>
        ///     Creates a new editor for the given pile of flags.
        /// </devdoc>
        public virtual int CreateEditorInstance(int vscreateeditorflags, string fileName, string physicalView,
                                                IVsHierarchy hierarchy, int itemid, object existingDocData,
                                                out object docView, out object docData,
                                                out string caption, out Guid cmdUIGuid)
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

            IVsTextStream textStream = null;          // the buffer we will use

            // We support a design view only
            //
            if (physicalView == null || !physicalView.Equals(physicalViewName))
            {
                Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "EditorFactory : Invalid physical view name.");
                throw new COMException("Invalid physical view", NativeMethods.E_NOTIMPL);
            }

            // perform parameter validation and initialization.
            //
            if (((vscreateeditorflags & (__VSCREATEEDITORFLAGS.CEF_OPENFILE | __VSCREATEEDITORFLAGS.CEF_SILENT)) == 0))
            {
                throw new ArgumentException("vscreateeditorflags");
            }

            docView = null;
            docData = null;
            caption = null;

            IVSMDDesignerService ds = (IVSMDDesignerService)serviceProvider.GetService(typeof(IVSMDDesignerService));

            if (ds == null)
            {
                Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "EditorFactory : No designer service.");
                throw new Exception(SR.GetString(SR.EDITORNoDesignerService, fileName));
            }

            // Create our doc data if we don't have an existing one.
            //
            if (existingDocData == null)
            {
                Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "EditorFactory : No existing doc data, creating one.");
                ILocalRegistry localRegistry = (ILocalRegistry)serviceProvider.GetService(typeof(ILocalRegistry));
                Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "\tobtained local registry");

                if (localRegistry == null)
                {
                    Debug.Fail("Shell did not offer local registry, so we can't create a text buffer.");
                    throw new COMException("Unable to create text buffer", NativeMethods.E_FAIL);
                }

                Debug.Assert(!(typeof(VsTextBuffer)).GUID.Equals(Guid.Empty), "EE has munched on text buffer guid.");

                try {
                    Guid guidTemp = typeof(IVsTextStream).GUID;
                    textStream = (IVsTextStream)localRegistry.CreateInstance(typeof(VsTextBuffer).GUID,
                                                                             null,
                                                                             ref guidTemp,
                                                                             NativeMethods.CLSCTX_INPROC_SERVER);
                }
                #if DEBUG
                catch (ExternalException ex) {
                    Guid SID_VsTextBuffer  = typeof(VsTextBuffer).GUID;
                    Guid IID_IVsTextStream = typeof(IVsTextStream).GUID;
                    Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "\tILocalRegistry.CreateInstance(" + SID_VsTextBuffer.ToString() + ", " + IID_IVsTextStream.ToString() + ") failed (hr=" + ex.ErrorCode.ToString() + ")");
                #else
                catch (Exception) {
                #endif
                    throw new COMException("Failed to create text buffer", NativeMethods.E_FAIL);
                }

                Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "\tcreated text buffer");
            }
            else
            {
                Debug.Assert(existingDocData is IVsTextStream, "Existing doc data must implement IVsTextStream");
                textStream = (IVsTextStream)existingDocData;
            }

            // Create and initialize our code stream.
            //
            object loaderObj = ds.CreateDesignerLoader(ds.GetDesignerLoaderClassForFile(fileName));

            // Before we embark on creating the designer, we need to do a quick check
            // to see if this file can be designed.  If it can't be we will fail this
            // editor create, and the shell will go on to the next editor in the list.
            //
            Debug.Assert(loaderObj is DesignerLoader, "loader must inherit from DesignerLoader: " + loaderObj.GetType().FullName);
            Debug.Assert(loaderObj is IVSMDDesignerLoader, "code stream must implement IVSMDDesignerLoader: " + loaderObj.GetType().FullName);
            NativeMethods.IOleServiceProvider oleProvider = (NativeMethods.IOleServiceProvider)serviceProvider.GetService(typeof(NativeMethods.IOleServiceProvider));
            ((IVSMDDesignerLoader)loaderObj).Initialize(oleProvider, hierarchy, itemid, textStream);

            DesignerLoader loader = (DesignerLoader)loaderObj;

            if (existingDocData == null)
            {
                if (textStream is NativeMethods.IObjectWithSite)
                {
                    ((NativeMethods.IObjectWithSite)textStream).SetSite(site);
                    Debug.WriteLineIf(Switches.TRACEEDIT.TraceVerbose, "\tsited text buffer");
                }
            }

            // Now slam the two together and make a designer
            //
            IVSMDDesigner designer = ds.CreateDesigner(oleProvider, loader);
            Debug.Assert(designer != null, "Designer service should have thrown if it had a problem.");

            // Now ask for the view and setup our out-parameters
            //
            int attrs = NativeMethods.GetFileAttributes(fileName);
            if ((attrs & NativeMethods.FILE_ATTRIBUTE_READONLY) != 0)
            {
                attrs = _READONLYSTATUS.ROSTATUS_ReadOnly;
            }
            else
            {
                attrs = _READONLYSTATUS.ROSTATUS_NotReadOnly;
            }

            docView   = designer.View;
            docData   = textStream;
            caption   = ((IVSMDDesignerLoader)loaderObj).GetEditorCaption(attrs);
            cmdUIGuid = designer.CommandGuid;

            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;

            return(0);
        }
Пример #9
0
 public int GetStreamBuffer(out IVsTextStream ppBuffer) {
     ppBuffer = _buffer;
     return VSConstants.S_OK;
 }
Пример #10
0
 public VsTextStreamMarker(IVsTextStream buffer, int start, int length) {
     _buffer = buffer;
     _start = start;
     _length = length;
 }
Пример #11
0
        private void ProcessFile(string filePath)
        {
            IVsTextBuffer      textBuffer        = null;
            IPersistFileFormat textBufferPersist = null;
            IVsTextStream      textStream        = null;
            IVsUserData        userData          = null;
            IServiceProvider   serviceProvider   = (IServiceProvider)GetService(typeof(IServiceProvider));

            using (DocData docData = new DocData(serviceProvider, filePath))
                try
                {
                    textBuffer = docData.Buffer;
                    userData   = (IVsUserData)textBuffer;
                    Guid VsBufferDetectLangSID = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}");
                    Marshal.ThrowExceptionForHR(userData.SetData(ref VsBufferDetectLangSID, false));
                    textBufferPersist = (IPersistFileFormat)textBuffer;
                    textStream        = (IVsTextStream)textBuffer;
                    int fileLenBeforeReplacement = 0;
                    Marshal.ThrowExceptionForHR(textStream.GetSize(out fileLenBeforeReplacement));
                    IntPtr buffer = IntPtr.Zero;
                    try
                    {
                        buffer = Marshal.StringToCoTaskMemUni(this.Content);
                        Marshal.ThrowExceptionForHR(textStream.ReloadStream(0, fileLenBeforeReplacement, buffer, Content.Length));
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(buffer);
                        buffer = IntPtr.Zero;
                    }

                    // Get the original encoding as Texteditor detected it.
                    // The Unicode lib packs codePage in the low word and flags (as emmit BOM) in high word.
                    object encObj = null;
                    Guid   VsBufferEncodingVSTFF = new Guid("{16417F39-A6B7-4c90-89FA-770D2C60440B}");
                    Marshal.ThrowExceptionForHR(userData.GetData(ref VsBufferEncodingVSTFF, out encObj));
                    uint encValue = (uint)encObj;
                    // set the desired encoding
                    encValue = 65001 | 0x10000;
                    Marshal.ThrowExceptionForHR(userData.SetData(ref VsBufferEncodingVSTFF, encValue));
                    Marshal.ThrowExceptionForHR(textBufferPersist.Save(filePath, 1, 0));
                    Marshal.ThrowExceptionForHR(textBufferPersist.SaveCompleted(filePath));
                }
                finally
                {
                    //if (userData != null)
                    //{
                    //    Marshal.ReleaseComObject(userData);
                    //}
                    //if (textStream != null)
                    //{
                    //    Marshal.ReleaseComObject(textStream);
                    //}
                    //if (textBufferPersist != null)
                    //{
                    //    Marshal.ReleaseComObject(textBufferPersist);
                    //}
                    //if (textBuffer != null)
                    //{
                    //    Marshal.ReleaseComObject(textBuffer);
                    //}
                }
        }
Пример #12
0
        public void GotoLocation(Location loc, string caption, bool asReadonly)
        {
            //TODO: VladD2: Разобраться почему этот код вызывает вылет
            //IVsUIShell uiShell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
            //if (uiShell != null)
            //{
            //  IVsWindowFrame frame;
            //  string data;
            //  object unknown;
            //  ErrorHandler.ThrowOnFailure(uiShell.GetCurrentBFNavigationItem(out frame, out data, out unknown));
            //  ErrorHandler.ThrowOnFailure(uiShell.AddNewBFNavigationItem(frame, data, unknown, 0));
            //}

            TextSpan span = new TextSpan();

            span.iStartLine  = loc.Line - 1;
            span.iStartIndex = loc.Column - 1;
            span.iEndLine    = loc.EndLine - 1;
            span.iEndIndex   = loc.EndColumn - 1;

            uint           itemID;
            IVsUIHierarchy hierarchy;
            IVsWindowFrame docFrame;
            IVsTextView    textView;

            if (loc.FileIndex == 0)
            {
                return;
            }

            VsShell.OpenDocument(Site, loc.File, VSConstants.LOGVIEWID_Code,
                                 out hierarchy, out itemID, out docFrame, out textView);

            if (asReadonly)
            {
                IVsTextLines buffer;
                ErrorHandler.ThrowOnFailure(textView.GetBuffer(out buffer));
                IVsTextStream stream = (IVsTextStream)buffer;
                stream.SetStateFlags((uint)BUFFERSTATEFLAGS.BSF_USER_READONLY);
            }

            if (caption != null)
            {
                ErrorHandler.ThrowOnFailure(docFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption));
            }

            ErrorHandler.ThrowOnFailure(docFrame.Show());

            if (textView != null && loc.Line != 0)
            {
                try
                {
                    ErrorHandler.ThrowOnFailure(textView.SetCaretPos(span.iStartLine, span.iStartIndex));
                    TextSpanHelper.MakePositive(ref span);
                    ErrorHandler.ThrowOnFailure(textView.SetSelection(span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex));
                    ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(span));
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex.Message);
                }
            }
        }
Пример #13
0
        private static bool ValidateHash(IVsTextLines textLines, string expectedHash)
        {
            // We can't get the content of the text buffer from an IVsTextLines instance.
            // We need an IVsTextStream instance instead.
            IVsTextStream textStream = textLines as IVsTextStream;

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

            // Before retrieving the content we need to allocate a buffer that is big
            // enough to hold all the text. So query the text buffer for the content
            // length first.
            int length;
            int hr = textStream.GetSize(out length);

            if (ErrorHandler.Failed(hr))
            {
                return(false);
            }

            // Allocate a native OLE buffer for the text and the trailing termination
            // character. Don't forget to always free it!
            string text;
            int    neededNativeBufferSize = (length + 1) * Marshal.SystemDefaultCharSize;
            IntPtr nativeBuffer           = Marshal.AllocCoTaskMem(neededNativeBufferSize);

            try
            {
                // Get the content of the text buffer.
                hr = textStream.GetStream(0, length, nativeBuffer);
                if (ErrorHandler.Failed(hr))
                {
                    return(false);
                }

                // Marshal the text from the unmanaged OLE memory region to a .NET
                // string object.
                text = Marshal.PtrToStringAuto(nativeBuffer);
            }
            finally
            {
                if (nativeBuffer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(nativeBuffer);
                }
            }

            // Now compute the hash of the text in the buffer. If it equals the expected
            // hash we're successful.
            byte[] content = Encoding.Default.GetBytes(text);
            string hash1   = GetHash(content);

            if (String.Compare(expectedHash, hash1, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(true);
            }

            // The Unicode Byte-Order Mark is interpreted correctly by the text editor.
            // However it does not exist in the text buffer (and of course it shouldn't).
            // To be able to open UTF-8 files we add the corresponding BOM to the content.
            byte[] contentWithBom = new byte[content.Length + 3];
            contentWithBom[0] = 0xEF;
            contentWithBom[1] = 0xBB;
            contentWithBom[2] = 0xBF;
            Array.Copy(content, 0, contentWithBom, 3, content.Length);

            // Let's see whether the hash matches a file with UTF-8 BOM.
            string hash2 = GetHash(contentWithBom);

            return(String.Compare(expectedHash, hash2, StringComparison.OrdinalIgnoreCase) == 0);
        }
Пример #14
0
 public int GetStreamBuffer(out IVsTextStream ppBuffer)
 {
     ppBuffer = _buffer;
     return(VSConstants.S_OK);
 }
Пример #15
0
 public VsTextStreamMarker(IVsTextStream buffer, int start, int length)
 {
     _buffer = buffer;
     _start  = start;
     _length = length;
 }