Exemple #1
0
 /// <include file='doc\ServiceProvider.uex' path='docs/doc[@for="ServiceProvider.ServiceProvider1"]' />
 /// <devdoc>
 ///     Creates a new ServiceProvider object and uses the given interface to resolve
 ///     services.  If defaultServices is true (the default) this service  provider will
 ///     respond to Microsoft.VisualStudio.OLE.Interop.IServiceProvider and IObjectWithSite
 ///     as services.  A query for Microsoft.VisualStudio.OLE.Interop.IServiceProvider will
 ///     return the underlying COM service provider and a query for IObjectWithSite will
 ///     return this object.  If false is passed into defaultServices these two services
 ///     will not be provided and the service provider will be "transparent".
 /// </devdoc>
 public ServiceProvider(IOleServiceProvider sp, bool defaultServices) {
     if (sp == null) {
         throw new ArgumentNullException("sp");
     }
     this.serviceProvider = sp;
     this.defaultServices = defaultServices;
 }
 //==========================================================================================
 // Methods
 //==========================================================================================
 public void Dispose()
 {
     if (this.oleServiceProvider != null)
     {
         this.oleServiceProvider = null;
     }
 }
        public CogaenEditProject(Package pkg, IOleServiceProvider site, MSBuild.Project buildProject)
        {
            this.package = pkg;
            SetSite(site);
            this.BuildProject = buildProject;
            this.CanFileNodesHaveChilds = true;
            this.OleServiceProvider.AddService(typeof(VSLangProj.VSProject), new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false);
            this.SupportsProjectDesigner = true;

            //Store the number of images in ProjectNode so we know the offset of the python icons.
            ImageOffset = this.ImageHandler.ImageList.Images.Count;
            foreach (Image img in CogaenEditImageList.Images)
            {
                this.ImageHandler.AddImage(img);
            }

            InitializeCATIDs();
        }
Exemple #4
0
        public void ResetDisplay(IOleServiceProvider oleServiceProvider)
        {
            var serviceProvider = oleServiceProvider.GetServiceProvider();
            var vsEditorAdaptersFactoryService = serviceProvider.GetExportedValue<IVsEditorAdaptersFactoryService>();
            var editorFactory = serviceProvider.GetExportedValue<IEditorFactory>();

            // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
            // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
            // the object returned by the Content property.
            var vsTextBuffer = vsEditorAdaptersFactoryService.CreateVsTextBufferAdapter(oleServiceProvider);

            // Set the content type
            var contentTypeKey = new Guid(0x1beb4195, 0x98f4, 0x4589, 0x80, 0xe0, 0x48, 12, 0xe3, 0x2f, 240, 0x59);
            var vsUserData = (IVsUserData)vsTextBuffer;
            vsUserData.SetData(ref contentTypeKey, "text");

            vsTextBuffer.InitializeContent("", 0);
            var textBuffer = vsEditorAdaptersFactoryService.GetDataBuffer(vsTextBuffer);

            var vsTextView = editorFactory.CreateVsTextView(
                vsTextBuffer,
                PredefinedTextViewRoles.Interactive,
                PredefinedTextViewRoles.Editable,
                PredefinedTextViewRoles.Document,
                PredefinedTextViewRoles.PrimaryDocument);

            var wpfTextViewHost = vsEditorAdaptersFactoryService.GetWpfTextViewHost(vsTextView);
            _editorControl.TextViewControl = wpfTextViewHost.HostControl;

            /*
            var oleCommandTarget = vsTextBuffer as IOleCommandTarget;
            if (oleCommandTarget != null)
            {
                ToolBarCommandTarget = oleCommandTarget;
            }
            */
        }
