Example #1
0
        /// <summary>
        /// Adds the specified service to the service container, and optionally promotes the
        /// service to parent service containers.
        /// </summary>
        /// <param name="serviceType">The type of service to add.</param>
        /// <param name="serviceInstanceOrCallback">
        /// <para>An instance of the service type to add. This object must implement or inherit
        /// from the type indicated by the <paramref name="serviceType"/> parameter.</para>
        /// <para>- or -</para>
        /// <para>A callback object that is used to create the service. This allows a service
        /// to be declared as available, but delays the creation of the object until the
        /// service is requested.</para>
        /// </param>
        /// <param name="promote">
        /// <see langword="true"/> to promote this request to any parent service containers;
        /// otherwise, <see langword="false"/>.
        /// </param>
        private void AddServiceHelper(Type serviceType, object serviceInstanceOrCallback, bool promote)
        {
            Tracer.Assert(serviceType != null && serviceInstanceOrCallback != null, "Shouldn't have null parameters.");

            // Create the services table if necessary.
            if (this.services == null)
            {
                this.services = new Hashtable();
            }

            bool isCallback          = (serviceInstanceOrCallback is ServiceCreatorCallback);
            Type serviceInstanceType = serviceInstanceOrCallback.GetType();

            if (!isCallback && !serviceInstanceType.IsCOMObject && !serviceType.IsAssignableFrom(serviceInstanceType))
            {
                string message = this.Context.NativeResources.GetString(ResId.IDS_E_INVALIDSERVICEINSTANCE, serviceType.FullName);
                Tracer.Fail(message);
                throw new ArgumentException(message);
            }

            // Disallow the addition of duplicate services.
            if (this.services.ContainsKey(serviceType))
            {
                string message = this.Context.NativeResources.GetString(ResId.IDS_E_DUPLICATESERVICE, serviceType.FullName);
                Tracer.Fail(message);
                throw new InvalidOperationException(message);
            }

            if (promote)
            {
                // If we're promoting, we need to store this guy in a promoted service
                // object because we need to manage additional state.  We attempt
                // to proffer at this time if we have a service provider.  If we don't,
                // we will proffer when we get one.
                ProfferedService service = new ProfferedService();
                service.Instance = serviceInstanceOrCallback;
                if (isCallback)
                {
                    this.services[serviceType] = service;
                }

                if (this.Context.ServiceProvider != null)
                {
                    IProfferService ps = (IProfferService)GetService(typeof(IProfferService));
                    if (ps != null)
                    {
                        uint cookie;
                        Guid serviceGuid = serviceType.GUID;
                        int  hr          = ps.ProfferService(ref serviceGuid, this, out cookie);
                        service.Cookie = cookie;
                        if (NativeMethods.Failed(hr))
                        {
                            string message = this.Context.NativeResources.GetString(ResId.IDS_E_FAILEDTOPROFFERSERVICE, serviceType.FullName);
                            Tracer.Fail(message);
                            throw new COMException(message, hr);
                        }
                    }
                }
            }

            if (!isCallback || (isCallback && !promote))
            {
                this.services[serviceType] = serviceInstanceOrCallback;
            }
        }
Example #2
0
 /// <summary>
 /// Event handler for the bound object's <see cref="PropertyPageSettings.PropertyChanged">PropertyChanged</see> event.
 /// </summary>
 /// <param name="sender">The bound object.</param>
 /// <param name="e">The <see cref="PropertyChangedEventArgs"/> object that contains the event data.</param>
 private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
 {
     Tracer.Assert(sender as PropertyPageSettings == this.BoundObject, "The sender should be the cached bound object.");
     this.NotifyPageSiteOnDirtyStateChange();
     this.Refresh();
 }
