Beispiel #1
0
        void SetBuildProperties(string inputFileName, ProjectItem item)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                string uniqueName = item.ContainingProject.UniqueName;

                IVsSolution solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution));

                IVsHierarchy hierarchy;
                solution.GetProjectOfUniqueName(uniqueName, out hierarchy);

                IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

                if (buildPropertyStorage != null)
                {
                    string fullPath = Path.ChangeExtension(inputFileName, GetDefaultExtension());

                    uint itemId;
                    hierarchy.ParseCanonicalName(fullPath, out itemId);

                    buildPropertyStorage.SetItemAttribute(itemId, "MergeWithCTO", "true");
                    buildPropertyStorage.SetItemAttribute(itemId, "ManifestResourceName", "VSPackage");
                }
            }), DispatcherPriority.ApplicationIdle, null);
        }
 public static void SetItemAttribute(this IVsBuildPropertyStorage propertyStorage, uint item, string name, bool value, bool defaultValue)
 {
     if (value != defaultValue)
     {
         propertyStorage.SetItemAttribute(item, name, value.ToString().ToLowerInvariant());
     }
     else
     {
         propertyStorage.SetItemAttribute(item, name, null);
     }
 }
Beispiel #3
0
 public static void SetItemAttribute(this IVsBuildPropertyStorage propertyStorage, uint item, string name, string value, string defaultValue)
 {
     if (value != defaultValue)
     {
         propertyStorage.SetItemAttribute(item, name, value);
     }
     else
     {
         propertyStorage.SetItemAttribute(item, name, null);
     }
 }