Exemple #5
0
        public virtual void SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site)
        {
            this.site          = new ServiceProvider(site);
            this.editorFactory = CreateEditorFactory();
            if (this.editorFactory != null)
            {
                this.editorFactory.SetSite(site);
                Guid editorGuid        = this.editorFactory.GetType().GUID;
                IVsRegisterEditors vre = (IVsRegisterEditors)this.site.QueryService(VsConstants.SID_SVsRegisterEditors, typeof(IVsRegisterEditors));
                vre.RegisterEditor(ref editorGuid, editorFactory, out this.editorFactoryCookie);
            }

            this.projectFactory = CreateProjectFactory();
            if (this.projectFactory != null)
            {
                this.projectFactory.SetSite(site);
                IVsRegisterProjectTypes rpt = (IVsRegisterProjectTypes)this.site.QueryService(VsConstants.SID_IVsRegisterProjectTypes, typeof(IVsRegisterProjectTypes));
                if (rpt != null)
                {
                    Guid projectType = this.projectFactory.GetType().GUID;
                    rpt.RegisterProjectType(ref projectType, this.projectFactory, out this.projectFactoryCookie);
                }
            }

            uint lcid = VsShell.GetProviderLocale(this.site);

            languageServices = new Hashtable();
            string          thisPackage = "{" + this.GetType().GUID.ToString() + "}";
            ServiceProvider thisSite    = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider) this);

            ILocalRegistry3 localRegistry = (ILocalRegistry3)this.site.QueryService(VsConstants.SID_SLocalRegistry, typeof(ILocalRegistry3));
            string          root          = null;

            if (localRegistry != null)
            {
                localRegistry.GetLocalRegistryRoot(out root);
            }
            using (RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(root)) {
                if (rootKey != null)
                {
                    using (RegistryKey languages = rootKey.OpenSubKey("Languages\\Language Services")) {
                        if (languages != null)
                        {
                            foreach (string languageName in languages.GetSubKeyNames())
                            {
                                using (RegistryKey langKey = languages.OpenSubKey(languageName)) {
                                    object pkg = langKey.GetValue("Package");
                                    if (pkg is string && string.Compare((string)pkg, thisPackage, false) == 0)
                                    {
                                        object guid = langKey.GetValue(null);
                                        if (guid is string)
                                        {
                                            Guid langGuid = new Guid((string)guid);
                                            if (!this.languageServices.Contains(langGuid.ToString()))
                                            {
                                                ILanguageService svc = CreateLanguageService(ref langGuid);
                                                if (svc != null)
                                                {
                                                    svc.Init(thisSite, ref langGuid, lcid, GetFileExtensions(rootKey, (string)guid));
                                                    this.languageServices.Add(langGuid.ToString(), svc);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //register with ComponentManager for Idle processing
            this.componentManager = (IOleComponentManager)this.site.QueryService(VsConstants.SID_SOleComponentManager, typeof(IOleComponentManager));
            if (componentID == 0)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)OLECRF.olecrfNeedIdleTime |
                                   (uint)OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)OLECADVF.olecadvfModal |
                                     (uint)OLECADVF.olecadvfRedrawOff |
                                     (uint)OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;
                this.componentManager.FRegisterComponent(this, crinfo, out componentID);
            }
        }
 public virtual int SetSite(IOleServiceProvider psp)
 {
     _serviceProvider = new ServiceProvider(psp);
     return VSConstants.S_OK;
 }
Exemple #7
0
 int IVsHierarchy.SetSite(IOleServiceProvider psp)
 {
     return ((IVsUIHierarchy)this).SetSite(psp);
 }
 public SiteServiceProvider(VsProject project, IOleServiceProvider spInner)
 {
     m_project = project;
     m_spInner = spInner;
 }
Exemple #9
0
        /// <include file='doc\Package.uex' path='docs/doc[@for="Package.IVsPackage.SetSite"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// IVsPackage implementation.
        /// </devdoc>
        int IVsPackage.SetSite(IOleServiceProvider sp) {

            if (zombie)
                Marshal.ThrowExceptionForHR(NativeMethods.E_UNEXPECTED);

            if (sp != null) {
                if (_provider != null) {
                    throw new InvalidOperationException(SR.GetString(SR.Package_SiteAlreadySet, GetType().FullName));
                }
                _provider = new ServiceProvider(sp);
                // Initialize the static service provider
                if (_globalProvider == null)
                    _globalProvider = _provider;
                // Increment the number of package that have been sited.
                // This allows us to know when to let go of our _globalProvider
                ++_sitedPackageCount;
                Initialize();
            }
            else if (_provider != null)
            {
                // No SP, dispose us.
                //
                Dispose(true);

                // Decrement the number of package that have been sited.
                --_sitedPackageCount;
                // Dispose of our  _globalProvider once all packages have been unsited
                if (_sitedPackageCount <= 0 && _globalProvider != null)
                {
                    Debug.Assert(_sitedPackageCount == 0, "We should not have unsited more package then we sited");
                    _globalProvider.Dispose();
                    _globalProvider = null;
                }
            }
            return NativeMethods.S_OK;
        }
Exemple #10
0
 public static InterfaceType CreateSitedInstance <InterfaceType>(IOleServiceProvider serviceProvider, Guid clsid) where InterfaceType : class
 {
     return(CreateSitedInstance <InterfaceType>(new ServiceProvider(serviceProvider), clsid));
 }
Exemple #11
0
 int IVsHierarchy.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider)
 {
     this.serviceProvider = (System.IServiceProvider) new ServiceProvider(serviceProvider);
     NativeMethods.ThrowOnFailure(innerVsHierarchy.SetSite(serviceProvider));
     return(NativeMethods.S_OK);
 }
Exemple #12
0
 public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) {
   _site = site;
   return 0;
 }
Exemple #13
0
 public SQLEditor(IOleServiceProvider sp)
     : this()
 {
     _vsServiceProvider = sp;
 }
Exemple #14
0
        public int SetSite(IOleServiceProvider psp)
        {
            _vsServiceProvider = psp;

            int hr = editorFrame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref GuidList.guidCmdUI_TextEditor);

            return VSConstants.S_OK;
        }
Exemple #15
0
        /// <summary>
        /// Initializes the VSPackage with a back pointer to the environment. This is the entry point
        /// for the Visual Studio package.
        /// </summary>
        /// <param name="sp">
        /// Pointer to the <see cref="IOleServiceProvider"/> interface through which the
        /// VSPackage can query for services.
        /// </param>
        /// <returns>An HRESULT indicating the result of the call.</returns>
        int IVsPackage.SetSite(IOleServiceProvider sp)
        {
            if (this.Closed)
            {
                Tracer.Fail("We shouldn't have been called if we're being unloaded.");
                return NativeMethods.E_UNEXPECTED;
            }

            try
            {
                if (sp != null)
                {
                    // If SetSite has been called more than once, it's an error.
                    if (this.Context != null)
                    {
                        string message = this.Context.NativeResources.GetString(ResId.IDS_E_SITEALREADYSET, this.GetType().FullName);
                        Tracer.Fail(message);
                        throw new InvalidOperationException(message);
                    }

                    // Initialize the ServiceProvider and ourself.
                    ServiceProvider contextServiceProvider = new ServiceProvider(sp);
                    this.context = this.CreatePackageContext(contextServiceProvider);
                    Tracer.Initialize(this.context);
                    this.Initialize();
                }
                else if (this.Context != null && this.Context.ServiceProvider != null)
                {
                    this.Dispose(true);
                }
            }
            catch (Exception e)
            {
                Tracer.Fail("Unexpected exception: {0}\n{1}", e.Message, e);
                throw;
            }

            return NativeMethods.S_OK;
        }
            public ContextServiceProvider( VsProject project, IOleServiceProvider spInner )
            {
                m_project = project;
                m_spInner = spInner;
                m_boInner = spInner as IVsBrowseObject;

                Debug.Assert( m_boInner != null );
            }
 int IVsHierarchy.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
     throw new NotImplementedException();
 }
Exemple #18
0
        // ----------------------------------------------------------------------------------
        /// <summary>
        /// Initialize the editor
        /// </summary>
        // ----------------------------------------------------------------------------------
        private void InitializeEditor()
        {
            const string message = "";

            var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(
              typeof(SComponentModel));
            _OleServiceProvider = (IServiceProvider)GetService(typeof(IServiceProvider));
            _BufferFactory = componentModel.GetService<ITextBufferFactoryService>();

            _EditorAdapterFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>();
            _BufferAdapter = _EditorAdapterFactory.CreateVsTextBufferAdapter(_OleServiceProvider,
                                                                             _BufferFactory.TextContentType);
            _BufferAdapter.InitializeContent(message, message.Length);

            _ViewAdapter = _EditorAdapterFactory.CreateVsTextViewAdapter(_OleServiceProvider);
            ((IVsWindowPane)_ViewAdapter).SetSite(_OleServiceProvider);

            var initView = new[] { new INITVIEW() };
            initView[0].fSelectionMargin = 0; // original: 0
            initView[0].fWidgetMargin = 0; // original: 0
            initView[0].fVirtualSpace = 0;
            initView[0].fDragDropMove = 1;
            initView[0].fVirtualSpace = 0;

            _ViewAdapter.Initialize(_BufferAdapter as IVsTextLines, IntPtr.Zero,
              (uint)TextViewInitFlags.VIF_HSCROLL |
              (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT, initView);
        }
 public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) {
     _serviceProvider = new ServiceProvider(psp);
     return VSConstants.S_OK;
 }
Exemple #20
0
 public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) // Used for initialization of the editor in the environment. "psp" is a pointer to the service provider. Can be used to obtain instances of other interfaces.
 {
     vsServiceProvider = new ServiceProvider(psp);
     return(VSConstants.S_OK);
 }
Exemple #21
0
 int IVsUIHierarchy.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
     return(((IVsHierarchy)this).SetSite(psp));
 }