Example #3
0
        int IVsProjectFactory.CreateProject(string pszFilename, string pszLocation, string pszName, uint grfCreateFlags, ref Guid iidProject, out IntPtr ppvProject, out int pfCanceled)
        {
            IntPtr pUnk = IntPtr.Zero;

            pfCanceled = 0;
            ppvProject = IntPtr.Zero;

            bool loadedSuccessfully = false;

            try
            {
                Tracer.VerifyStringArgument(pszFilename, "pszFilename");

                __VSCREATEPROJFLAGS createFlags = (__VSCREATEPROJFLAGS)grfCreateFlags;

                // Get the right version of the project serializer.
                ProjectSerializer serializer = this.CreateSerializer(pszFilename);

                // Do we need to suppress any load failures from being reported to the end user.
                serializer.SilentFailures = ((createFlags & __VSCREATEPROJFLAGS.CPF_SILENT) == __VSCREATEPROJFLAGS.CPF_SILENT);

                // Now we need to load the project, either from a template file or from an existing file.
                bool openExisting     = ((createFlags & __VSCREATEPROJFLAGS.CPF_OPENFILE) == __VSCREATEPROJFLAGS.CPF_OPENFILE);
                bool openFromTemplate = ((createFlags & __VSCREATEPROJFLAGS.CPF_CLONEFILE) == __VSCREATEPROJFLAGS.CPF_CLONEFILE);
                Tracer.Assert((openExisting && !openFromTemplate) || (!openExisting && openFromTemplate), "The grfCreateFlags are incorrect. You can't have both opening existing and opening from template. Flags={0}", createFlags);

                if (openExisting)
                {
                    Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "Attempting to load project: File name={0} Location={1} Name={2} GUID={3}.", pszFilename, pszLocation, pszName, iidProject.ToString("B").ToUpper(CultureInfo.InvariantCulture));
                    loadedSuccessfully = serializer.Load(pszFilename);

                    if (loadedSuccessfully)
                    {
                        Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "Successfully loaded project '{0}'.", pszFilename);
                    }
                    else
                    {
                        Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "There were errors in loading project '{0}'.", pszFilename);
                    }
                }
                else
                {
                    Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "Attempting to create a new project from a template: File name={0} Location={1} Name={2} GUID={3}.", pszFilename, pszLocation, pszName, iidProject.ToString("B").ToUpper(CultureInfo.InvariantCulture));
                    Tracer.VerifyStringArgument(pszLocation, "pszLocation");
                    Tracer.VerifyStringArgument(pszName, "pszName");

                    string destinationFile = Path.Combine(pszLocation, pszName);
                    loadedSuccessfully = serializer.LoadFromTemplate(pszFilename, destinationFile);

                    if (loadedSuccessfully)
                    {
                        Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "Successfully loaded project '{0}'.", pszFilename);
                    }
                    else
                    {
                        Tracer.WriteLineInformation(classType, "IVsProjectFactory.CreateProject", "There were errors in loading project '{0}'.", pszFilename);
                    }
                }

                if (loadedSuccessfully)
                {
                    // Once we've loaded the project, we need to return the COM object that the environment is requesting.
                    pUnk = Marshal.GetIUnknownForObject(serializer.Project);
                    int hr = Marshal.QueryInterface(pUnk, ref iidProject, out ppvProject);
                    Tracer.Assert(NativeMethods.Succeeded(hr), "Cannot get the requested project interface ({0}): returned {1}", iidProject.ToString("B").ToUpper(CultureInfo.InvariantCulture), hr);
                    NativeMethods.ThrowOnFailure(hr);
                }
            }
            catch (Exception e)
            {
                Package.Instance.Context.NotifyInternalError(e.ToString());
            }
            finally
            {
                if (pUnk != IntPtr.Zero)
                {
                    Marshal.Release(pUnk);
                }
            }

            return(loadedSuccessfully ? NativeMethods.S_OK : NativeMethods.E_FAIL);
        }
