/// <summary>
        /// Shows a preview of the transformation in a temporary file.
        /// </summary>
        /// <param name="hier">Current IVsHierarchy</param>
        /// <param name="sourceFile">Full path to the file to be trasnformed</param>
        /// <param name="transformFile">Full path to the transformation file</param>
        private void PreviewTransform(IVsHierarchy hier, string sourceFile, string transformFile)
        {
            if (string.IsNullOrWhiteSpace(sourceFile))
            {
                throw new ArgumentNullException("sourceFile");
            }

            if (string.IsNullOrWhiteSpace(transformFile))
            {
                throw new ArgumentNullException("transformFile");
            }

            if (!File.Exists(sourceFile))
            {
                throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_SourceFileNotFound, sourceFile), sourceFile);
            }

            if (!File.Exists(transformFile))
            {
                throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Error_TransformFileNotFound, transformFile), transformFile);
            }

            // Get our options
            using (OptionsDialogPage optionsPage = new OptionsDialogPage())
            {
                optionsPage.LoadSettingsFromStorage();

                this.LogMessageWriteLineFormat("SlowCheetah PreviewTransform");
                FileInfo sourceFileInfo = new FileInfo(sourceFile);

                // dest file
                string destFile = PackageUtilities.GetTempFilename(true, sourceFileInfo.Extension);
                this.TempFilesCreated.Add(destFile);

                // perform the transform and then display the result into the diffmerge tool that comes with VS.
                // If for some reason we can't find it, we just open it in an editor window
                this.errorListProvider.Tasks.Clear();
                ITransformationLogger logger      = new TransformationPreviewLogger(this.errorListProvider, hier);
                ITransformer          transformer = new XmlTransformer(logger, false);
                if (!transformer.Transform(sourceFile, transformFile, destFile))
                {
                    throw new TransformFailedException(Resources.Resources.TransformPreview_ErrorMessage);
                }

                // Does the customer want a preview?
                if (optionsPage.EnablePreview == false)
                {
                    ProjectUtilities.GetDTE().ItemOperations.OpenFile(destFile);
                }
                else
                {
                    // If the diffmerge service is available (dev11) and no diff tool is specified, or diffmerge.exe is specifed we use the service
                    if (this.GetService(typeof(SVsDifferenceService)) is IVsDifferenceService diffService && (string.IsNullOrEmpty(optionsPage.PreviewToolExecutablePath) || optionsPage.PreviewToolExecutablePath.EndsWith(@"\diffmerge.exe", StringComparison.OrdinalIgnoreCase)))
                    {
                        string sourceName = Path.GetFileName(sourceFile);
                        string leftLabel  = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_LeftLabel, sourceName);
                        string rightLabel = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_RightLabel, sourceName, Path.GetFileName(transformFile));
                        string caption    = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_Caption, sourceName);
                        string tooltip    = string.Format(CultureInfo.CurrentCulture, Resources.Resources.TransformPreview_ToolTip, sourceName);
                        diffService.OpenComparisonWindow2(sourceFile, destFile, caption, tooltip, leftLabel, rightLabel, null, null, (uint)__VSDIFFSERVICEOPTIONS.VSDIFFOPT_RightFileIsTemporary);
                    }
Esempio n. 2
0
        /// <summary>
        /// Gets all project configurations
        /// </summary>
        /// <param name="hierarchy">Current project hierarchy</param>
        /// <returns>List of configuration names for that project</returns>
        public static IEnumerable <string> GetProjectConfigurations(IVsHierarchy hierarchy)
        {
            Project project = PackageUtilities.GetAutomationFromHierarchy <Project>(hierarchy, (uint)VSConstants.VSITEMID.Root);

            return(GetProjectConfigurations(project));
        }
        /// <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>
        /// <param name="sender">The object that fired the event</param>
        /// <param name="e">Event arguments</param>
        private void OnAddTransformCommand(object sender, EventArgs e)
        {
            uint itemid = VSConstants.VSITEMID_NIL;

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

            IVsProject vsProject = (IVsProject)hierarchy;

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

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

            IVsBuildPropertyStorage buildPropertyStorage = vsProject as IVsBuildPropertyStorage;

            if (buildPropertyStorage == null)
            {
                this.LogMessageWriteLineFormat("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)Package.GetGlobalService(typeof(SVsSolution));
            int         hr       = solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, hierarchy, 0);

            if (ErrorHandler.Failed(hr))
            {
                throw new COMException(string.Format(Resources.Resources.Error_SavingProjectFile, itemFullPath, this.GetErrorInfo()), 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, TransformOnBuild, "true");

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

                string content = this.BuildXdtContent(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);
                }

                foreach (string config in transformsToCreate)
                {
                    string itemName = string.Format(Resources.Resources.String_FormatTransformFilename, itemFilename, config, itemExtension);
                    this.AddXdtTransformFile(selectedProjectItem, content, itemName, itemFolder);
                    hierarchy.ParseCanonicalName(Path.Combine(itemFolder, itemName), out uint addedFileId);
                    buildPropertyStorage.SetItemAttribute(addedFileId, IsTransformFile, "True");
                    buildPropertyStorage.SetItemAttribute(addedFileId, DependentUpon, itemFilenameExtension);
                }
            }
        }