Exemple #22
0
        public int CreateEditorInstance(
            uint grfCreateDoc,                 // Flags determining when to create the editor. Only open and silent flags are valid
            string pszMkDocument,              // path to the file to be opened
            string pszPhysicalView,            // name of the physical view
            IVsHierarchy pvHier,               // pointer to the IVsHierarchy interface
            uint itemid,                       // Item identifier of this editor instance
            System.IntPtr punkDocDataExisting, // This parameter is used to determine if a document buffer (DocData object) has already been created
            out System.IntPtr ppunkDocView,    // Pointer to the IUnknown interface for the DocView object
            out System.IntPtr ppunkDocData,    // Pointer to the IUnknown interface for the DocData object
            out string pbstrEditorCaption,     // Caption mentioned by the editor for the doc window
            out Guid pguidCmdUI,               // the Command UI Guid. Any UI element that is visible in the editor has to use this GUID. This is specified in the .vsct file.
            out int pgrfCDW)                   // Flags for CreateDocumentWindow
        {
            // Initialize to null:
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = GuidList.guidEditorFactory;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

            // Quit if the project is not of type "C#/XAML for HTML5":
            bool isCSharpXamlForHtml5 = IsCSharpXamlForHtml5(pszMkDocument);

            if (!isCSharpXamlForHtml5)
            {
                return(VSConstants.VS_E_UNSUPPORTEDFORMAT);
            }

            // Validate inputs:
            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }


            //TEST:
            if (punkDocDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            IVsTextLines textBuffer = null;

            // punkDocDataExisting is null which means the file is not yet open. We need to create a new text buffer object

            // Get the ILocalRegistry interface so we can use it to create the text buffer from the shell's local registry:
            try
            {
                ILocalRegistry localRegistry = (ILocalRegistry)GetService(typeof(SLocalRegistry));
                if (localRegistry != null)
                {
                    IntPtr ptr;
                    Guid   iid = typeof(IVsTextLines).GUID;
                    Guid   CLSID_VsTextBuffer = typeof(VsTextBufferClass).GUID;
                    localRegistry.CreateInstance(CLSID_VsTextBuffer, null, ref iid, 1, out ptr);
                    try
                    {
                        textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
                    }
                    finally
                    {
                        Marshal.Release(ptr); // Release RefCount from CreateInstance call
                    }

                    IObjectWithSite objWSite = (IObjectWithSite)textBuffer; // It is important to site the TextBuffer object
                    if (objWSite != null)
                    {
                        Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider));
                        objWSite.SetSite(oleServiceProvider);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Can not get IVsCfgProviderEventsHelper" + ex.Message);
                throw;
            }

            ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);

            var editorControl = new EditorPane(textBuffer, pszMkDocument, pvHier, itemid, pszPhysicalView, ppunkDocData, vsServiceProvider);

            ppunkDocView = Marshal.GetIUnknownForObject(editorControl);

            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
 public int SetSite(IServiceProvider psp)
 {
     _oleServiceProvider = psp;
     _serviceProvider    = new ServiceProvider(psp);
     return(VSConstants.S_OK);
 }
 /// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.IVsUIElementPane.SetUIElementSite"]/*' />
 /// <internalonly/>
 /// <devdoc>
 /// IVsUIElementPane implementation.
 /// </devdoc>
 int IVsUIElementPane.SetUIElementSite(IOleServiceProvider p)
 {
     // If classes derived from WindowPane explicitly implemented IVsWindowPane, and relied on the explicit implementation of SetSite to be called,
     // we should make sure we call them.  Otherwise, IVsWindowPane.SetSite will call SetSiteInternal in the default implementation.
     return ((IVsWindowPane)this).SetSite(p);
 }
Exemple #25
0
 /// <include file='doc\ServiceProvider.uex' path='docs/doc[@for="ServiceProvider.ServiceProvider"]' />
 /// <devdoc>
 ///     Creates a new ServiceProvider object and uses the given interface to resolve
 ///     services.
 /// </devdoc>
 public ServiceProvider(IOleServiceProvider sp) : this(sp, true){
 }
 int IVsEditorFactory.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
     this.serviceProvider = psp;
     return(VSConstants.S_OK);
 }
Exemple #27
0
        int IVsUIHierarchy.SetSite(IOleServiceProvider psp)
        {
            try
            {
                Tracer.VerifyNonNullArgument(psp, "psp");

                // We don't want to create another service provider if the argument is a pointer
                // to the one currently stored in the PackageContext (we already initialized our
                // pointer to the PackageContext's service provider in the constructor).
                if (!Object.ReferenceEquals(psp, this.serviceProvider))
                {
                    this.serviceProvider = new ServiceProvider(psp);
                }
            }
            catch (Exception e)
            {
                Tracer.Fail("Unexpected exception: {0}\n{1}", e.Message, e);
                throw;
            }

            return NativeMethods.S_OK;
        }