Beispiel #4
0
        /// <summary>
        /// Creates a new transformation file and adds it to the project.
        /// </summary>
        /// <param name="hierarchy">The project hierarchy</param>
        /// <param name="selectedProjectItem">The selected item to be transformed</param>
        /// <param name="itemName">Full name of the transformation file</param>
        /// <param name="projectPath">Full path to the current project</param>
        /// <param name="addDependentUpon">Wheter to add the new file dependent upon the source file</param>
        private void AddTransformFile(
            IVsHierarchy hierarchy,
            ProjectItem selectedProjectItem,
            string itemName,
            string projectPath,
            bool addDependentUpon)
        {
            try
            {
                string transformPath  = Path.Combine(projectPath, itemName);
                string sourceFileName = selectedProjectItem.FileNames[1];

                ITransformer transformer = TransformerFactory.GetTransformer(sourceFileName, null);

                transformer.CreateTransformFile(sourceFileName, transformPath, false);

                // Add the file to the project
                // If the DependentUpon metadata is required, add it under the original file
                // If not, add it to the project
                ProjectItem addedItem = addDependentUpon ? selectedProjectItem.ProjectItems.AddFromFile(transformPath)
                                                      : selectedProjectItem.ContainingProject.ProjectItems.AddFromFile(transformPath);

                // We need to set the Build Action to None to ensure that it doesn't get published for web projects
                addedItem.Properties.Item("ItemType").Value = "None";

                IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

                if (buildPropertyStorage == null)
                {
                    this.logger.LogMessage("Error obtaining IVsBuildPropertyStorage from hierarcy.");
                }
                else if (ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(addedItem.FileNames[0], out uint addedItemId)))
                {
                    buildPropertyStorage.SetItemAttribute(addedItemId, SlowCheetahPackage.IsTransformFile, "true");

                    if (addDependentUpon)
                    {
                        // Not all projects (like CPS) set the dependent upon metadata when using the automation object
                        buildPropertyStorage.GetItemAttribute(addedItemId, SlowCheetahPackage.DependentUpon, out string dependentUponValue);
                        if (string.IsNullOrEmpty(dependentUponValue))
                        {
                            // It didm not set it
                            buildPropertyStorage.SetItemAttribute(addedItemId, SlowCheetahPackage.DependentUpon, selectedProjectItem.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.LogMessage("AddTransformFile: Exception> " + ex.Message);
            }
        }
        /// <summary>
        /// Sets the known properties for the <see cref="ProjectItem"/> added to solution.
        /// </summary>
        /// <param name="projectItem">
        /// A <see cref="ProjectItem"/> that represents the generated item in the solution.
        /// </param>
        /// <param name="output">
        /// An <see cref="OutputFile"/> that holds metadata about the <see cref="ProjectItem"/> to be added to the solution.
        /// </param>
        private static void SetProjectItemBuildProperties(ProjectItem projectItem, OutputFile output)
        {
            if (output.BuildProperties.Count > 0)
            {
                // Get access to the build property storage service
                IServiceProvider serviceProvider = (IServiceProvider)Host;
                IVsSolution      solution        = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution));
                IVsHierarchy     hierarchy;
                ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(projectItem.ContainingProject.UniqueName, out hierarchy));
                IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
                if (buildPropertyStorage == null)
                {
                    throw new TransformationException(
                              string.Format(
                                  CultureInfo.CurrentCulture,
                                  "Project {0} does not support build properties required by {1}",
                                  projectItem.ContainingProject.Name,
                                  projectItem.Name));
                }

                // Find the target project item in the property storage
                uint projectItemId;
                ErrorHandler.ThrowOnFailure(hierarchy.ParseCanonicalName(projectItem.get_FileNames(1), out projectItemId));

                // Set build projerties for the target project item
                foreach (KeyValuePair <string, string> buildProperty in output.BuildProperties)
                {
                    ErrorHandler.ThrowOnFailure(buildPropertyStorage.SetItemAttribute(projectItemId, buildProperty.Key, buildProperty.Value));
                }
            }
        }
        int IVsBuildPropertyStorage.SetItemAttribute(uint item, string attributeName, string attributeValue)
        {
            IVsBuildPropertyStorage cfg = _innerCfg as IVsBuildPropertyStorage;

            if (cfg != null)
            {
                return(cfg.SetItemAttribute(item, attributeName, attributeValue));
            }
            return(VSConstants.S_OK);
        }
        private void SaveRunCustomToolOn(string[] items)
        {
            string s = null;

            if (items != null)
            {
                s = string.Join(";", items);
            }
            _storage.SetItemAttribute(_itemId, AutoRunCustomToolPackage.TargetsPropertyName, s);
        }
        public static void SetProjectItemProperty(IVsSolution solution, ProjectItem projectItem, string propertyName, string propertyValue)
        {
            IVsHierarchy            hierarchy            = GetHierarchy(solution, projectItem.ContainingProject);
            IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
            uint   itemId;
            string fullPath = (string)projectItem.Properties.Item("FullPath").Value;

            hierarchy.ParseCanonicalName(fullPath, out itemId);
            buildPropertyStorage.SetItemAttribute(itemId, propertyName, propertyValue);
        }
        protected void Set <T>(T value = default(T), [CallerMemberName] string name = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (!_isInitialized)
            {
                return;
            }

            var serializedValue = Convert.ToString(value);

            _storage.SetItemAttribute(_itemId, Scope(name), serializedValue);
        }
Beispiel #10
0
    internal static void SetIncludeInVsix(IServiceProvider provider, ProjectItem projectItem, bool value)
    {
        string      projectUniqueName = projectItem.ContainingProject.UniqueName;
        IVsSolution vsSolution        = (IVsSolution)provider.GetService(typeof(SVsSolution));

        if (vsSolution != null)
        {
            IVsHierarchy hierarchy;
            uint         projectItemId;
            vsSolution.GetProjectOfUniqueName(projectUniqueName, out hierarchy);
            hierarchy.ParseCanonicalName(projectItem.get_FileNames(0), out projectItemId);
            IVsBuildPropertyStorage storage = hierarchy as IVsBuildPropertyStorage;
            if (hierarchy != null)
            {
                storage.SetItemAttribute(projectItemId, "IncludeInVSIX", value.ToString().ToLower());
            }
        }
    }
Beispiel #11
0
        public bool SetValue(string name, object value)
        {
            if (value == null)
            {
                throw new ArgumentException(Strings.ItemProperties.InvalidNullValue(name), "value");
            }

            if (item != null)
            {
                Property property;
                try
                {
                    property = item.Properties.Item(name);
                }
                catch (ArgumentException)
                {
                    property = null;
                }

                if (property != null)
                {
                    try
                    {
                        property.Value = value;
                        return(true);
                    }
                    catch
                    {
                        return(false);
                    }
                }
            }

            // Fallback to MSBuild item properties.
            if (msBuild != null)
            {
                return(ErrorHandler.Succeeded(
                           msBuild.SetItemAttribute(node.HierarchyIdentity.ItemID, name, value.ToString())));
            }

            return(false);
        }
