Ejemplo n.º 1
0
 public Context(ILocalRegistry localRegistry, IRemoteRegistry remoteRegistry, ITranslation translation = null)
     : base()
 {
     LocalRegistry  = localRegistry;
     RemoteRegistry = remoteRegistry;
     Translation    = translation;
 }
        /// <summary>
        /// Helper to create an instance from the local registry given a CLSID Guid
        /// </summary>
        internal static InterfaceType CreateInstance <InterfaceType>(System.IServiceProvider serviceProvider, Guid clsid) where InterfaceType : class
        {
            InterfaceType instance = null;

            if (clsid != Guid.Empty)
            {
                ILocalRegistry localRegistry = serviceProvider.GetService <ILocalRegistry>();
                if (localRegistry != null)
                {
                    IntPtr proxy = IntPtr.Zero;
                    Guid   iid   = NativeMethods.IID_IUnknown;

                    // This creates an IUnknown ptr to an object with the given CLSID - the problem is that the object is wrapped
                    // in a proxy behind an IntPtr. To get an object we can call from .Net we need to unwrap the proxy and then
                    // manually release the reference to the proxy.
                    //
                    // This method handles failures in creating an object or converting the appropriate type by returning null,
                    // which the surrounding code expects.
                    int hr = localRegistry.CreateInstance(clsid, null, ref iid, NativeMethods.CLSCTX_INPROC_SERVER, out proxy);
                    if (!NativeMethods.Succeeded(hr) || proxy == IntPtr.Zero)
                    {
                        return(null);
                    }

                    instance = Marshal.GetObjectForIUnknown(proxy) as InterfaceType;

                    // We're throwing here on failure because we don't expect this to every happen under any circumstances.
                    hr = Marshal.Release(proxy);
                    Marshal.ThrowExceptionForHR(hr);
                }
            }

            return(instance);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates a native object instance of the specified class type using the ILocalRegistry database
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="classType">Type of the class.</param>
        /// <returns></returns>
        protected T CreateLocalInstance <T>(Type classType)
            where T : class
        {
            if (classType == null)
            {
                throw new ArgumentNullException("classType");
            }

            ILocalRegistry registry = GetService <ILocalRegistry>(typeof(SLocalRegistry));

            Guid   gType = typeof(T).GUID;
            IntPtr instance;

            Marshal.ThrowExceptionForHR(registry.CreateInstance(classType.GUID, null, ref gType,
                                                                (uint)Microsoft.VisualStudio.OLE.Interop.CLSCTX.CLSCTX_INPROC_SERVER, out instance));

            try
            {
                return((T)Marshal.GetObjectForIUnknown(instance));
            }
            finally
            {
                if (instance != IntPtr.Zero)
                {
                    Marshal.Release(instance);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates an object
        /// </summary>
        /// <param name="localRegistry">Establishes a locally-registered COM object relative to the local Visual Studio registry hive</param>
        /// <param name="clsid">GUID if object to be created</param>
        /// <param name="iid">GUID assotiated with specified System.Type</param>
        /// <returns>An object</returns>
        public object CreateObject(ILocalRegistry localRegistry, Guid clsid, Guid iid)
        {
            object objectInstance;
            IntPtr unknown = IntPtr.Zero;

            int hr = localRegistry.CreateInstance(clsid, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out unknown);

            if (hr != VSConstants.S_OK)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            try
            {
                objectInstance = Marshal.GetObjectForIUnknown(unknown);
            }
            finally
            {
                if (unknown != IntPtr.Zero)
                {
                    Marshal.Release(unknown);
                }
            }

            // Try to site object instance
            IObjectWithSite objectWithSite = objectInstance as IObjectWithSite;

            if (objectWithSite != null)
            {
                objectWithSite.SetSite(psp);
            }

            return(objectInstance);
        }
Ejemplo n.º 5
0
        /// <include file='doc\StyleBuilderSite.uex' path='docs/doc[@for="StyleBuilderSite.GetBuilder"]/*' />
        /// <devdoc>
        /// </devdoc>
        public object GetBuilder(Type builderType)
        {
            Debug.Assert(builderType != null, "null builder type");

            object builder = null;

            if (site != null)
            {
                try {
                    ILocalRegistry localReg = (ILocalRegistry)QueryService(typeof(ILocalRegistry));
                    Debug.Assert(localReg != null);

                    if (localReg != null)
                    {
                        builder = localReg.CreateInstance(builderType.GUID, null, ref NativeMethods.IID_IUnknown, 1 /*CLSCTX_INPROC_SERVER*/);

                        Debug.Assert(builder != null, "Could not create builder of type: " + builderType.Name);
                        Debug.Assert(builder is NativeMethods.IObjectWithSite, "Builder does not implement IObjectWithSite?");

                        NativeMethods.IObjectWithSite ows = (NativeMethods.IObjectWithSite)builder;
                        ows.SetSite(site);
                        ows = null;
                    }
                }
                catch (Exception e) {
                    Debug.WriteLineIf(StyleBuilder.StyleBuilderSwitch.TraceVerbose, "Exception in StyleBuilderSite::GetBuilder\n\t" + e.ToString());
                    Debug.Fail(e.ToString());

                    builder = null;
                }
            }
            return(builder);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Utility function to create an instance of a class from the local registry.
        /// </summary>
        /// <param name="classType">The type of the class to create.</param>
        /// <param name="interfaceType">An interface implemented by the class.</param>
        private object CreateObject(Type classType, Type interfaceType)
        {
            // Get the local registry service that will allow us to create the object
            // using the registration inside the current registry root.
            ILocalRegistry localRegistry = (ILocalRegistry)globalProvider.GetService(typeof(SLocalRegistry));

            // Create the object.
            Guid   interfaceGuid = interfaceType.GUID;
            IntPtr interfacePointer;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                localRegistry.CreateInstance(classType.GUID, null, ref interfaceGuid,
                                             (uint)CLSCTX.CLSCTX_INPROC_SERVER, out interfacePointer));
            if (interfacePointer == IntPtr.Zero)
            {
                throw new COMException(Resources.CanNotCreateObject);
            }

            // Get a CLR object from the COM pointer
            object obj = null;

            try
            {
                obj = Marshal.GetObjectForIUnknown(interfacePointer);
            }
            finally
            {
                Marshal.Release(interfacePointer);
            }

            return(obj);
        }
Ejemplo n.º 7
0
 public DefaultAccountBuilder(IObjectFactory objectFactory, IAccountManagerInternal accountManager, ILocalRegistry localRegistry)
 {
     Helper.GuardNotNull(objectFactory);
     Helper.GuardNotNull(accountManager);
     Helper.GuardNotNull(localRegistry);
     _objectFactory  = objectFactory;
     _accountManager = accountManager;
     _localRegistry  = localRegistry;
 }
Ejemplo n.º 8
0
 public DefaultAccountBuilder(IObjectFactory objectFactory, IAccountManagerInternal accountManager, ILocalRegistry localRegistry)
 {
     Helper.GuardNotNull(objectFactory);
     Helper.GuardNotNull(accountManager);
     Helper.GuardNotNull(localRegistry);
     _objectFactory = objectFactory;
     _accountManager = accountManager;
     _localRegistry = localRegistry;
     _account = CreateAccount();
     _accountScope = _account.InitializationScope();
 }
Ejemplo n.º 9
0
        //private static MediaManager _instance;

        public DefaultMediaManager(IConferenceBridge conferenceBridge, IMediaApiProvider mediaApi, ILocalRegistry registry)
        {
            Helper.GuardNotNull(conferenceBridge);
            Helper.GuardNotNull(mediaApi);
            Helper.GuardNotNull(registry);
            _conferenceBridge = conferenceBridge;
            _registry         = registry;
            _mediaApi         = mediaApi;

            //SetDevices();
        }
        public RemoteQueryDialog(Context ctx, Identifier id = default(Identifier), bool updowngrade = false)
        {
            this.Font = new Font(SystemFonts.CaptionFont.FontFamily, 12F, FontStyle.Regular, GraphicsUnit.Pixel);
            InitializeComponent();

            this.ctx                = ctx;
            this.i18n               = ctx.Translation;
            this.localReg           = ctx.LocalRegistry;
            this.remoteReg          = ctx.RemoteRegistry;
            this.SelectedIdentifier = id;
            this.updowngrade        = updowngrade;
        }
Ejemplo n.º 11
0
 public DefaultImManager(ILocalRegistry localRegistry, IIMApiProvider imApi,
                         ICallApiProvider callApi, IEventsProvider eventsProvider)
 {
     Helper.GuardNotNull(localRegistry);
     Helper.GuardNotNull(imApi);
     Helper.GuardNotNull(callApi);
     Helper.GuardNotNull(eventsProvider);
     _imApi          = imApi;
     _callApi        = callApi;
     _eventsProvider = eventsProvider;
     _localRegistry  = localRegistry;
 }
Ejemplo n.º 12
0
 public DefaultAccountManager(IAccountApiProvider accountApi, IEventsProvider eventsProvider,
                              ILocalRegistry localRegistry)
 {
     Helper.GuardNotNull(accountApi);
     Helper.GuardNotNull(eventsProvider);
     Helper.GuardNotNull(localRegistry);
     _provider       = accountApi;
     _eventsProvider = eventsProvider;
     _localRegistry  = localRegistry;
     _accounts       = new SortedDictionary <int, IAccountInternal>();
     //_syncContext = SynchronizationContext.Current;
     _deleting = new Queue <Account>();
 }
Ejemplo n.º 13
0
 public MediaSession(ICallInternal call, ILocalRegistry localRegistry,
     ICallManagerInternal callManager, IConferenceBridge conferenceBridge)
 {
     Helper.GuardNotNull(call);
     Helper.GuardNotNull(localRegistry);
     Helper.GuardNotNull(callManager);
     Helper.GuardNotNull(conferenceBridge);
     _call = new WeakReference(call);
     _state = new NoneMediaState(this);
     _localRegistry = localRegistry;
     _callManager = callManager;
     _conferenceBridge = conferenceBridge;
 }
Ejemplo n.º 14
0
 public MediaSession(ICallInternal call, ILocalRegistry localRegistry,
                     ICallManagerInternal callManager, IConferenceBridge conferenceBridge)
 {
     Helper.GuardNotNull(call);
     Helper.GuardNotNull(localRegistry);
     Helper.GuardNotNull(callManager);
     Helper.GuardNotNull(conferenceBridge);
     _call             = new WeakReference(call);
     _state            = new NoneMediaState(this);
     _localRegistry    = localRegistry;
     _callManager      = callManager;
     _conferenceBridge = conferenceBridge;
 }
Ejemplo n.º 15
0
        public DefaultSipUserAgent(IBasicApiProvider basicApi, IEventsProvider eventsProvider, 
            ILocalRegistry localRegistry, IContainer container)
        {
            Helper.GuardNotNull(basicApi);
            Helper.GuardNotNull(eventsProvider);
            Helper.GuardNotNull(localRegistry);
            Helper.GuardNotNull(container);
            _basicApi = basicApi;
            _localRegistry = localRegistry;
            _container = container;
            _eventsProvider = eventsProvider;

            _eventsProvider.Subscribe<LogRequested>(e => OnLog(e));
        }
Ejemplo n.º 16
0
        public DefaultSipUserAgent(IBasicApiProvider basicApi, IEventsProvider eventsProvider,
                                   ILocalRegistry localRegistry, IContainer container)
        {
            Helper.GuardNotNull(basicApi);
            Helper.GuardNotNull(eventsProvider);
            Helper.GuardNotNull(localRegistry);
            Helper.GuardNotNull(container);
            _basicApi       = basicApi;
            _localRegistry  = localRegistry;
            _container      = container;
            _eventsProvider = eventsProvider;

            _eventsProvider.Subscribe <LogRequested>(e => OnLog(e));
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     Instantiates and sites a new VsTextBuffer.
        /// </summary>
        internal static T CreateInstance <T>(ServiceProviderHelper serviceProvider, ILocalRegistry localRegistry) where T : IVsTextBuffer
        {
            ArgumentValidation.CheckForNullReference(serviceProvider, "serviceProvider");
            ArgumentValidation.CheckForNullReference(localRegistry, "localRegistry");

            var obj = CreateObject <T>(localRegistry);

            var objectWithSite = obj as IObjectWithSite;

            if (objectWithSite != null)
            {
                objectWithSite.SetSite(serviceProvider);
            }

            return(obj);
        }
        protected override object CreateDocView(System.IServiceProvider serviceProvider, IVsHierarchy hierarchy, uint itemid, string fileName, object docData, out Guid cmdUIGuid)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            // Instead of creating a WindowPane based object, we'll create an instance of the VS Code Editor, to serve
            // as our source editor view.

            ILocalRegistry localRegistry = serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry;

            Assumes.Present(localRegistry);

            cmdUIGuid = typeof(SourceEditorFactory).GUID;
            Guid          guidCodeWindow = typeof(IVsCodeWindow).GUID;
            IntPtr        pUnkPtr;
            IVsCodeWindow vsCodeWindow;

            int hr = localRegistry.CreateInstance(typeof(VsCodeWindowClass).GUID, null, ref guidCodeWindow, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out pUnkPtr);

            ErrorHandler.ThrowOnFailure(hr);

            try
            {
                vsCodeWindow = (IVsCodeWindow)Marshal.GetObjectForIUnknown(pUnkPtr);
            }
            finally
            {
                Marshal.Release(pUnkPtr);
            }

            IVsTextLines vsTextLines = docData as IVsTextLines;

            if (vsTextLines == null)
            {
                IVsTextBufferProvider provider = docData as IVsTextBufferProvider;
                if (provider != null)
                {
                    ErrorHandler.ThrowOnFailure(provider.GetTextBuffer(out vsTextLines));
                }
            }

            if (vsTextLines != null)
            {
                ErrorHandler.ThrowOnFailure(vsCodeWindow.SetBuffer(vsTextLines));
            }

            return(vsCodeWindow);
        }
Ejemplo n.º 19
0
        void insertBeforeAuto(ILocalRegistry item)
        {
            if (RegistryManager.Config.LocalRegisteries.Contains(item))
            {
                return;
            }

            var firstAutoIndex = 0;

            while (firstAutoIndex <= localRegistryListBox.Items.Count - 1 &&
                   !((IRegistry)localRegistryListBox.Items[firstAutoIndex]).IsFromAutoDetect)
            {
                firstAutoIndex++;
            }
            item.IsFromAutoDetect = false;
            localRegistryListBox.Items.Insert(firstAutoIndex, item);
            RegistryManager.Config.LocalRegisteries.Insert(firstAutoIndex, item);
            localRegistryListBox.SelectedIndex = firstAutoIndex;
        }
Ejemplo n.º 20
0
        public DefaultCallManager(IObjectFactory objectFactory, ICallApiProvider callApi, ILocalRegistry localRegistry,
                                  IBasicApiProvider basicApi, IMediaApiProvider mediaApi, IEventsProvider eventsProvider, IAccountManagerInternal accMgr)
        {
            Helper.GuardNotNull(objectFactory);
            Helper.GuardNotNull(basicApi);
            Helper.GuardNotNull(callApi);
            Helper.GuardNotNull(mediaApi);
            Helper.GuardNotNull(localRegistry);
            Helper.GuardNotNull(eventsProvider);
            _objectFactory  = objectFactory;
            _accMgr         = accMgr;
            _mediaApi       = mediaApi;
            _eventsProvider = eventsProvider;
            _basicApi       = basicApi;
            _localRegistry  = localRegistry;
            _callApi        = callApi;

            _barrier = new ManualResetEvent(true);
            //_syncContext = SynchronizationContext.Current;
        }
Ejemplo n.º 21
0
        public DefaultCallManager(IObjectFactory objectFactory, ICallApiProvider callApi, ILocalRegistry localRegistry, 
            IBasicApiProvider basicApi, IMediaApiProvider mediaApi, IEventsProvider eventsProvider, IAccountManagerInternal accMgr)
        {
            Helper.GuardNotNull(objectFactory);
            Helper.GuardNotNull(basicApi);
            Helper.GuardNotNull(callApi);
            Helper.GuardNotNull(mediaApi);
            Helper.GuardNotNull(localRegistry);
            Helper.GuardNotNull(eventsProvider);
            _objectFactory = objectFactory;
            _accMgr = accMgr;
            _mediaApi = mediaApi;
            _eventsProvider = eventsProvider;
            _basicApi = basicApi;
            _localRegistry = localRegistry;
            _callApi = callApi;

            _barrier = new ManualResetEvent(true);
            //_syncContext = SynchronizationContext.Current;
        }
Ejemplo n.º 22
0
        public Call(ICallManagerInternal callManager, ILocalRegistry registry, IConferenceBridge conferenceBridge)
        {
            Id = -1;
            Helper.GuardNotNull(callManager);
            Helper.GuardNotNull(conferenceBridge);
            Helper.GuardNotNull(registry);
            _callManager = callManager;

            _inviteSession = new InviteSession(this, callManager);
            _inviteSession.StateChanged += delegate { OnStateChanged(); };
            _mediaSession = new MediaSession(this, registry, callManager, conferenceBridge);
            _mediaSession.StateChanged += delegate { OnStateChanged(); };

            CallInfo info = GetCallInfo();

            if (info != null)
            {
                IsIncoming = info.Role == SipRole.RoleUas;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     Instanciates a new VsTextBuffer from the local registry
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="localRegistry"></param>
        /// <returns></returns>
        private static T CreateObject <T>(ILocalRegistry localRegistry)
        {
            object obj = null;

            var iid = typeof(T).GUID;
            var ptr = IntPtr.Zero;

            NativeMethods.ThrowOnFailure(
                localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out ptr));

            try
            {
                obj = Marshal.GetObjectForIUnknown(ptr);
            }
            finally
            {
                Marshal.Release(ptr);
            }

            return((T)obj);
        }
Ejemplo n.º 24
0
        public ManipulationForm(ILocalRegistry registry, bool callInstallDlg = false, Identifier idToInstall = default(Identifier))
        {
            this.Font = new Font(SystemFonts.CaptionFont.FontFamily, 12F, FontStyle.Regular, GraphicsUnit.Pixel);
            InitializeComponent();
            this.registry = registry;

            var ctx = new Context(registry, PreferenceManager.Config.RemoteRegistry,
                                  PreferenceManager.Config.Translation);

            comboCategory.Items.Add("(ALL)");             // TODO: I18n
            foreach (var package in registry.ListPackages(ctx))
            {
                if (!comboCategory.Items.Contains(package.Category))
                {
                    comboCategory.Items.Add(package.Category);
                }
                localPackageListBox.Items.Add(package);
            }
            comboCategory.SelectedIndex = 0;

            progCtrl = new ProgressControl()
            {
                BoxColor     = Color.FromArgb(55, 57, 46),
                BarFillColor = Color.FromArgb(80, 205, 206),
                ForeColor    = Color.FromArgb(250, 250, 250),
                LogLevel     = LogLevel.Debug,
                Dock         = DockStyle.Fill
            };
            progCtrl.btnOK.Text            = I._("bpmgui_mainform_ok");
            progCtrl.btnCancel.Text        = I._("bpmgui_mainform_cancel");
            progCtrl.progressBar.TextColor = Color.Black;
            pushLog = (level, msg) =>
                      Invoke((Action <LogLevel, string>)progCtrl.PushList, level, msg);
            pushProgress = (total, finished, ratio) =>
                           BeginInvoke((Action <long?, long?, double?>)progCtrl.PushBar,
                                       total, finished, ratio);

            this.callInstallDlg = callInstallDlg;
            this.idToInstall    = idToInstall;
        }
        internal static InterfaceType CreateInstance <InterfaceType>(System.IServiceProvider serviceProvider, Guid clsid)
            where InterfaceType : class
        {
            InterfaceType objectForIUnknown = default(InterfaceType);

            if (clsid != Guid.Empty)
            {
                ILocalRegistry service = serviceProvider.GetService <ILocalRegistry>();
                if (service != null)
                {
                    IntPtr zero       = IntPtr.Zero;
                    Guid   iDIUnknown = NativeMethods.IID_IUnknown;
                    if (!NativeMethods.Succeeded(service.CreateInstance(clsid, null, ref iDIUnknown, 1, out zero)) || zero == IntPtr.Zero)
                    {
                        return(default(InterfaceType));
                    }
                    objectForIUnknown = (InterfaceType)(Marshal.GetObjectForIUnknown(zero) as InterfaceType);
                    Marshal.ThrowExceptionForHR(Marshal.Release(zero));
                }
            }
            return(objectForIUnknown);
        }
Ejemplo n.º 26
0
        ///--------------------------------------------------------------------------------------------
        /// <summary>
        /// Helper to create an instance from the local registry given a CLSID Guid
        /// </summary>
        ///--------------------------------------------------------------------------------------------
        public static InterfaceType CreateInstance <InterfaceType>(IServiceProvider serviceProvider, Guid clsid) where InterfaceType : class
        {
            InterfaceType instance = null;

            if (clsid != Guid.Empty)
            {
                ILocalRegistry localRegistry = GetService <ILocalRegistry>(serviceProvider);
                if (localRegistry != null)
                {
                    IntPtr pInstance  = IntPtr.Zero;
                    Guid   iidUnknown = NativeMethods.IID_IUnknown;

                    try
                    {
                        localRegistry.CreateInstance(clsid, null, ref iidUnknown, NativeMethods.CLSCTX_INPROC_SERVER, out pInstance);
                    }
                    catch { }

                    if (pInstance != IntPtr.Zero)
                    {
                        try
                        {
                            instance = Marshal.GetObjectForIUnknown(pInstance) as InterfaceType;
                        }
                        catch { }

                        try
                        {
                            Marshal.Release(pInstance);
                        }
                        catch { }
                    }
                }
            }

            return(instance);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates an instance of a COM object declared in the local registry of VisualStudio
        /// </summary>
        public static object CoCreateInstance(System.IServiceProvider provider, Type type, Type interfaceType)
        {
            Guard.ArgumentNotNull(provider, "provider");
            Guard.ArgumentNotNull(type, "type");
            Guard.ArgumentNotNull(interfaceType, "interfaceType");

            ILocalRegistry localRegistry = (ILocalRegistry)provider.GetService(typeof(SLocalRegistry));

            if (localRegistry != null)
            {
                Guid   interfaceGuid = interfaceType.GUID;
                IntPtr pObject       = IntPtr.Zero;
                localRegistry.CreateInstance(type.GUID,
                                             null,
                                             ref interfaceGuid,
                                             (uint)CLSCTX.CLSCTX_INPROC_SERVER,
                                             out pObject);
                if (pObject != IntPtr.Zero)
                {
                    return(Marshal.GetObjectForIUnknown(pObject));
                }
            }
            return(null);
        }
Ejemplo n.º 28
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);
        }
        public int CreateEditorInstance(uint vsCreateEditorFlags, string fileName, string physicalView,
                                        IVsHierarchy hierarchy, uint itemid, IntPtr existingDocData,
                                        out IntPtr docView, out IntPtr docData,
                                        out string caption, out Guid cmdUIGuid, out int flags)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            object docViewObject = null;

            docView   = IntPtr.Zero;
            docData   = IntPtr.Zero;
            caption   = null;
            cmdUIGuid = Guid.Empty;
            flags     = 0;

            if ((vsCreateEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            try
            {
                object docDataObject;

                // if needed create our DocData object
                if (existingDocData == IntPtr.Zero)
                {
                    ILocalRegistry localRegistry = serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry;
                    Assumes.Present(localRegistry);

                    Guid   guidUnknown = VSConstants.IID_IUnknown;
                    IntPtr newDocDataPtr;
                    ErrorHandler.ThrowOnFailure(localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref guidUnknown, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out newDocDataPtr));

                    try
                    {
                        docDataObject = Marshal.GetObjectForIUnknown(newDocDataPtr);
                    }
                    finally
                    {
                        Marshal.Release(newDocDataPtr);
                    }

                    IObjectWithSite ows = docDataObject as IObjectWithSite;
                    if (ows != null)
                    {
                        ows.SetSite(this.site);
                    }
                }
                else
                {
                    // if document is already open
                    docDataObject = Marshal.GetObjectForIUnknown(existingDocData);
                    IVsTextLines textLines = docDataObject as IVsTextLines;
                    Marshal.Release(existingDocData);

                    if (textLines == null)
                    {
                        return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }
                }

                docViewObject = this.CreateDocView(this.serviceProvider, hierarchy, itemid, fileName, docDataObject, out cmdUIGuid);
                Debug.Assert(docViewObject != null);

                // todo: maybe check to see if we need to add readonly to caption?
                caption = "";

                docView       = Marshal.GetIUnknownForObject(docViewObject);
                docData       = Marshal.GetIUnknownForObject(docDataObject);
                docViewObject = null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                // if we have a disposable view here, clean it up
                IDisposable disposableView;
                if ((disposableView = docViewObject as IDisposable) != null)
                {
                    disposableView.Dispose();
                }
            }

            return(VSConstants.S_OK);
        }
Ejemplo n.º 30
0
 public DefaultAccountManager(IAccountApiProvider accountApi, IEventsProvider eventsProvider, 
     ILocalRegistry localRegistry)
 {
     Helper.GuardNotNull(accountApi);
     Helper.GuardNotNull(eventsProvider);
     Helper.GuardNotNull(localRegistry);
     _provider = accountApi;
     _eventsProvider = eventsProvider;
     _localRegistry = localRegistry;
     _accounts = new SortedDictionary<int, IAccountInternal>();
     //_syncContext = SynchronizationContext.Current;
     _deleting = new Queue<Account>();
 }
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            IntPtr punkDocDataExisting,
            out IntPtr ppunkDocView,
            out IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out Guid pguidCmdUI,
            out int pgrfCDW)
        {
            // Initialize to null
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pbstrEditorCaption = null;
            pguidCmdUI         = GuidList.guidPartEditorFactory;
            pgrfCDW            = (int)_VSRDTFLAGS.RDT_DontSaveAs;

            try
            {
                // Validate inputs
                if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
                {
                    Debug.Assert(false, "Only Open or Silent is valid");
                    return(VSConstants.E_INVALIDARG);
                }

                PackageEditorPane existingPackageEditor = null;
                if (punkDocDataExisting != IntPtr.Zero)
                {
                    existingPackageEditor = Marshal.GetObjectForIUnknown(punkDocDataExisting) as PackageEditorPane;
                    if (existingPackageEditor == null)
                    {
                        // The user is trying to open our editor on an existing DocData which is not our editor.
                        // This editor does not support other editors simultaneously editing the same file.
                        return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }
                }

                if (pszPhysicalView == null)
                {
                    if (punkDocDataExisting != IntPtr.Zero)
                    {
                        // An XML fragment editor was already editing our DocData, and we are trying to open the main editor on it now.
                        // Just return the existing DocData object.
                        ppunkDocView       = Marshal.GetIUnknownForObject(existingPackageEditor);
                        ppunkDocData       = Marshal.GetIUnknownForObject(existingPackageEditor);
                        pbstrEditorCaption = string.Empty;
                        return(VSConstants.S_OK);
                    }
                    // Open the main editor (the normal scenario).
                    PackageEditorPane editor = new PackageEditorPane(myPackage);
                    ppunkDocView       = Marshal.GetIUnknownForObject(editor);
                    ppunkDocData       = Marshal.GetIUnknownForObject(editor);
                    pbstrEditorCaption = string.Empty;
                    return(VSConstants.S_OK);
                }

                // If physical view is non-null, create an editor window on an xml fragment.

                // Verify that the base document is created

                IVsRunningDocumentTable runningDocTable = (IVsRunningDocumentTable)this.GetService(typeof(SVsRunningDocumentTable));
                int hr = runningDocTable.FindAndLockDocument(
                    (uint)_VSRDTFLAGS.RDT_NoLock,
                    pszMkDocument,
                    out IVsHierarchy hierarchy,
                    out uint itemIdFindAndLock,
                    out IntPtr docDataFindAndLock,
                    out uint docCookieFindAndLock
                    );

                string xml = string.Empty;
                if (VSConstants.S_OK != hr) // can't find document in RDT.
                {
                    // We are being asked to open a sub document before the main document is open.
                    // Let's create the main and put it in the RDT with a temporary EditLock that
                    // we will release after the sub document window is created.
                    using (PackageEditorPane editor = new PackageEditorPane(myPackage))
                    {
                        IVsPersistDocData mainDocData = editor;
                        mainDocData.LoadDocData(pszMkDocument);
                        // TODO editor.TemporaryLockDocument(runningDocTable, pvHier, itemid, pszMkDocument);
                        xml = editor.GetXml(pszPhysicalView);
                    }
                }
                else
                {
                    // get xml from open editor.
                    if (docDataFindAndLock != IntPtr.Zero)
                    {
                        Marshal.Release(docDataFindAndLock);
                    }
                    if (existingPackageEditor != null)
                    {
                        xml = existingPackageEditor.GetXml(pszPhysicalView);
                    }
                }

                // Use ILocalRegistry to create text buffer and code window
                ILocalRegistry localRegistry = (ILocalRegistry)this.GetService(typeof(ILocalRegistry));
                Debug.Assert(null != localRegistry);

                // Create the document (text buffer)
                IntPtr vsTextLines   = IntPtr.Zero;
                Guid   guidTextLines = typeof(IVsTextLines).GUID;
                ErrorHandler.ThrowOnFailure(
                    localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref guidTextLines, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out vsTextLines)
                    );
                IVsTextLines textLines = (IVsTextLines)Marshal.GetObjectForIUnknown(vsTextLines);

                // Create the codewindow (editor)
                IntPtr vsCodeWindow   = IntPtr.Zero;
                Guid   guidCodeWindow = typeof(IVsCodeWindow).GUID;
                ErrorHandler.ThrowOnFailure(
                    localRegistry.CreateInstance(typeof(VsCodeWindowClass).GUID, null, ref guidCodeWindow, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out vsCodeWindow)
                    );
                IVsCodeWindow codeWindow = Marshal.GetObjectForIUnknown(vsCodeWindow) as IVsCodeWindow;

                // Site it, so it can find/query for various services
                IObjectWithSite textLinesWithSite = (IObjectWithSite)textLines;

                // Site the TextBuffer with an IOleServiceProvider
                IOleServiceProvider pOleSeviceProvider;
                pOleSeviceProvider = (IOleServiceProvider)this.vsServiceProvider.GetService(typeof(IOleServiceProvider));
                textLinesWithSite.SetSite(pOleSeviceProvider);

                ErrorHandler.ThrowOnFailure(
                    textLines.InitializeContent(xml, xml.Length)
                    );

                // Attach buffer to code window
                ErrorHandler.ThrowOnFailure(
                    codeWindow.SetBuffer(textLines)
                    );

                // Set the language service to the XML language service to get syntax highlighting
                Guid xmlLanguageServiceGuid = new Guid("{f6819a78-a205-47b5-be1c-675b3c7f0b8e}");
                textLines.SetLanguageServiceID(ref xmlLanguageServiceGuid);

                // If the project system has specified the language service clear the auto detect flag to ensure that we use the preferred service
                IVsUserData userData = (IVsUserData)textLines;
                Guid        vsBufferDetectLangSIDGuid = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}");
                object      flagObject = false;
                userData.SetData(ref vsBufferDetectLangSIDGuid, flagObject);

                ppunkDocView       = vsCodeWindow; // refcnt from CreateEditorInstance
                ppunkDocData       = vsTextLines;  // refcnt from CreateEditorInstance
                pbstrEditorCaption = " (" + pszPhysicalView + ")";
                pgrfCDW           |= (int)__VSCREATEDOCWIN.CDW_fAltDocData;

                return(VSConstants.S_OK);
            }
            catch (Exception error)
            {
                System.Windows.Forms.MessageBox.Show(error.Message);
            }
            return(VSConstants.E_INVALIDARG);
        }
Ejemplo n.º 32
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 CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            System.IntPtr punkDocDataExisting,
            out System.IntPtr ppunkDocView,
            out System.IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out Guid pguidCmdUI,
            out int pgrfCDW)
        {
            // Initialize to null
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = GuidList.guidVsTemplateDesignerEditorFactory;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

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

            IVsTextLines textBuffer = null;

            if (punkDocDataExisting == IntPtr.Zero)
            {
                // 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 /*CLSCTX_INPROC_SERVER*/, out ptr);
                        try
                        {
                            textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
                        }
                        finally
                        {
                            Marshal.Release(ptr); // Release RefCount from CreateInstance call
                        }

                        // It is important to site the TextBuffer object
                        IObjectWithSite objWSite = (IObjectWithSite)textBuffer;
                        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;
                }
            }
            else
            {
                // punkDocDataExisting is *not* null which means the file *is* already open.
                // We need to verify that the open document is in fact a TextBuffer. If not
                // then we need to return the special error code VS_E_INCOMPATIBLEDOCDATA which
                // causes the user to be prompted to close the open file. If the user closes the
                // file then we will be called again with punkDocDataExisting as null

                // QI existing buffer for text lines
                textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
                if (textBuffer == null)
                {
                    return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            // Create the Document (editor)
            EditorPane NewEditor = new EditorPane(editorPackage, pszMkDocument, textBuffer);

            ppunkDocView       = Marshal.GetIUnknownForObject(NewEditor);
            ppunkDocData       = Marshal.GetIUnknownForObject(textBuffer);
            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
        /// <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);
        }
Ejemplo n.º 35
0
        private ITextBuffer GetTextBufferOnUIThread(bool create)
        {
            IVsTextManager textMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
            var            model   = GetService(typeof(SComponentModel)) as IComponentModel;
            var            adapter = model.GetService <IVsEditorAdaptersFactoryService>();
            uint           itemid;

            IVsRunningDocumentTable rdt = ProjectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (rdt != null)
            {
                IVsHierarchy      hier;
                IVsPersistDocData persistDocData;
                uint   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, GetMkDocument(), out hier, out itemid, out docData, out cookie);
                    if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero)
                    {
                        if (!create)
                        {
                            return(null);
                        }
                        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);
                    }
                }

                // 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 (srpTextLines != null)
                {
                    return(adapter.GetDocumentBuffer(srpTextLines));
                }
            }

            IWpfTextView view = GetTextView();

            return(view.TextBuffer);
        }