Exemple #28
0
        /// <summary>
        /// Implements the IVsSingleFileGenerator.Generate method.
        /// Executes the transformation and returns the newly generated output file, whenever a custom tool is loaded, or the input file is saved
        /// </summary>
        /// <remarks>
        /// When this is called, the current generator enumerator consists of a list of file extentions that we are going to generate.
        /// </remarks>
        /// <param name="wszInputFilePath">The full path of the input file. May be a null reference (Nothing in Visual Basic) in future releases of Visual Studio, so generators should not rely on this value</param>
        /// <param name="bstrInputFileContents">The contents of the input file. This is either a UNICODE BSTR (if the input file is text) or a binary BSTR (if the input file is binary). If the input file is a text file, the project system automatically converts the BSTR to UNICODE</param>
        /// <param name="wszDefaultNamespace">This parameter is meaningful only for custom tools that generate code. It represents the namespace into which the generated code will be placed. If the parameter is not a null reference (Nothing in Visual Basic) and not empty, the custom tool can use the following syntax to enclose the generated code</param>
        /// <param name="rgbOutputFileContents">[out] Returns an array of bytes to be written to the generated file. You must include UNICODE or UTF-8 signature bytes in the returned byte array, as this is a raw stream. The memory for rgbOutputFileContents must be allocated using the .NET Framework call, System.Runtime.InteropServices.AllocCoTaskMem, or the equivalent Win32 system call, CoTaskMemAlloc. The project system is responsible for freeing this memory</param>
        /// <param name="pcbOutput">[out] Returns the count of bytes in the rgbOutputFileContent array</param>
        /// <param name="pGenerateProgress">A reference to the IVsGeneratorProgress interface through which the generator can report its progress to the project system</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns E_FAIL</returns>
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput,
                            IVsGeneratorProgress pGenerateProgress)
        {
            // TODO: There are a number of nested try catch blocks that should be cleaned up.
            // Make sure exception handling is properly laid out. This function has high
            // complexity (probably too high with cycl over 30), which makes error handling important. What
            // exceptions escape (ie. not handled)? What halts file generation? etc...
            try
            {
                // EnsureActiveProjectSet();

                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "");
                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, string.Format("------ CSD file generation started: Configuration document: {0} ------", InputFilePath));

                Diagnostics.DebugWrite("VsMultipleFileGenerator => VSMFG.");

                ProjectItem configurationSectionModelFile = null;

                _bstrInputFileContents = bstrInputFileContents;
                _wszInputFilePath      = wszInputFilePath;
                _generatorProgress     = pGenerateProgress;
                _oldFileNames.Clear();
                _newFileNames.Clear();

                // Look through all the projects in the solution
                // The _project holds DTE reference, so not needed here.
                //DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
                //Diagnostics.DebugWrite("VSMFG.Generate >> dte.Solution.Projects.Count = {0}.", dte.Solution.Projects.Count);

                VsOutputWindowPaneManager.OutputWindowWrite(vsOutputWindowPaneName, "* Searching for configuration project handle... ");

                Project     project     = null;
                ProjectItem projectItem = null;
                if (!VsHelper.FindProjectContainingFile(InputFilePath, out projectItem, out project))
                {
                    // TODO: Will this fail if NEW diagram is created but not saved? Confirm. I THINK empty diagram is always saved to disk upon creation.
                    throw new ApplicationException("Could not retrieve Visual Studio ProjectItem and/or parent project containing this CSD diagram. Has this diagram been saved yet after being created?");
                }
                _project = project;

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(_project); // ABM - Issue 10435: 2nd WindowsService project results in FAILURE here.
                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
                // TODO: 20140908: Might not be needed due to the new way I locate projectitem and project.
                VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[(int)VSDOCUMENTPRIORITY.DP_Standard];
                int result = vsProject.IsDocumentInProject(InputFilePath, out iFound, prio, out itemId); // ABM - Issue 10435: WindowsService project results in iFound=0!!!

                #region VSITEMID Documentation
                // itemid: Pointer to the item identifier of the document within the project.
                // NOTE: itemId is either a specific id pointing to the file, or is one of VSITEMID enumeration.
                // VSITEMID represents Special items inside a VsHierarchy:

                /*
                 * public enum VSITEMID
                 * {
                 * Selection = 4294967293, // all the currently selected items. // represents the currently selected item or items, which can include the root of the hierarchy.
                 * Root = 4294967294,      // the hierarchy itself. // represents the root of a project hierarchy and is used to identify the entire hierarchy, as opposed to a single item.
                 * Nil = 4294967295,       // no node.// represents the absence of a project item. This value is used when there is no current selection.
                 * }
                 */
                /*
                 * http://visual-studio.todaysummary.com/q_visual-studio_76086.html
                 *
                 * http://msdn.microsoft.com/en-us/subscriptions/downloads/microsoft.visualstudio.shell.interop.ivshierarchy(v=vs.100).aspx
                 * The IVsHierarchy interface is a generic interface to a hierarchy of nodes. Each node, including the root node, can have arbitrary
                 * properties associated with it. Each node on the hierarchy object is identified using a cookie (VSITEMID), which indicates a particular
                 * node. This cookie is invisible to the consumer of IVsHierarchy, and is typically a pointer to some private data maintained by the
                 * hierarchy's implementation.
                 *
                 * A VSITEMID is a DWORD uniquely identifying a node within a hierarchy. Itemids from one IVsHierarchy may not be passed to another hierarchy. Also, note that itemids have a limited lifetime, as indicated by events fired by the hierarchy, so holding on to itemids for long durations will require either the sinking of these events, or the conversion of the itemid into a canonical, persistable form.
                 *
                 * An item in a hierarchy can be a leaf node, a container of other items, or a link into some other hierarchy using GetNestedHierarchy.
                 *
                 * The IVsHierarchy interface is not used only for project hierarchies. For example, the Server Explorer window implements the IVsHierarchy interface to display its hierarchy, which is not a project hierarchy.
                 *
                 * There are times when it is useful to query a hierarchy about various virtual nodes, such as the hierarchy itself or the selected nodes within the hierarchy. Where such virtual nodes are potentially of interest, one of the predefined VSITEMID values may be passed.
                 *
                 * The environment views a project as a hierarchy, that is, a tree of nodes in which the nodes are project items. Each node also has a set of associated properties, and provides hierarchy management for VSPackages that implement project hierarchies.
                 *
                 * Notes to Implementers
                 * Implemented by VSPackages that create their own project hierarchy.
                 *
                 * Notes to Callers
                 * Called by the environment to get and set hierarchy properties.*/

                #endregion

                if (result != VSConstants.S_OK)
                {
                    throw new Exception("Unexpected error calling IVsProject.IsDocumentInProject.");
                }

                Diagnostics.DebugWrite("VH.TFP >> vsProject.IsDocumentInProject(inputFilePath, out iFound={0}, pdwPriority, out itemId={1}).", iFound, itemId);

                // 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.
                        }
                    }
                    else
                    {
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                    }
                }
                else
                {
                    VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "error: Unable to retrieve Visual Studio ProjectItem. File generation halted.");
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem. Try running the tool again.");
                }

                // ABM: Code below was the complex and error prone way to find project/items. Interface exists to easily
                // locate these items. This interface is used to set current project as local variable instead of here.
                /**/
                // [7296] FILE = ~\ConfigurationSectionDesigner\Debugging\Sample.csd.
                if (!VsHelper.TryFindProjectItemAndParentProject(InputFilePath, out _project, out configurationSectionModelFile) || _project == null)
                {
                    VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "error: Unable to retrieve Visual Studio ProjectItem. File generation halted.");
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem. Try running the tool again.");
                }
                /**/
                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "found!");

                // Check out this CSD file. DISABLED: Too much can go wrong the way this generator is currently structured.

                /*if (_project.DTE.SourceControl.IsItemUnderSCC(InputFilePath) && !_project.DTE.SourceControl.IsItemCheckedOut(InputFilePath))
                 * { _project.DTE.SourceControl.CheckOutItem(InputFilePath); } */

                // Check for source control integration for the CSD item and check it out of needed.
                //if (VsHelper.IsItemUnderSourceControl(dte, configurationSectionModelFile))
                if (_project.DTE.SourceControl.IsItemUnderSCC(InputFilePath) &&
                    !_project.DTE.SourceControl.IsItemCheckedOut(InputFilePath))
                {
                    // ABM: For simplicity, we checkout the CSD file and all subitems. All file operations later down the chain will not have a SC issue.
                    // REASON: This generator has a unique design where null generated content means "don't write to file at this step". For cs files,
                    //         the write to file occurs outside of the iteration later on. For diagram, it never happens. All of these conditions
                    //         make selective SC checkout more complicated than the possible performance improvement is worth. Opinions?

                    VsHelper.CheckoutItem(_project.DTE, configurationSectionModelFile);
                }

                #region new

                // Get names of all of the existing files under CSD.
                foreach (ProjectItem childItem in configurationSectionModelFile.ProjectItems)
                {
                    _oldFileNames.Add(childItem.Name);
                }
                #endregion

                // now we can start our work, iterate across all the 'elements' in our source file.
                // Each of these items is a file extension.
                foreach (TIterativeElement item in this)
                {
                    // This try catch only exists for debugging purposes.
                    try
                    {
                        // obtain a name for this target file
                        string fileName = GetFileName(item);
                        Diagnostics.DebugWrite("VSMFG.Generate >> Filename for current element in loop is '{0}'", fileName);

                        // add it to the tracking cache
                        _newFileNames.Add(fileName);

                        // fully qualify the file on the filesystem
                        //string strFile = Path.Combine(wszInputFilePath.Substring(0, wszInputFilePath.LastIndexOf(Path.DirectorySeparatorChar)), fileName);
                        string strFile = Path.Combine(Path.GetDirectoryName(wszInputFilePath), fileName);

                        bool isNewAdded = !_oldFileNames.Contains(fileName);

                        /*
                         * if (!isNewAdded)
                         * {
                         *  if (_project.DTE.SourceControl.IsItemUnderSCC(strFile) && !_project.DTE.SourceControl.IsItemCheckedOut(strFile))
                         *  {
                         *      Diagnostics.DebugWrite("VSMFG.Generate >> Checking file out from source control '{0}'", fileName);
                         *      _project.DTE.SourceControl.CheckOutItem(strFile);
                         *  }
                         * }*/

                        // create the file
                        FileStream fs = null;

                        try
                        {
                            // generate our target file content
                            byte[] data = GenerateContent(item); // NOTE: For .diagram and .cs, this will be null, so those will not be written.

                            // if data is null, it means to ignore the contents of the generated file (no write to file).
                            if (data == null)
                            {
                                continue;
                            }

                            fs = File.Create(strFile);

                            #region Replaced code: Remove later.

                            /*if (!isNewAdded)
                             * {
                             *  // If the (xsd or config) file already exists, only save the data if the generated file is different than the existing file.
                             *  if (!Util.IsDataEqual(File.ReadAllBytes(strFile), data))
                             *  {
                             *      // Check out this file.
                             *      if (_project.DTE.SourceControl.IsItemUnderSCC(strFile) &&
                             *          !_project.DTE.SourceControl.IsItemCheckedOut(strFile))
                             *      {
                             *          Diagnostics.DebugWrite("VSMFG.Generate >> Checking file out from source control '{0}'", fileName);
                             *          _project.DTE.SourceControl.CheckOutItem(strFile);
                             *      }
                             *
                             *      Diagnostics.DebugWrite("VSMFG.Generate >> File data has changed for file '{0}'. Re-using existing file...", strFile);
                             *      fs = File.Open(strFile, FileMode.Truncate);
                             *  }
                             * }
                             * else
                             * {
                             *  // create the file
                             *  fs = File.Create(strFile);
                             * }*/

                            //if (fs != null) // We only write if file is modified or new.
                            //{

                            #endregion

                            VsOutputWindowPaneManager.OutputWindowWrite(vsOutputWindowPaneName, "* Generating the " + item + " file...");

                            // write it out to the stream
                            fs.Write(data, 0, data.Length);
                            fs.Close();
                            OnFileGenerated(strFile, isNewAdded);

                            // add the newly generated file to the solution, as a child of the source file
                            //if (!configurationSectionModelFile.ProjectItems.Cast<ProjectItem>().Any(pi => pi.Name == fileName))
                            if (isNewAdded)
                            {
                                ProjectItem itm = configurationSectionModelFile.ProjectItems.AddFromFile(strFile);

                                /*
                                 * Here you may wish to perform some addition logic such as, setting a custom tool for the target file if it
                                 * is intented to perform its own generation process.
                                 * Or, set the target file as an 'Embedded Resource' so that it is embedded into the final Assembly.
                                 *
                                 * EnvDTE.Property prop = itm.Properties.Item("CustomTool");
                                 * //// set to embedded resource
                                 * itm.Properties.Item("BuildAction").Value = 3;
                                 * if (String.IsNullOrEmpty((string)prop.Value) || !String.Equals((string)prop.Value, typeof(AnotherCustomTool).Name))
                                 * {
                                 *  prop.Value = typeof(AnotherCustomTool).Name;
                                 * }
                                 */
                            }
                            //}
                        }
                        catch (Exception e)
                        {
                            //GeneratorProgress.GeneratorError( false, 0, string.Format( "{0}\n{1}", e.Message, e.StackTrace ), -1, -1 );
                            //GeneratorProgress.GeneratorError(0, 0, string.Format("{0}\n{1}", e.Message, e.StackTrace), 0, 0);

                            if (File.Exists(strFile))
                            {
                                // TODO: ABM - Should we write this error to the file (breaking the build), or just show error and keep old file?
                                File.WriteAllText(strFile, "An exception occured while running the CsdFileGenerator on this file. See the Error List for details. E=" + e);
                            }
                            throw;
                        }
                        finally
                        {
                            if (fs != null)
                            {
                                fs.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // This is here for debugging purposes, as setting a breakpoint here can be very helpful
                        Diagnostics.DebugWrite("VSMFG.Generate >> EXCEPTION: {0}", ex);
                        throw;
                    }
                }

                // perform some clean-up, making sure we delete any old (stale) target-files
                VsOutputWindowPaneManager.OutputWindowWrite(vsOutputWindowPaneName, "* Cleaning up existing files... ");
                foreach (ProjectItem childItem in configurationSectionModelFile.ProjectItems)
                {
                    string next;
                    DefaultExtension(out next);

                    if (!(childItem.Name.EndsWith(next) || _newFileNames.Contains(childItem.Name)))
                    {
                        // then delete it
                        childItem.Delete();
                    }
                }
                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "complete!");

                VsOutputWindowPaneManager.OutputWindowWrite(vsOutputWindowPaneName, "* Generating the class file... ");

                // generate our default content for our 'single' file
                byte[] defaultData = null;
                try
                {
                    // This will call GenerateAllContent(string.Format("{0}-gen", [cs or vb]));
                    defaultData = GenerateDefaultContent();
                }
                catch (Exception ex)
                {
                    Diagnostics.DebugWrite("VSMFG.Generate >> EXCEPTION: {0}", ex);
                    throw;
                    //GeneratorProgress.GeneratorError( false, 0, string.Format( "{0}\n{1}", ex.Message, ex.StackTrace ), -1, -1 );
                    //GeneratorProgress.GeneratorError(0, 0, string.Format("{0}\n{1}", ex.Message, ex.StackTrace), 0, 0);
                }
                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "complete!");

                if (defaultData == null)
                {
                    defaultData = new byte[0];
                }
                // return our default data (code behind file), so that Visual Studio may write it to disk.

                /*
                 * You need to write the bytes of the generated file into this variable. However, you cannot
                 * do it directly (hence the IntPtr[] type) ?instead, you must use the System.Runtime.InteropServices.AllocCoTaskMem
                 * allocator to create the memory and write type bytes in there.
                 */
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(defaultData.Length);

                Marshal.Copy(defaultData, 0, rgbOutputFileContents[0], defaultData.Length);

                // must be set to the number of bytes that we wrote to rgbOutputFileContents.
                pcbOutput = (uint)defaultData.Length;

                //string codefileName = GetFileName(CodeFileExtension);
                //OnFileGenerated(codefileName, isNewAdded);

                VsOutputWindowPaneManager.OutputWindowWriteLine(vsOutputWindowPaneName, "========== CSD file generation: complete! ==========");
            }
            catch (Exception ex)
            {
                // Currently, all exceptions are rethrown to be caught here.
                OnError(ex);

                LogException(ex);

                rgbOutputFileContents[0] = IntPtr.Zero;
                pcbOutput = 0;
            }

            return(0);
        }