Beispiel #12
0
        private static void IncludeManifestInProjectAndVsix(Project project, string fileName)
        {
            var item = project.AddFileToProject(fileName, "Content");

            IVsSolution solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution));

            IVsHierarchy hierarchy;

            solution.GetProjectOfUniqueName(item.ContainingProject.UniqueName, out hierarchy);

            IVsBuildPropertyStorage buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;

            if (buildPropertyStorage != null)
            {
                uint itemId;
                hierarchy.ParseCanonicalName(fileName, out itemId);

                buildPropertyStorage.SetItemAttribute(itemId, "IncludeInVSIX", "true");
            }
        }
Beispiel #13
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                PropertyInfo buildProjectInfo = typeof(VisualStudio.Project.ProjectNode).GetProperty("BuildProject", BindingFlags.Instance | BindingFlags.NonPublic);
                Microsoft.Build.Evaluation.Project buildProject = buildProjectInfo.GetValue(testEnv.Project, new object[0]) as Microsoft.Build.Evaluation.Project;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                MethodInfo itemMapGetter           = typeof(VisualStudio.Project.ProjectNode).GetProperty("ItemIdMap", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true);
                Microsoft.VisualStudio.Shell.EventSinkCollection itemMap = (Microsoft.VisualStudio.Shell.EventSinkCollection)itemMapGetter.Invoke(testEnv.Project, new object[0]);
                uint itemID = itemMap.Add(node);

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Beispiel #14
0
        public void FileProperties()
        {
            using (PackageTestEnvironment testEnv = new PackageTestEnvironment())
            {
                Microsoft.Build.Evaluation.Project buildProject = testEnv.Project.BuildProject;

                // Add a node to the project map so it can be resolved
                IEnumerable <Microsoft.Build.Evaluation.ProjectItem> itemGroup = buildProject.GetItems("Compile");
                Microsoft.Build.Evaluation.ProjectItem item = null;
                foreach (Microsoft.Build.Evaluation.ProjectItem currentItem in itemGroup)
                {
                    if (currentItem.EvaluatedInclude == "OtherFile.cs")
                    {
                        item = currentItem;
                        break;
                    }
                }
                VisualStudio.Project.FileNode node = new VisualStudio.Project.FileNode(testEnv.Project, testEnv.Project.GetProjectElement(item));
                uint itemID = node.Id;

                IVsBuildPropertyStorage buildProperty = testEnv.Project as IVsBuildPropertyStorage;
                Assert.IsNotNull(buildProperty, "Project does not implements IVsBuildPropertyStorage.");
                // Get
                string propertyName = "Metadata";
                string value        = null;
                int    hr           = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual("OtherFileProperty", value);

                // Set (with get to confirm)
                string newValue = "UpdatedFileProperty";
                hr = buildProperty.SetItemAttribute(itemID, propertyName, newValue);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "SetPropertyValue failed");
                hr = buildProperty.GetItemAttribute(itemID, propertyName, out value);
                Assert.AreEqual <int>(VSConstants.S_OK, hr, "GetItemAttribute failed");
                Assert.AreEqual(newValue, value);
            }
        }
