int IPersistFileFormat.InitNew(uint nFormatIndex) { // We don't have to do anything in this method because we'll never be called. A new // project is created in a different way than through this interface. Tracer.Fail("IPersistFileFormat.InitNew should never get called."); return(NativeMethods.S_OK); }
/// <summary> /// Reads the <LibraryReference> node. /// </summary> /// <param name="node">The <see cref="XmlNode"/> to read.</param> /// <returns>true if the node was read correctly; otherwise, false.</returns> protected bool ReadLibraryReferenceNode(XmlNode node) { if (!this.VerifyNode(node, this.ReferenceElementName)) { Tracer.Fail("Getting to this point indicates a bug."); return(false); } // <Reference RelativePath="path" /> string relativePath; if (!this.GetRequiredAttribute(node, AttributeNames.RelativePath, out relativePath)) { return(false); } // Make the relative path into an absolute one. string absolutePath = Path.Combine(this.Project.RootDirectory, relativePath); absolutePath = PackageUtility.CanonicalizeFilePath(absolutePath); // Add the reference to the library node. this.Project.AddReference(absolutePath, false); return(true); }
/// <summary> /// Reads the <Configuration> node and all of its children. /// </summary> /// <param name="node">The <see cref="XmlNode"/> to read.</param> /// <returns>true if the node was read correctly; otherwise, false.</returns> protected bool ReadConfigurationNode(XmlNode node) { if (!this.VerifyNode(node, ElementNames.Configuration)) { Tracer.Fail("Getting to this point indicates a bug."); return(false); } // Read in all of the required attributes. string name; string outputDirectory; if (!this.GetRequiredAttribute(node, AttributeNames.Name, out name) || !this.GetRequiredAttribute(node, AttributeNames.RelativeOutputDirectory, out outputDirectory)) { return(false); } // Read in all of the optional attributes string intermediateDirectory = this.GetOptionalAttribute(node, AttributeNames.RelativeIntermediateDirectory, outputDirectory); // Create the project configuration and add it to the project. ProjectConfiguration projectConfig = this.CreateProjectConfiguration(this.Project, name); projectConfig.RelativeOutputDirectory = outputDirectory; projectConfig.RelativeIntermediateDirectory = intermediateDirectory; this.Project.ConfigurationProvider.ProjectConfigurations.Add(projectConfig); // Read the children. bool success = this.ReadConfigurationChildrenNodes(node, projectConfig); return(success); }
/// <summary> /// Throws an <see cref="InvalidOperationException"/> informing the user that a critical service is missing and to /// try to repair the Visual Studio installation. /// </summary> /// <param name="classType">The type of the class containing the method.</param> /// <param name="methodName">The name of the method that is being entered.</param> /// <param name="serviceType">An object that specifies the type of service object that was requested but failed.</param> /// <remarks>Also logs a failure message in the trace log and asserts in debug mode.</remarks> public void ThrowFailedServiceException(Type classType, string methodName, Type serviceType) { string serviceTypeName = serviceType.Name; Tracer.Fail("Cannot get an instance of {0}", serviceTypeName); throw new InvalidOperationException(SconceStrings.ErrorMissingService(serviceTypeName)); }
//========================================================================================== // Constructors //========================================================================================== /// <summary> /// Initializes a new instance of the <see cref="PackageContext"/> class. /// </summary> /// <param name="serviceProvider"> /// The <see cref="ServiceProvider"/> instance to use for getting services from the environment. /// </param> public PackageContext(ServiceProvider serviceProvider) { Tracer.VerifyNonNullArgument(serviceProvider, "serviceProvider"); this.serviceProvider = serviceProvider; // Get an IUIHostLocale instance and Visual Studio's locale IUIHostLocale hostLocale = this.GetService(typeof(SUIHostLocale)) as IUIHostLocale; Tracer.Assert(hostLocale != null, "Cannot get Visual Studio's locale. Defaulting to current thread's locale."); int lcid = Thread.CurrentThread.CurrentUICulture.LCID; if (hostLocale != null) { uint lcidUnsigned; int hr = hostLocale.GetUILocale(out lcidUnsigned); if (NativeMethods.Succeeded(hr)) { lcid = (int)lcidUnsigned; } else { Tracer.Fail("Cannot get Visual Studio's locale. Defaulting to current thread's locale."); } } // Initialize our helpers this.managedResources = this.CreateManagedResourceManager(); this.nativeResources = new NativeResourceManager(lcid); this.settings = this.CreatePackageSettings(this.ServiceProvider); }
//========================================================================================== // Methods //========================================================================================== /// <summary> /// Executes the command line, piping output to the specified output pane. /// </summary> /// <param name="outputPane">The output pane to write message to.</param> /// <param name="launchPadEvents">Receives event callbacks on the progress of the process.</param> /// <returns>Value returned by the process.</returns> public int ExecuteCommand(IVsOutputWindowPane outputPane, IVsLaunchPadEvents launchPadEvents) { Tracer.VerifyNonNullArgument(outputPane, "outputPane"); Tracer.VerifyNonNullArgument(launchPadEvents, "launchPadEvents"); // Create the IVsLaunchPad object if it hasn't been created yet. if (this.launchPad == null) { this.launchPad = this.CreateLaunchPad(); } uint processExitCode; uint flags = unchecked ((uint)this.Flags); uint taskPadCategory = unchecked ((uint)this.TaskPadCategory); uint taskItemBitmap = unchecked ((uint)this.TaskItemBitmap); int hr = this.launchPad.ExecCommand(null, this.CommandLine, this.WorkingDirectory, flags, outputPane, taskPadCategory, taskItemBitmap, null, launchPadEvents, out processExitCode, null); if (NativeMethods.Failed(hr)) { string debugMessage = PackageUtility.SafeStringFormatInvariant("Error in attempting to launch command '{0}': Hr=0x{1:x}", this.CommandLine, hr); Package.Instance.Context.NotifyInternalError(ResourceId.IDS_E_BUILD, debugMessage); Tracer.Fail(debugMessage); } return((int)processExitCode); }
/// <summary> /// Initializes the image list by loading a bitmap strip from the resource file. /// </summary> private static void Initialize() { // Create and initialize the image list. imageList = new ImageList(); imageList.ImageSize = new Size(16, 16); imageList.TransparentColor = Color.Magenta; // Load the bitmap strip. The stream and bitmap must be around for the lifetime of // the image list so don't use "using" or Dispose them because the image list has // a reference to them and will dispose them correctly. Type thisType = typeof(HierarchyImages); Stream bitmapStream = thisType.Assembly.GetManifestResourceStream(thisType, BitmapName); // Check to make sure that the bitmap actually got loaded. if (bitmapStream == null) { Tracer.Fail("The image list for the hierarchy images cannot be found."); bitmapLoadFailed = true; } else { Bitmap imageStrip = new Bitmap(bitmapStream); // Assign the bitmap strip to the image list. imageList.Images.AddStrip(imageStrip); } }
/// <summary> /// Reads a node containing no attributes and all of its children, where each child is of the same type. /// </summary> /// <param name="node">The <see cref="XmlNode"/> to read.</param> /// <param name="nodeName">The name of the collection node.</param> /// <param name="childNodeName">The name of the children nodes.</param> /// <param name="readItem">A delegate pointing to the method that reads the individual collection items.</param> /// <returns>true if the node was read correctly; otherwise, false.</returns> protected bool ReadCollectionNode(XmlNode node, string nodeName, string childNodeName, ReadCollectionItem readItem) { bool successful = true; // Make sure we're reading the expected node. if (!this.VerifyNode(node, nodeName)) { Tracer.Fail("Getting to this point indicates a bug."); return(false); } // Read all of the children. foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == childNodeName) { if (!readItem(childNode)) { successful = false; break; } } } return(successful); }
//========================================================================================== // Methods //========================================================================================== int IList.Add(object value) { if (this.IsReadOnly) { Tracer.Fail("The collection is read-only."); throw new NotSupportedException("Cannot add to a read-only collection."); } this.ValidateType(value); this.OnAdd(value); // Find the spot to insert the node, or the index if it already exists. int index = this.list.BinarySearch(value, this.comparer); if (index >= 0) { throw new ArgumentException("value is already in the collection", "value"); } // Find the location to insert the new item by taking the bitwise complement of the // negative number returned from BinarySearch. index = ~index; this.list.Insert(index, value); this.OnAddComplete(index, value); // Raise the CollectionChanged event. this.OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); return(index); }
/// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// <para>A service object of type <paramref name="serviceType"/>.</para> /// <para>-or-</para> /// <para><see langword="null"/> if there is no service object of type /// <paramref name="serviceType"/>.</para> /// </returns> public object GetService(Type serviceType) { Tracer.VerifyNonNullArgument(serviceType, "serviceType"); Tracer.WriteLineVerbose(classType, "GetService", "ServiceType = {0}", serviceType.FullName); // Check for the special services that we provide. if (serviceType == typeof(IServiceContainer) || serviceType == Instance.GetType()) { return(this); } object value = null; // Check our proferred services list to see if we can return this service. if (this.services != null) { value = this.services[serviceType]; if (value is ProfferedService) { value = ((ProfferedService)value).Instance; } // If we have a callback then we have to attempt to create the service // by calling the callback method. if (value is ServiceCreatorCallback) { // In case the callback method tries to recursively call back into // us, we'll just null out the entry for this service now. That // way this method will just fail instead of allowing for a stack // overflow exception. this.services[serviceType] = null; // Let the callback create the service. Tracer.WriteLineVerbose(classType, "GetService", "Creating the {0} service via a callback.", serviceType.FullName); value = ((ServiceCreatorCallback)value)(this, serviceType); // Verify that the callback gave us a valid service. if (value != null && !value.GetType().IsCOMObject&& !serviceType.IsAssignableFrom(value.GetType())) { // Well, the callback was naughty and didn't give us what we wanted, but // let's not punish our caller by raising an exception. We'll just fail // by nulling the value. Tracer.Fail("The service creator callback returned the object '{0}' that doesn't implement the requested type '{1}'", value.GetType().FullName, serviceType.FullName); value = null; } // Set the created service in our proferred service list. this.services[serviceType] = value; } } // Let our parent provider handle the rest of the types. if (value == null && this.Context.ServiceProvider != null) { value = this.Context.ServiceProvider.GetService(serviceType); } return(value); }
public int Compare(object x, object y) { Node node1 = x as Node; Node node2 = y as Node; // Null checks. if (node1 == null && node2 == null) { return(0); } if (node1 == null && node2 != null) { return(1); } if (node1 != null && node2 == null) { return(-1); } // If they're the same type, then sort by caption. if (node1.GetType() == node2.GetType() || (node1 is FileNode && node2 is FileNode)) { return(String.Compare(node1.Caption, node2.Caption, StringComparison.InvariantCultureIgnoreCase)); } // Root first, then library, then folders, then file. if (node1 is ProjectNode) { return(-1); } if (node2 is ProjectNode) { return(1); } if (node1 is ReferenceFolderNode) { return(-1); } if (node2 is ReferenceFolderNode) { return(1); } if (node1 is FolderNode) { return(-1); } if (node2 is FolderNode) { return(1); } Tracer.Fail("FolderFirstComparer.Compare: We should not be hitting here."); return(0); }
protected override void CastAndStoreValue(object value) { try { this.value = (string)value; } catch (InvalidCastException) { this.value = (string)this.DefaultValue; Tracer.Fail("Cannot convert '{0}' to a string.", value.ToString()); } }
/// <summary> /// Removes the node from the project. /// </summary> /// <remarks>By default, this does nothing.</remarks> public virtual void RemoveFromProject() { // Don't do anything if we can't remove the node. if (!this.CanRemoveFromProject) { return; } FolderNode parentFolder = this.Parent; // We'd better have a parent. if (parentFolder == null) { Tracer.Fail("Cannot remove the root node from the project."); return; } // Our parent better have children. if (parentFolder.Children == null) { Tracer.Fail("This node's ({0}) parent ({1}) should have a non-null Children collection.", this.ToString(), parentFolder.ToString()); return; } // Before we remove ourself from the hierachy, make sure that we're not selected. // If we have to, we'll move the selection to the previous sibling. Node nodeToSelect = null; if (this.Selected) { // If the previous sibling is null, then select the root node. if (this.PreviousSibling != null) { nodeToSelect = this.PreviousSibling; } else { nodeToSelect = this.Hierarchy.RootNode; } } // Remove ourself from the parent. parentFolder.Children.Remove(this); // Now select the node. We have to do it here because the removal causes a refresh // on the hierarchy, which will select the root node by default. if (nodeToSelect != null) { nodeToSelect.Select(); } }
/// <summary> /// Initializes this package. /// </summary> private void Initialize() { int hr = NativeMethods.S_OK; // If we have any services to proffer, let's do it now. if (this.services != null) { IProfferService ps = (IProfferService)this.GetService(typeof(IProfferService)); Tracer.Assert(ps != null, "We have services to proffer, but can't get an instance of IProfferService."); if (ps != null) { foreach (DictionaryEntry entry in this.services) { ProfferedService service = entry.Value as ProfferedService; if (service != null) { Type serviceType = (Type)entry.Key; Guid serviceGuid = serviceType.GUID; uint cookie; 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); } } } } } // Create the Project Factory and register our project types. Tracer.WriteLineInformation(classType, "Initialize", "Creating the project factory and registering our project types."); IVsRegisterProjectTypes regProjTypes = (IVsRegisterProjectTypes)this.Context.ServiceProvider.GetServiceOrThrow(typeof(SVsRegisterProjectTypes), typeof(IVsRegisterProjectTypes), classType, "Initialize"); this.projectFactory = this.CreateProjectFactory(); Guid projectGuid = this.ProjectTypeGuid; hr = regProjTypes.RegisterProjectType(ref projectGuid, this.projectFactory, out this.projectCookie); if (NativeMethods.Succeeded(hr)) { Tracer.WriteLine(classType, "Initialize", Tracer.Level.Information, "Successfully registered our project types."); } else { Tracer.Fail("Failed to register the Wix Project type. HRESULT = 0x{0}", hr.ToString("x")); } }
//========================================================================================== // Constructors //========================================================================================== /// <summary> /// Initializes a new instance of the <see cref="NativeResourceManager"/> class. /// </summary> public NativeResourceManager(int lcid) { try { // Set the thread's cultures to that of the VS shell's locale so that our // resource strings will be the right language. CultureInfo culture = new CultureInfo(lcid, false); Thread.CurrentThread.CurrentUICulture = culture; Thread.CurrentThread.CurrentCulture = culture; } catch (Exception e) { Tracer.Fail("Cannot set the current thread's culture to {0}: {1}", lcid, e.ToString()); } }
/// <summary> /// Clones this object into the specified object by performing deep copy if the elements implement /// <see cref="ICloneable"/>, otherwise a shallow copy is performed. /// </summary> /// <param name="clone">The object to clone this object into.</param> protected void CloneInto(CloneableCollection clone) { if (this.innerList != null) { this.CloneIntoList(clone); } else if (this.innerDictionary != null) { this.CloneIntoDictionary(clone); } else { Tracer.Fail("The CloneableCollection is in an illegal state."); } }
public void Remove(uint cookie) { if (this.listeners.ContainsKey(cookie)) { this.listeners.Remove(cookie); Tracer.WriteLine(classType, "Remove", Tracer.Level.Information, "Removing an event listener from the {0} collection: Cookie={1}", this.GetType().Name, cookie); } else { string message = "Attempting to unadvise an unregistered event sink. Cookie=" + cookie; Tracer.Fail(message); message = Package.Instance.Context.NativeResources.GetString(ResourceId.IDS_E_UNADVISINGUNREGISTEREDEVENTSINK, cookie); Package.Instance.Context.ShowErrorMessageBox(message); } }
protected override void CastAndStoreValue(object value) { try { this.value = (Enum)Enum.Parse(this.enumType, value.ToString(), true); } catch (FormatException) { this.value = (Enum)this.DefaultValue; Tracer.Fail("Cannot convert '{0}' to an enum of type '{1}'.", value.ToString(), this.enumType.Name); } catch (InvalidCastException) { this.value = (Enum)this.DefaultValue; Tracer.Fail("Cannot convert '{0}' to a string.", value.ToString()); } }
/// <summary> /// Performs initial verifications on the new caption before anything is changed. This includes /// making sure that it's a valid file name and that the user wants to change the extension. /// </summary> /// <param name="newCaption">The new caption value.</param> /// <param name="newPath">The new absolute path.</param> /// <returns> /// true if processing should continue after the method returns; false if the caller should return S_OK. /// Note that on errors an exception is thrown. /// </returns> protected virtual bool VerifyCaption(string newCaption, string newPath) { if (!this.CaptionEditable) { Tracer.Fail("SetCaption should not be called when the caption is not editable."); return(false); } // If the caption is exactly the same, then there's no need to do anything. bool differInCaseOnly; if (PackageUtility.FileStringEquals(this.Caption, newCaption, out differInCaseOnly) && !differInCaseOnly) { return(false); } // Make sure the new caption is a valid file name. if (!PackageUtility.IsValidFileOrFolderName(newCaption)) { throw new InvalidOperationException(SconceStrings.ErrorInvalidFileOrFolderName); } // If the old and the new caption differ in just case, then we won't do any // file moving since the file system is case-insensitive. We do want to allow // users to change the case on their captions, though. if (differInCaseOnly) { this.OnPropertyChanged(__VSHPROPID.VSHPROPID_Caption); return(false); } // Make sure the file doesn't already exist in the hierarchy or the file system. this.VerifyCaptionDoesNotExist(newCaption, newPath); // We don't want to do anything if we don't own the document. if (this.DocumentCookie != DocumentInfo.NullCookie && this.DocumentCookie != this.Hierarchy.RootNode.DocumentCookie) { DocumentInfo docInfo = Context.RunningDocumentTable.FindByCookie(this.DocumentCookie); if (docInfo.VisualStudioHierarhcy == null || !PackageUtility.IsSameComObject(docInfo.VisualStudioHierarhcy, (Hierarchy)this.Hierarchy)) { return(false); } } return(true); }
/// <summary> /// Removes the element at the specified index after <see cref="OnRemove"/> is called but /// before <see cref="OnRemoveComplete"/> is called. /// </summary> /// <param name="index">A zero-based index of the item to remove.</param> public void RemoveAt(int index) { if (this.IsReadOnly) { Tracer.Fail("The collection is read-only."); throw new NotSupportedException("Cannot remove from a read-only collection."); } object value = this.InnerList[index]; this.OnRemove(index, value); this.list.RemoveAt(index); this.OnRemoveComplete(index, value); // Raise the CollectionChanged event after completing the remove. this.OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, value)); }
/// <summary> /// Gets a string from the resource file and formats it using the specified arguments. /// </summary> /// <param name="name">The resource identifier of the string to retrieve.</param> /// <param name="args">An array of objects to use in the formatting. Can be null or empty.</param> /// <returns>A formatted string from the resource file.</returns> public string GetString(string name, params object[] args) { string returnString = this.missingManifestString; // If we previously tried to get a string from the resource file and we had a // MissingManifestResourceException, then we don't want to try again. Exceptions // are expensive especially when we could be getting lots of strings. if (!this.isMissingManifest) { try { // First give the subclass a chance to retrieve the string if (this.IsStringDefined(name)) { returnString = this.manager.GetString(name, CultureInfo.CurrentUICulture); } //\ Try getting the string from our assembly if the subclass can't handle it else if (SconceStrings.IsValidStringName(name)) { returnString = thisAssemblyManager.GetString(name, CultureInfo.CurrentUICulture); } else { Tracer.WriteLineWarning(classType, "GetString", "The string id '{0}' is not defined.", name); returnString = name; } // Format the message if there are arguments specified. Note that we format // using the CurrentCulture and not the CurrentUICulture (although in almost all // cases it will be the same). if (returnString != null && args != null && args.Length > 0) { returnString = String.Format(CultureInfo.CurrentCulture, returnString, args); } } catch (MissingManifestResourceException e) { this.isMissingManifest = true; Tracer.Fail("The resource cannot be found in the assembly: {0}", e); } } return(returnString); }
/// <summary> /// Shows the context menu when a user right-mouse clicks on the node. /// </summary> public virtual void ShowContextMenu() { int menuId = (int)this.VisualStudioContextMenuId; if (menuId != VsMenus.IDM_VS_CTXT_NOCOMMANDS) { // Tell the Visual Studio shell to show the context menu. Point menuLocation = Cursor.Position; POINTS[] vsPoints = new POINTS[1]; vsPoints[0].x = (short)menuLocation.X; vsPoints[0].y = (short)menuLocation.Y; Guid activeMenuGuid = VsMenus.SHLMainMenu; IVsUIShell uiShell = this.ServiceProvider.GetVsUIShell(classType, "ShowContextMenu"); int hr = uiShell.ShowContextMenu(0, ref activeMenuGuid, menuId, vsPoints, this.Hierarchy); if (NativeMethods.Failed(hr)) { Tracer.Fail("Error in showing the context menu: 0x{0:x}", hr); NativeMethods.ThrowOnFailure(hr); } } }
/// <summary> /// Reads the <BuildSettings> node. /// </summary> /// <param name="node">The <see cref="XmlNode"/> to read.</param> /// <returns>true if the node was read correctly; otherwise, false.</returns> protected virtual bool ReadBuildSettingsNode(XmlNode node) { // Make sure we're reading the expected node. if (!this.VerifyNode(node, ElementNames.BuildSettings)) { Tracer.Fail("Getting to this point indicates a bug."); return(false); } // Get the required attributes. string outputName; if (!this.GetRequiredAttribute(node, AttributeNames.OutputName, out outputName)) { return(false); } // Set the properties on the BuildSettings object. this.Project.BuildSettings.OutputName = outputName; return(true); }
/// <summary> /// Starts the specified build operation on the project for the currently selected project configuration. /// </summary> /// <param name="operation">The operation to perform.</param> public void StartBuild(BuildOperation operation) { Tracer.VerifyEnumArgument((int)operation, "operation", typeof(BuildOperation)); // We have to verify that the environment is not busy right now if (Package.Instance.Context.IsSolutionBuilding) { Tracer.WriteLineVerbose(classType, "StartBuild", "The build manager is busy right now."); return; } // Get the build manager from VS IVsSolutionBuildManager solutionBuildMgr = this.ServiceProvider.GetServiceOrThrow(typeof(SVsSolutionBuildManager), typeof(IVsSolutionBuildManager), classType, "StartBuild") as IVsSolutionBuildManager; // Convert the enum to one of the VS flags VSSOLNBUILDUPDATEFLAGS flags = VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_NONE; switch (operation) { case BuildOperation.Clean: flags |= VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_CLEAN; break; case BuildOperation.Build: flags |= VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD; break; case BuildOperation.Rebuild: flags |= VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_CLEAN | VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD; break; default: Tracer.Fail("Unknown BuildOperation '{0}'", operation.ToString()); return; } NativeMethods.ThrowOnFailure(solutionBuildMgr.StartSimpleUpdateProjectConfiguration((IVsHierarchy)this, null, null, (uint)flags, 0, 0)); }
/// <summary> /// Initializes the VSPackage with a back pointer to the environment. This is the entry point /// for the Visual Studio package. /// </summary> /// <param name="sp"> /// Pointer to the <see cref="IOleServiceProvider"/> interface through which the /// VSPackage can query for services. /// </param> /// <returns>An HRESULT indicating the result of the call.</returns> int IVsPackage.SetSite(IOleServiceProvider sp) { if (this.Closed) { Tracer.Fail("We shouldn't have been called if we're being unloaded."); return(NativeMethods.E_UNEXPECTED); } try { if (sp != null) { // If SetSite has been called more than once, it's an error. if (this.Context != null) { string message = this.Context.NativeResources.GetString(ResId.IDS_E_SITEALREADYSET, this.GetType().FullName); Tracer.Fail(message); throw new InvalidOperationException(message); } // Initialize the ServiceProvider and ourself. ServiceProvider contextServiceProvider = new ServiceProvider(sp); this.context = this.CreatePackageContext(contextServiceProvider); Tracer.Initialize(this.context); this.Initialize(); } else if (this.Context != null && this.Context.ServiceProvider != null) { this.Dispose(true); } } catch (Exception e) { Tracer.Fail("Unexpected exception: {0}\n{1}", e.Message, e); throw; } return(NativeMethods.S_OK); }
int IPersistFileFormat.Save(string pszFilename, int fRemember, uint nFormatIndex) { // Check the file name. if (!PackageUtility.FileStringEquals(pszFilename, this.FilePath)) { // TODO: Show the following error message to the user: "******" where 0=the AbsoluteDirectory. string message = PackageUtility.SafeStringFormatInvariant("Cannot perform a Save As operation on the project file to another location. Filename={0}", pszFilename); Tracer.Fail(message); throw new ArgumentException(message, "pszFilename"); } Encoding encoding; switch (nFormatIndex) { case 0: encoding = Encoding.UTF8; break; case 1: encoding = Encoding.Default; break; case 2: encoding = Encoding.Unicode; break; default: Tracer.Fail("Unknown format index {0}", nFormatIndex); encoding = Encoding.Default; break; } // Save the project if it's dirty. this.Serializer.Save(encoding, false); return(NativeMethods.S_OK); }
/// <summary> /// Reads the <File> node. /// </summary> /// <param name="node">The <see cref="XmlNode"/> to read.</param> /// <returns>true if the node was read correctly; otherwise, false.</returns> protected bool ReadFileNode(XmlNode node) { if (!this.VerifyNode(node, ElementNames.File)) { Tracer.Fail("Getting to this point indicates a bug."); return(false); } // <File RelativePath="path" /> string relativePath; if (!this.GetRequiredAttribute(node, AttributeNames.RelativePath, out relativePath)) { return(false); } if (this.Project.AddExistingFile(relativePath, false) == null) { return(false); } return(true); }
int IVsProject3.OpenItemWithSpecific(uint itemid, uint grfEditorFlags, ref Guid rguidEditorType, string pszPhysicalView, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) { ppWindowFrame = null; FileNode node = this.GetNode(itemid, false) as FileNode; if (node == null) { Tracer.Fail("The framework is calling us in an unexpected way because we report that we don't own the item '{0}' but Visual Studio thinks we do.", itemid); return(NativeMethods.E_UNEXPECTED); } // Map the raw logical view guid to one of our predetermined ones. VsLogicalView view; if (!VsLogicalView.TryFromGuid(rguidLogicalView, out view)) { Tracer.WriteLine(classType, "IVsProject3.OpenItemWithSpecific", Tracer.Level.Warning, "We're getting a logical view that we don't understand: '{0}'. Using the primary view instead.", rguidLogicalView.ToString("B")); view = VsLogicalView.Primary; } // Do we open with the standard or a specific editor? bool openWithSpecificEditor = ((((__VSSPECIFICEDITORFLAGS)grfEditorFlags) & __VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_UseEditor) == __VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_UseEditor); // Tell the node to open itself. if (openWithSpecificEditor) { ppWindowFrame = node.OpenWithSpecificEditor(view, punkDocDataExisting, pszPhysicalView, rguidEditorType); } else { ppWindowFrame = node.OpenWithStandardEditor(view, punkDocDataExisting); } return(NativeMethods.S_OK); }
int IVsProject3.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen, string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult) { bool canceled = false; bool wereErrors = false; pResult[0] = VSADDRESULT.ADDRESULT_Failure; // Get the parent node to which it should be added. FolderNode parentNode = this.GetNode(itemidLoc, true) as FolderNode; if (parentNode == null) { string message = this.NativeResources.GetString(ResId.IDS_E_ADDITEMTOPROJECT, Path.GetFileName(this.FilePath)); Context.ShowErrorMessageBox(message); Tracer.Fail("The specified parent {0} is not a FolderNode so we can't add an item to it.", itemidLoc); return(NativeMethods.E_UNEXPECTED); } // Loop through the files that are to be added and add them, one by one. foreach (string sourcePath in rgpszFilesToOpen) { string destPath = null; Node addedNode = null; switch (dwAddItemOperation) { case VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE: destPath = Path.Combine(parentNode.AbsoluteDirectory, pszItemName); addedNode = this.AddCopyOfFile(sourcePath, destPath, out canceled); break; case VSADDITEMOPERATION.VSADDITEMOP_OPENFILE: if (PackageUtility.IsRelative(this.RootDirectory, sourcePath)) { destPath = PackageUtility.MakeRelative(this.RootDirectory, sourcePath); addedNode = this.AddExistingFile(destPath, true); } else { destPath = Path.Combine(parentNode.AbsoluteDirectory, Path.GetFileName(sourcePath)); addedNode = this.AddCopyOfFile(sourcePath, destPath, out canceled); } break; case VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE: Tracer.Fail("NYI: VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE."); throw new NotImplementedException("Linking to files is not supported yet."); case VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD: Tracer.Fail("NYI: VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD."); throw new NotImplementedException("Running a wizard is not supported yet."); default: Tracer.Fail("Unknown VSADDDITEMOPERATION '{0}'", dwAddItemOperation); throw new ArgumentException(PackageUtility.SafeStringFormatInvariant("The dwAddItemOperation contains an unknown and unsupported value '{0}'.", dwAddItemOperation), "dwAddItemOperation"); } // There were errors if the node is still null at this point. wereErrors = (addedNode == null); } pResult[0] = (canceled ? VSADDRESULT.ADDRESULT_Cancel : (wereErrors ? VSADDRESULT.ADDRESULT_Failure : VSADDRESULT.ADDRESULT_Success)); return(NativeMethods.S_OK); }
/// <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; } }