Exemple #29
0
 public int SetSite(IOleServiceProvider psp)
 {
     _oleServiceProvider = psp;
     _serviceProvider = new ServiceProvider(psp);
     return VSConstants.S_OK;
 }
Exemple #30
0
 public TextBufferEditor(System.IServiceProvider sp)
 {
     psp = sp as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
     noContent = true;
     CreateCodeEditor();
 }
 int IVsUIShell.CreateToolWindow(uint grfCTW, uint dwToolWindowId, object punkTool, ref Guid rclsidTool, ref Guid rguidPersistenceSlot, ref Guid rguidAutoActivate, Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp, string pszCaption, int[] pfDefaultPosition, out IVsWindowFrame ppWindowFrame)
 {
     throw new NotImplementedException();
 }
Exemple #32
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            Debug.Assert(rgbOutputFileContents.Length == 1);
            this._inputFileContents = bstrInputFileContents;
            this._inputFilePath     = wszInputFilePath;
            this._defaultNamespace  = wszDefaultNamespace;
            this._newFileNames.Clear();

            int  iFound = 0;
            uint itemId = 0;

            EnvDTE.ProjectItem item;
            Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[] pdwPriority = new Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[1];

            // obtain a reference to the current project as an IVsProject type
            Microsoft.VisualStudio.Shell.Interop.IVsProject VsProject = VsHelper.ToVsProject(_project);
            // this locates, and returns a handle to our source file, as a ProjectItem
            VsProject.IsDocumentInProject(InputFilePath, out iFound, pdwPriority, out itemId);


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

            // now we can start our work, iterate across all the 'elements' in our source file
            foreach (IterativeElementType element in this)
            {
                try {
                    // obtain a name for this target file
                    string fileName = GetFileName(element);
                    // add it to the tracking cache
                    _newFileNames.Add(fileName);
                    // fully qualify the file on the filesystem
                    string strFile = Path.Combine(wszInputFilePath.Substring(0, wszInputFilePath.LastIndexOf(Path.DirectorySeparatorChar)), fileName);
                    // create the file
                    FileStream fs = File.Create(strFile);

                    try
                    {
                        // generate our target file content
                        byte[] data = GenerateContent(element);

                        // write it out to the stream
                        fs.Write(data, 0, data.Length);

                        fs.Close();

                        // add the newly generated file to the solution, as a child of the source file...
                        EnvDTE.ProjectItem itm = item.ProjectItems.AddFromFile(strFile);

                        /*
                         * Here you may wish to perform some addition logic
                         * such as, setting a custom tool for the target file if it
                         * is intented to perform its own generation process.
                         * Or, set the target file as an 'Embedded Resource' so that
                         * it is embedded into the final Assembly.
                         *
                         * EnvDTE.Property prop = itm.Properties.Item("CustomTool");
                         * //// set to embedded resource
                         * itm.Properties.Item("BuildAction").Value = 3;
                         * if (String.IsNullOrEmpty((string)prop.Value) || !String.Equals((string)prop.Value, typeof(AnotherCustomTool).Name))
                         * {
                         *  prop.Value = typeof(AnotherCustomTool).Name;
                         * }
                         */
                    }
                    catch (Exception)
                    {
                        fs.Close();
                        if (File.Exists(strFile))
                        {
                            File.Delete(strFile);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            // perform some clean-up, making sure we delete any old (stale) target-files
            foreach (EnvDTE.ProjectItem childItem in item.ProjectItems)
            {
                if (!(childItem.Name.EndsWith(GetDefaultExtension()) || _newFileNames.Contains(childItem.Name)))
                {
                    // then delete it
                    childItem.Delete();
                }
            }

            // generate our summary content for our 'single' file
            byte[] summaryData = GenerateSummaryContent();

            if (summaryData == null)
            {
                rgbOutputFileContents[0] = IntPtr.Zero;

                pcbOutput = 0;
            }
            else
            {
                // return our summary data, so that Visual Studio may write it to disk.
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(summaryData.Length);

                Marshal.Copy(summaryData, 0, rgbOutputFileContents[0], summaryData.Length);

                pcbOutput = (uint)summaryData.Length;
            }
            return(VSConstants.S_OK);
        }
Exemple #33
0
        int IVsProjectFactory.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider)
        {
            this.Initialize();

            return(VSConstants.S_OK);
        }
Exemple #34
0
 int IVsEditorFactory.SetSite(IOleServiceProvider psp)
 {
     this.serviceProvider = psp;
     return VSConstants.S_OK;
 }
 int IVsUIHierarchy.GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider ppSP)
 {
     throw new NotImplementedException();
 }
Exemple #36
0
 public SQLEditor(IOleServiceProvider sp)
     : this()
 {
     _vsServiceProvider = sp;
 }
Exemple #37
0
 int IVsHierarchy.GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider)
 {
     serviceProvider = this.GetSite();
     return(NativeMethods.S_OK);
 }
 int IVsHierarchy.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider)
 {
     this.serviceProvider = (System.IServiceProvider) new ServiceProvider(serviceProvider);
     ErrorHandler.ThrowOnFailure(_innerVsHierarchy.SetSite(serviceProvider));
     return(VSConstants.S_OK);
 }