Example #4
0
        /// <summary>
        /// Opens the standard editor for this file type in Visual Studio.
        /// </summary>
        /// <param name="logicalView">The type of view in which to open the document.</param>
        /// <param name="existingDocumentData">
        /// Passed through to the IVsUIShellOpenDocument.OpenStandardEditor or OpenSpecificEditor, which
        /// will then determine if the document is already opened and reused the open window.
        /// </param>
        /// <param name="physicalView">
        /// Name of the physical view if we're opening with a specific editor. Not used if opening with a standard editor.
        /// </param>
        /// <param name="specificEditor">The GUID of the specific registered editor to use to open this node.</param>
        /// <returns>The <see cref="IVsWindowFrame"/> object that contains the opened document.</returns>
        private IVsWindowFrame Open(VsLogicalView logicalView, IntPtr existingDocumentData, Guid specificEditor, string physicalView)
        {
            Tracer.VerifyNonNullArgument(logicalView, "logicalView");

            // Check to see if the file exists before we try to open it.
            if (!File.Exists(this.AbsolutePath))
            {
                Context.ShowErrorMessageBox(SconceStrings.FileDoesNotExist(this.AbsolutePath));
                return(null);
            }

            IVsWindowFrame windowFrame;
            Guid           logicalViewGuid   = logicalView.Value;
            Guid           editorTypeGuid    = specificEditor;
            bool           useSpecificEditor = (specificEditor != Guid.Empty);
            int            hr;

            // Get a IVsUIShellOpenDocument object so that we can use it to open the document.
            IVsUIShellOpenDocument vsUIShellOpenDocument = (IVsUIShellOpenDocument)this.ServiceProvider.GetServiceOrThrow(typeof(SVsUIShellOpenDocument), typeof(IVsUIShellOpenDocument), classType, "Open");

            // Open the document.
            if (useSpecificEditor)
            {
                hr = vsUIShellOpenDocument.OpenSpecificEditor(
                    0,
                    this.CanonicalName,
                    ref editorTypeGuid,
                    physicalView,
                    ref logicalViewGuid,
                    this.Caption,
                    (IVsUIHierarchy)this.Hierarchy,
                    this.HierarchyId,
                    existingDocumentData,
                    (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Package.Instance,
                    out windowFrame);
            }
            else
            {
                hr = vsUIShellOpenDocument.OpenStandardEditor(
                    unchecked ((uint)__VSOSEFLAGS.OSE_ChooseBestStdEditor),
                    this.CanonicalName,
                    ref logicalViewGuid,
                    this.Caption,
                    (IVsUIHierarchy)this.Hierarchy,
                    this.HierarchyId,
                    existingDocumentData,
                    (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Package.Instance,
                    out windowFrame);
            }

            string editorTypeName = useSpecificEditor ? "specific" : "standard";

            if (NativeMethods.Succeeded(hr))
            {
                Tracer.WriteLineInformation(classType, "Open", "Succeeded in opening '{0}' with a {1} editor.", this.AbsolutePath, editorTypeName);
                if (windowFrame != null)
                {
                    // Get the document cookie and cache it.
                    object pvar;
                    hr = windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out pvar);
                    NativeMethods.ThrowOnFailure(hr);
                    // pvar is an int, but we need a uint. We get an error if we try to immediately cast to uint
                    // without first casting to an int.
                    uint cookie = unchecked ((uint)(int)pvar);
                    this.SetDocumentCookie(cookie);
                    Tracer.WriteLineInformation(classType, "Open", "Document '{0}' has a cookie value of {1}", this.AbsolutePath, cookie);

                    // Show the window frame of the open document. The documentation says we don't need to do this, but the reality is different.
                    hr = windowFrame.Show();
                    Tracer.Assert(NativeMethods.Succeeded(hr), "Error in IVsWindowFrame.Show(): 0x{0:x}", hr);

                    // Trace the running documents.
                    VsHelperMethods.TraceRunningDocuments();
                }
                else
                {
                    Tracer.Fail("Open succeeded but we were returned a null IVsWindowFrame so we can't show the document.");
                }
            }
            else if (hr == NativeMethods.OLE_E_PROMPTSAVECANCELLED)
            {
                Tracer.WriteLineInformation(classType, "Open", "The user canceled out of the open dialog box.");
            }
            else
            {
                Tracer.Fail("Failed to open '{0}' with a {1} editor. Hr=0x{2:x}", this.AbsolutePath, editorTypeName, hr);
                NativeMethods.ThrowOnFailure(hr);
            }

            return(windowFrame);
        }