Beispiel #15
0
        private void OnAfterAddedGrammarHelperFile(IVsProject project, string currentFile)
        {
            int found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemId;

            if (ErrorHandler.Failed(project.IsDocumentInProject(currentFile, out found, priority, out itemId)))
            {
                return;
            }

            if (found == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard)
            {
                return;
            }

            IVsHierarchy            hierarchy            = project as IVsHierarchy;
            IVsBuildPropertyStorage buildPropertyStorage = project as IVsBuildPropertyStorage;

            if (hierarchy != null && buildPropertyStorage != null)
            {
                string dependentUpon;
                if (ErrorHandler.Failed(buildPropertyStorage.GetItemAttribute(itemId, "DependentUpon", out dependentUpon)))
                {
                    string[] stripExtensions = { ".cs", ".lexer", ".parser" };
                    string   parentFileName  = Path.GetFileName(currentFile);
                    while (!string.IsNullOrWhiteSpace(parentFileName) && Array.IndexOf(stripExtensions, Path.GetExtension(parentFileName).ToLowerInvariant()) >= 0)
                    {
                        parentFileName = Path.GetFileNameWithoutExtension(parentFileName);
                    }

                    int hr = buildPropertyStorage.SetItemAttribute(itemId, "DependentUpon", parentFileName);
                }
            }
        }
        /// <summary>
        /// Code from Xsd2Code.Addin::Connect
        /// </summary>
        private void openConfigurationWindow()
        {
            ProjectItem proitem          = Dte.SelectedItems.Item(1).ProjectItem;
            Project     proj             = proitem.ContainingProject;
            string      projectDirectory = Path.GetDirectoryName(proj.FullName);

            // Try to get default nameSpace
            string defaultNamespace = string.Empty;
            uint?  targetFramework  = 0;
            bool?  isSilverlightApp = false;

            try
            {
                defaultNamespace = proj.Properties.Item("DefaultNamespace").Value as string;
                targetFramework  = proj.Properties.Item("TargetFramework").Value as uint?;
                isSilverlightApp = proj.Properties.Item("SilverlightProject.IsSilverlightApplication").Value as bool?;
            }
            catch
            {
            }

            string xsdFileName = proitem.FileNames[0];

            try
            {
                proitem.Save(xsdFileName);
            }
            catch (Exception)
            {
            }

            TargetFramework framework = TargetFramework.Net20;

            if (targetFramework.HasValue)
            {
                uint target = targetFramework.Value;
                switch (target)
                {
                case 196608:
                    framework = TargetFramework.Net30;
                    break;

                case 196613:
                    framework = TargetFramework.Net35;
                    break;

                case 262144:
                    framework = TargetFramework.Net40;
                    break;
                }
            }
            if (isSilverlightApp.HasValue)
            {
                if (isSilverlightApp.Value)
                {
                    framework = TargetFramework.Silverlight;
                }
            }

            // We associate an outputfile with the selected XSD file to know were to look for the parameters
            // TODO embed all the parameters as attributes of the XSD file in the project ?
            IVsHierarchy            hierarchy = null;
            uint                    itemid;
            string                  outputFile           = null;
            IVsBuildPropertyStorage buildPropertyStorage = null;

            if (IsSingleProjectItemSelection(out hierarchy, out itemid))
            {
                buildPropertyStorage = hierarchy as IVsBuildPropertyStorage;
                if (buildPropertyStorage != null)
                {
                    buildPropertyStorage.GetItemAttribute(itemid, "Xsd2CodeOutputFile", out outputFile);
                }
            }

            var frm = new FormOption();

            frm.Init(xsdFileName, proj.CodeModel.Language, defaultNamespace, framework, Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile ?? string.Empty));

            DialogResult result = frm.ShowDialog();

            GeneratorParams generatorParams = frm.GeneratorParams.Clone();

            generatorParams.InputFilePath = xsdFileName;

            var gen = new GeneratorFacade(generatorParams);

            bool foundOutputFile = false;

            if (xsdFileName.Length > 0)
            {
                if (result == DialogResult.OK)
                {
                    // Close file if open in IDE
                    ProjectItem projElmts = null;
                    if (!String.IsNullOrEmpty(outputFile))
                    {
                        string rootedOutputFile = Path.IsPathRooted(outputFile) ? outputFile : Path.Combine(projectDirectory, outputFile);
                        foundOutputFile = FindInProject(proj.ProjectItems, rootedOutputFile, out projElmts);
                        if (foundOutputFile)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Close(vsSaveChanges.vsSaveChangesNo);
                        }
                    }

                    Result <List <string> > generateResult  = gen.Generate();
                    List <string>           outputFileNames = generateResult.Entity;

                    if (!generateResult.Success)
                    {
                        MessageBox.Show(generateResult.Messages.ToString(), "XSD2Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        string vsProjectOutputFilePath = outputFileNames[0];
                        // Save one of the output file path so we can read the parameters from it the next time
                        if (buildPropertyStorage != null)
                        {
                            buildPropertyStorage.SetItemAttribute(itemid, "Xsd2CodeOutputFile", GetRelativePath(vsProjectOutputFilePath, projectDirectory));
                        }

                        // try again now that the generation occured
                        string newRootedOutputFile = Path.Combine(projectDirectory, vsProjectOutputFilePath);
                        foundOutputFile = FindInProject(proj.ProjectItems, newRootedOutputFile, out projElmts);
                        if (!foundOutputFile)
                        {
                            projElmts = proj.ProjectItems.AddFromFile(newRootedOutputFile);
                        }


                        if (frm.OpenAfterGeneration && projElmts != null)
                        {
                            Window window = projElmts.Open(EnvDTE.Constants.vsViewKindCode);
                            window.Activate();
                            window.SetFocus();

                            try
                            {
                                // this.applicationObjectField.DTE.ExecuteCommand("Edit.RemoveAndSort", "");
                                Dte.ExecuteCommand("Edit.FormatDocument", string.Empty);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            return;
        }
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void OnAddTransformCommand(object sender, EventArgs e)
        {
            IVsHierarchy hierarchy = null;
            uint         itemid    = VSConstants.VSITEMID_NIL;

            if (!IsSingleProjectItemSelection(out hierarchy, out itemid))
            {
                return;
            }

            IVsProject vsProject = (IVsProject)hierarchy;

            if (!ProjectSupportsTransforms(vsProject))
            {
                return;
            }

            string projectFullPath = null;

            if (ErrorHandler.Failed(vsProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out projectFullPath)))
            {
                return;
            }

            // build the import path
            string localAppData    = Settings.Default.InstallUserFolderMSBuild;
            string installPath     = Settings.Default.InstallPath;
            string targetsFilename = Settings.Default.TargetsFilename;
            string importPath      = Path.Combine(localAppData, installPath, targetsFilename);

            IVsBuildPropertyStorage buildPropertyStorage = vsProject as IVsBuildPropertyStorage;

            if (buildPropertyStorage == null)
            {
                this.LogMessageWriteLineFormat("Error obtaining IVsBuildPropertyStorage from hierarcy.");
                return;
            }

            bool addImports;

            if (!ValidateSlowCheetahTargetsAvailable(buildPropertyStorage, projectFullPath, importPath, out addImports))
            {
                return;
            }

            // get the name of the item
            string itemFullPath = null;

            if (ErrorHandler.Failed(vsProject.GetMkDocument(itemid, out itemFullPath)))
            {
                return;
            }

            // Save the project file
            IVsSolution solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution));
            int         hr       = solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, hierarchy, 0);

            if (Failed(hr))
            {
                throw new COMException(string.Format(Resources.Error_SavingProjectFile, itemFullPath, GetErrorInfo()), hr);
            }
            ProjectItem selectedProjectItem = GetProjectItemFromHierarchy(hierarchy, itemid);

            if (selectedProjectItem != null)
            {
                // need to enure that this item has metadata TransformOnBuild set to true
                if (buildPropertyStorage != null)
                {
                    buildPropertyStorage.SetItemAttribute(itemid, TransformOnBuild, "true");
                }

                string itemFolder    = Path.GetDirectoryName(itemFullPath);
                string itemFilename  = Path.GetFileNameWithoutExtension(itemFullPath);
                string itemExtension = Path.GetExtension(itemFullPath);

                string   content = BuildXdtContent(itemFullPath);
                string[] configs = GetProjectConfigurations(selectedProjectItem.ContainingProject);
                foreach (string config in configs)
                {
                    string itemName = string.Format(Resources.String_FormatTransformFilename, itemFilename, config, itemExtension);
                    AddXdtTransformFile(selectedProjectItem, content, itemName, itemFolder);
                    uint addedFileId;
                    hierarchy.ParseCanonicalName(Path.Combine(itemFolder, itemName), out addedFileId);
                    buildPropertyStorage.SetItemAttribute(addedFileId, IsTransformFile, "True");
                }
            }

            if (addImports)
            {
                AddSlowCheetahImport(projectFullPath, importPath);
            }
        }