Exemple #39
0
 int IVsUIHierarchy.GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider ppSP)
 {
     return(((IVsHierarchy)this).GetSite(out ppSP));
 }
 public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider pSP)
 {
     return(VSConstants.E_NOTIMPL);
 }
Exemple #41
0
 public virtual int SetSite(IVsServiceProvider psp)
 {
     VsServiceProvider = psp;
     return(VSConstants.S_OK);
 }
 public virtual int SetSite(IOleServiceProvider serviceProvider)
 {
     _ServiceProvider = new ServiceProvider(serviceProvider);
     return(VSConstants.S_OK);
 }
Exemple #43
0
 internal MyServiceProvider(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
     _psp = psp;
 }
        private int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
        {
            windowFrame = null;
            if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed)
            {
                return(VSConstants.E_FAIL);
            }

            Debug.Assert(this.Node != null, "No node has been initialized for the document manager");
            Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager");
            Debug.Assert(this.Node is FileNode, "Node is not FileNode object");

            int    returnValue = VSConstants.S_OK;
            string caption     = this.GetOwnerCaption();
            string fullPath    = this.GetFullPathForDocument();

            // Make sure that the file is on disk before we open the editor and display message if not found
            if (!((FileNode)this.Node).IsFileOnDisk(true))
            {
                // Bail since we are not able to open the item
                // Do not return an error code otherwise an internal error message is shown. The scenario for this operation
                // normally is already a reaction to a dialog box telling that the item has been removed.
                return(VSConstants.S_FALSE);
            }

            IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
            IOleServiceProvider    serviceProvider     = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;

            try
            {
                this.Node.ProjectMgr.OnOpenItem(fullPath);
                int result = VSConstants.E_FAIL;

                if (openWith)
                {
                    result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                }
                else
                {
                    __VSOSEFLAGS openFlags = 0;
                    if (newFile)
                    {
                        openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile;
                    }

                    //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid
                    // of the node being opened, otherwise the debugger doesn't work.
                    if (editorType != Guid.Empty)
                    {
                        result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                    }
                    else
                    {
                        openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor;
                        result     = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                    }
                }

                if (result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    return(result);
                }

                if (windowFrame != null)
                {
                    object var;

                    if (newFile)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var));
                        IVsPersistDocData persistDocData = (IVsPersistDocData)var;
                        ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath));
                    }

                    var = null;
                    ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var));
                    this.Node.DocCookie = (uint)(int)var;

                    if (windowFrameAction == WindowFrameShowAction.Show)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.Show());
                    }
                    else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate());
                    }
                    else if (windowFrameAction == WindowFrameShowAction.Hide)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.Hide());
                    }
                }
            }
            catch (COMException e)
            {
                Trace.WriteLine("Exception e:" + e.Message);
                returnValue = e.ErrorCode;
                this.CloseWindowFrame(ref windowFrame);
            }

            return(returnValue);
        }
