private IntPtr CreateFormView(
            IVsHierarchy hierarchy,
            uint itemid,
            IVsTextLines textLines,
            ref string editorCaption,
            ref Guid cmdUI)
        {
            // Request the Designer Service
            IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));

            // Create loader for the designer
            IVSMDDesignerLoader designerLoader =
                (IVSMDDesignerLoader)designerService.CreateDesignerLoader(
                    "Microsoft.VisualStudio.Designer.Serialization.VSDesignerLoader");

            bool loaderInitalized = false;

            try
            {
                IOleServiceProvider service = null;
                ThreadHelper.JoinableTaskFactory.Run(async delegate
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                    service = (IOleServiceProvider)_serviceProvider.GetService(typeof(IOleServiceProvider));
                });

                // Initialize designer loader
                designerLoader.Initialize(service, hierarchy, (int)itemid, textLines);
                loaderInitalized = true;

                // Create the designer
                IVSMDDesigner designer = designerService.CreateDesigner(service, designerLoader);

                // Get editor caption
                editorCaption = designerLoader.GetEditorCaption((int)READONLYSTATUS.ROSTATUS_Unknown);

                // Get view from designer
                object docView = designer.View;

                // Get command guid from designer
                cmdUI = designer.CommandGuid;

                return(Marshal.GetIUnknownForObject(docView));
            }
            catch
            {
                // The designer loader may have created a reference to the shell or the text buffer.
                // In case we fail to create the designer we should manually dispose the loader
                // in order to release the references to the shell and the textbuffer
                if (loaderInitalized)
                {
                    designerLoader.Dispose();
                }
                throw;
            }
        }
        private IVSMDDesignerService GetDesignerFromForegroundThread()
        {
            if (_dotNotAccessDirectlyDesigner != null)
            {
                return(_dotNotAccessDirectlyDesigner);
            }

            AssertIsForeground();
            _dotNotAccessDirectlyDesigner = _serviceProvider.GetService(typeof(SVSMDDesignerService)) as IVSMDDesignerService;

            return(_dotNotAccessDirectlyDesigner);
        }
        private IntPtr CreateDesignerView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI, string documentMoniker)
        {
            // Request the Designer Service
            IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));

            try
            {
                // Get the service provider
                IOleServiceProvider provider = serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;

                // Create loader for the designer
                FrameXmlDesignerLoader designerLoader = new FrameXmlDesignerLoader(textLines, documentMoniker, itemid);

                // Create the designer using the provider and the loader
                IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader);

#if !HIDE_FRAME_XML_PANE
                // Retrieve the design surface
                DesignSurface designSurface = (DesignSurface)designer;

                // Create pane with this surface
                FrameXmlPane frameXmlPane = new FrameXmlPane(designSurface);

                designerLoader.InitializeFrameXmlPane(frameXmlPane);

                // Get command guid from designer
                cmdUI         = frameXmlPane.CommandGuid;
                editorCaption = " [Design]";

                // Return FrameXmlPane
                return(Marshal.GetIUnknownForObject(frameXmlPane));
#else
                object view = designer.View;

                cmdUI         = designer.CommandGuid;
                editorCaption = " [Design]";

                designerLoader.InitializeFrameXmlPane(null);
                // Return view
                return(Marshal.GetIUnknownForObject(view));
#endif
            }
            catch (Exception ex)
            {
                // Just rethrow for now
                throw;
            }
        }
        private void NotifyLegacyProjectSystemOnUIThread(
            IVSMDDesignerService designerService,
            IVsHierarchy hierarchy,
            DesignerAttributeData data)
        {
            this.AssertIsForeground();

            var itemId = hierarchy.TryGetItemId(data.FilePath);

            if (itemId == VSConstants.VSITEMID_NIL)
            {
                return;
            }

            // PERF: Avoid sending the message if the project system already has the current value.
            if (ErrorHandler.Succeeded(hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ItemSubType, out var currentValue)))
            {
                var currentStringValue = string.IsNullOrEmpty(currentValue as string) ? null : (string)currentValue;
                if (string.Equals(currentStringValue, data.Category, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
            }

            try
            {
                designerService.RegisterDesignViewAttribute(
                    hierarchy, (int)itemId, dwClass: 0,
                    pwszAttributeValue: data.Category);
            }
            catch
            {
                // DevDiv # 933717
                // turns out RegisterDesignViewAttribute can throw in certain cases such as a file failed to be checked out by source control
                // or IVSHierarchy failed to set a property for this project
                //
                // just swallow it. don't crash VS.
            }
        }
        /// <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);
        }
        private IVSMDDesignerService GetDesignerFromForegroundThread()
        {
            if (_dotNotAccessDirectlyDesigner != null)
            {
                return _dotNotAccessDirectlyDesigner;
            }

            AssertIsForeground();
            _dotNotAccessDirectlyDesigner = _serviceProvider.GetService(typeof(SVSMDDesignerService)) as IVSMDDesignerService;

            return _dotNotAccessDirectlyDesigner;
        }
        private IntPtr CreateDesignerView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI, string documentMoniker)
        {
            // Request the Designer Service
            IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));

            try
            {
                // Get the service provider
                IOleServiceProvider provider = serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
                IObjectWithSite     ows      = (IObjectWithSite)textLines;
                ows.SetSite(provider);
                // Create loader for the designer
                LimnorXmlDesignerLoader2 designerLoader = new LimnorXmlDesignerLoader2(documentMoniker, itemid);

                // Create the designer using the provider and the loader
                IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader);

                designerLoader.AddComponentChangeEventHandler();

                // Retrieve the design surface
                DesignSurface designSurface = (DesignSurface)designer;

                IDesignerHost dh = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                dh.AddService(typeof(INameCreationService), new NameCreationService());

                IServiceContainer serviceContainer = dh.GetService(typeof(ServiceContainer)) as IServiceContainer;
                dh.AddService(typeof(IDesignerSerializationService), new DesignerSerializationService(serviceContainer));
                //DesignerSerializationService uses CodeDomComponentSerializationService
                CodeDomComponentSerializationService codeDomComponentSerializationService = new CodeDomComponentSerializationService(serviceContainer);
                dh.AddService(typeof(ComponentSerializationService), codeDomComponentSerializationService);

                //LimnorUndoEngine undoEngine = new LimnorUndoEngine(serviceContainer);
                //undoEngine.Enabled = false;//not use undo during loading
                //dh.AddService(typeof(UndoEngine), undoEngine);
                //object v = dh.GetService(typeof(IOleUndoManager));
                //if (v != null)
                //{
                //    object v2 = dh.GetService(typeof(UndoEngine));
                //    if (v2 == null)
                //    {
                //        dh.AddService(typeof(UndoEngine), v);
                //    }
                //}
                // Create pane with this surface
                LimnorXmlPane2 limnorXmlPane = new LimnorXmlPane2(designSurface);//, winControlPME);

                // Get command guid from designer
                cmdUI         = limnorXmlPane.CommandGuid;
                editorCaption = " [Design]";
                if (designerLoader.IsSetup)
                {
                }
                else
                {
                    if (limnorXmlPane.Loader.ObjectMap != null)
                    {
                        limnorXmlPane.BeginApplyConfig();
                    }
                }
                // Return LimnorXmlPane
                return(Marshal.GetIUnknownForObject(limnorXmlPane));
            }
            catch (Exception ex)
            {
                MathNode.Log(ex);
                //Trace.WriteLine("Exception: " + ex.Message);
                // Just rethrow for now
                throw;
            }
        }