Beispiel #18
0
        protected void SetMsBuildBool(String attributeName, bool value)
        {
            var valueStr = value ? "true" : ""; // "" - will remove attribute

            ErrorHandler.ThrowOnFailure(_storage.SetItemAttribute(_itemid, attributeName, valueStr));
        }
 public static void SetValue(IVsBuildPropertyStorage storage, uint itemId, string propertyName, object value)
 {
     storage.SetItemAttribute(itemId, propertyName, value.ToString());
 }
Beispiel #20
0
        /// <inheritdoc/>
        protected override void OnInvoke(object sender, EventArgs e)
        {
            uint itemid = VSConstants.VSITEMID_NIL;

            if (!ProjectUtilities.IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out itemid))
            {
                return;
            }

            IVsProject vsProject = (IVsProject)hierarchy;

            if (!this.package.ProjectSupportsTransforms(vsProject))
            {
                return;
            }

            if (ErrorHandler.Failed(vsProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out string projectFullPath)))
            {
                return;
            }

            IVsBuildPropertyStorage buildPropertyStorage = vsProject as IVsBuildPropertyStorage;

            if (buildPropertyStorage == null)
            {
                this.logger.LogMessage("Error obtaining IVsBuildPropertyStorage from hierarchy.");
                return;
            }

            // get the name of the item
            if (ErrorHandler.Failed(vsProject.GetMkDocument(itemid, out string itemFullPath)))
            {
                return;
            }

            // Save the project file
            IVsSolution solution = (IVsSolution)Shell.Package.GetGlobalService(typeof(SVsSolution));
            int         hr       = solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, hierarchy, 0);

            ErrorHandler.ThrowOnFailure(hr);

            ProjectItem selectedProjectItem = PackageUtilities.GetAutomationFromHierarchy <ProjectItem>(hierarchy, itemid);

            if (selectedProjectItem != null)
            {
                try
                {
                    selectedProjectItem.Save();
                }
                catch
                {
                    // If the item is not open, an exception is thrown,
                    // but that is not a problem as it is not dirty
                }

                // Checks the SlowCheetah NuGet package installation
                this.nuGetManager.CheckSlowCheetahInstallation(hierarchy);

                // need to enure that this item has metadata TransformOnBuild set to true
                buildPropertyStorage.SetItemAttribute(itemid, SlowCheetahPackage.TransformOnBuild, "true");

                string itemFolder            = Path.GetDirectoryName(itemFullPath);
                string itemFilename          = Path.GetFileNameWithoutExtension(itemFullPath);
                string itemExtension         = Path.GetExtension(itemFullPath);
                string itemFilenameExtension = Path.GetFileName(itemFullPath);

                IEnumerable <string> configs = ProjectUtilities.GetProjectConfigurations(selectedProjectItem.ContainingProject);

                List <string> transformsToCreate = null;
                if (configs != null)
                {
                    transformsToCreate = configs.ToList();
                }

                if (transformsToCreate == null)
                {
                    transformsToCreate = new List <string>();
                }

                // if it is a web project we should add publish profile specific transforms as well
                var publishProfileTransforms = this.GetPublishProfileTransforms(hierarchy, projectFullPath);
                if (publishProfileTransforms != null)
                {
                    transformsToCreate.AddRange(publishProfileTransforms);
                }

                using (OptionsDialogPage optionsPage = new OptionsDialogPage())
                {
                    optionsPage.LoadSettingsFromStorage();

                    foreach (string config in transformsToCreate)
                    {
                        string itemName = string.Format(CultureInfo.CurrentCulture, Resources.Resources.String_FormatTransformFilename, itemFilename, config, itemExtension);
                        this.AddTransformFile(selectedProjectItem, itemName, itemFolder, optionsPage.AddDependentUpon);
                        hierarchy.ParseCanonicalName(Path.Combine(itemFolder, itemName), out uint addedFileId);
                        buildPropertyStorage.SetItemAttribute(addedFileId, SlowCheetahPackage.IsTransformFile, "True");
                    }
                }
            }
        }
Beispiel #21
0
 private void SetBoolValue(bool WillRunCustomTool, string propertyName)
 {
     _storage.SetItemAttribute(_itemId, propertyName, WillRunCustomTool.ToString());
 }