Exemple #45
0
        public CodeEditorWindow(IAnkhServiceProvider context, Control container)
            : base(context)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            _container = container;
            _serviceProvider = context.GetService<IOleServiceProvider>();
        }
Exemple #46
0
 /// <include file='doc\ServiceProvider.uex' path='docs/doc[@for="ServiceProvider.Dispose"]' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public void Dispose() {
     if (serviceProvider != null) {
         serviceProvider = null;
     }
 }
Exemple #47
0
 /// <include file='doc\ServiceProvider.uex' path='docs/doc[@for="ServiceProvider.IObjectWithSite.SetSite"]/*' />
 /// <internalonly/>
 /// <devdoc>
 /// Sets the site object we will be using to resolve services.
 /// </devdoc>
 void IObjectWithSite.SetSite(object pUnkSite) {
     if (pUnkSite is IOleServiceProvider) {
         serviceProvider = (IOleServiceProvider)pUnkSite;
     }
 }
 internal MyServiceProvider(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
   _psp = psp;
 }
 public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
 {
     vsServiceProvider = psp;
     return(VSConstants.S_OK);
 }
Exemple #50
0
        /// <include file='doc\Package.uex' path='docs/doc[@for="Package.IVsPackage.SetSite"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// IVsPackage implementation.
        /// </devdoc>
        int IVsPackage.SetSite(IOleServiceProvider sp)
        {
            if (zombie)
                Marshal.ThrowExceptionForHR(NativeMethods.E_UNEXPECTED);

            if (sp != null) {
                if (_provider != null) {
                    throw new InvalidOperationException(string.Format(Resources.Culture, Resources.Package_SiteAlreadySet, GetType().FullName));
                }
                _provider = ServiceProvider.CreateFromSetSite(sp);

                Initialize();
            }
            else if (_provider != null)
            {
                // No SP, dispose us.
                //
                Dispose(true);
            }
            return NativeMethods.S_OK;
        }
Exemple #51
0
        public IServiceProvider GetOrUpdateServiceProvider(ITextBuffer buffer)
        {
            if (ServiceProvider != null)
            {
                return ServiceProvider;
            }

            var vsTextLines = _adaptersFactory.GetBufferAdapter(buffer) as IVsTextLines;
            if (vsTextLines == null)
            {
                return null;
            }

            var objectWithSite = vsTextLines as IObjectWithSite;
            if (objectWithSite == null)
            {
                return null;
            }

            ServiceProvider = objectWithSite.GetServiceProvider();
            MaybeUpdateVimHostServiceProvider();
            return ServiceProvider;
        }
        //==========================================================================================
        // Constructors
        //==========================================================================================

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceProvider"/> class.
        /// </summary>
        public ServiceProvider(IOleServiceProvider oleServiceProvider)
        {
            Tracer.VerifyNonNullArgument(oleServiceProvider, "oleServiceProvider");
            this.oleServiceProvider = oleServiceProvider;
        }
Exemple #53
0
 int IVsUIHierarchy.GetSite(out IOleServiceProvider ppSP)
 {
     ppSP = this.serviceProvider.OleServiceProvider;
     return NativeMethods.S_OK;
 }
Exemple #54
0
 public int GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider site)
 {
     _logger.LogHierarchy("GetSite()");
     site = _site;
     return(0);
 }
Exemple #55
0
 int IVsHierarchy.GetSite(out IOleServiceProvider ppSP)
 {
     return ((IVsUIHierarchy)this).GetSite(out ppSP);
 }
Exemple #56
0
 public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site)
 {
     _site = site;
     return(0);
 }
Exemple #57
0
        /// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.IVsWindowPane.SetSite"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// IVsWindowPane implementation.
        /// </devdoc>
        int IVsWindowPane.SetSite(IOleServiceProvider p) {

            // The siting mechanism works as follows:  If the
            // parent provider provides ServiceProviderHierarchy
            // as a service we will insert our service provider in
            // the WindowPaneSite slot of the hierarchy.
            // If, however, it does not provide
            // this service, we will create a new 
            // ServiceProvider that will be used to resolve
            // services through this site.  
            //
            if (_provider != null) {
                _provider.Dispose();
                _provider = null;
            }

            IObjectWithSite ows = GetService(typeof(IObjectWithSite)) as IObjectWithSite;
            ServiceProviderHierarchy serviceHierarchy = GetService(typeof(ServiceProviderHierarchy)) as ServiceProviderHierarchy;
            if (serviceHierarchy != null) {
                ServiceProvider sp = (p == null ? null : new ServiceProvider(p));
                serviceHierarchy[ServiceProviderHierarchyOrder.WindowPaneSite] = sp;             
            }
            else if (ows != null) {
               ows.SetSite(p);
            }
            else {
                if (p != null) {
                    _provider = new ServiceProvider(p);
                }
            }

            if (p != null) {
                Initialize();
            }
            return NativeMethods.S_OK;
        }
Exemple #58
0
 public int GetItemContext(uint itemid, out Microsoft.VisualStudio.OLE.Interop.IServiceProvider ppSP)
 {
     _logger.LogHierarchy("GetItemContext({0})", (int)itemid);
     ppSP = null;
     return(0);
 }
        /// <summary>
        /// Called by the enviorment to provide us with our site
        /// This lets us call services that are important to the codeWindowHost
        /// </summary>
        /// <param name="psp"></param>
        /// <returns></returns>
        public int SetSite(IOleServiceProvider psp)
        {
            ServiceProvider = psp;
            //Guid to be used in SetGuidProperty as a ref parameter to tell frame that we want texteditor key bindings
            Guid cmdUI_TextEditor = GuidList.textEditorFactory;
            int hr = EditorFrame.SetGuidProperty((int) __VSFPROPID.VSFPROPID_InheritKeyBindings, ref cmdUI_TextEditor);

            return hr;
        }
 int IVsUIShell.CreateDocumentWindow(uint grfCDW, string pszMkDocument, IVsUIHierarchy pUIH, uint itemid, IntPtr punkDocView, IntPtr punkDocData, ref Guid rguidEditorType, string pszPhysicalView, ref Guid rguidCmdUI, Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp, string pszOwnerCaption, string pszEditorCaption, int[] pfDefaultPosition, out IVsWindowFrame ppWindowFrame)
 {
     throw new NotImplementedException();
 }