Beispiel #1
0
        private void GetTemplate(string templateFile, ArrayList templates, Configuration.GuidancePackage guidancePackage)
        {
            IVsTemplate template = null;

            // HACK: we don't want to process VB templates if VB package isn't installed

            if (IsVbTemplate(templateFile) && !IsVsIsInstalled())
            {
                Trace.TraceInformation("The VS template '{0}' uses VB and VB isn't installed, skipping it...", templateFile);
                return;
            }

            if (guidancePackage != null)
            {
                RegisterTemplate(templateFile, guidancePackage.Name, new Guid(guidancePackage.Guid));
            }

            template = ((IVsTemplatesService)this).GetTemplate(templateFile);

            if (template != null)
            {
                templates.Add(template);
            }

            //IVsTemplate template = null;
            //if (guidancePackage != null)
            //{
            //    RegisterTemplate(templateFile, guidancePackage.Name, new Guid(guidancePackage.Guid));
            //}
            //template = ((IVsTemplatesService)this).GetTemplate(templateFile);
            //if (template != null)
            //{
            //    templates.Add(template);
            //}
        }
 public UnfoldParentResolver(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, IVsTemplate template)
 {
     this.solution = solution;
     this.uriService = uriService;
     this.currentElement = currentElement;
     this.theTemplate = template;
 }
Beispiel #3
0
        public static void RemoveWizardExtension(this IVsTemplate template, Type templateExtensionType)
        {
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => templateExtensionType, templateExtensionType);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            if (temp.WizardExtension == null)
            {
                return;
            }
            else
            {
                var extensionToRemove = temp.WizardExtension.FirstOrDefault(ext =>
                                                                            (ext.Assembly[0] as XmlNode[])[0].Value.Contains(templateExtensionType.Assembly.GetName().Name) &&
                                                                            (ext.FullClassName[0] as XmlNode[])[0].Value.Contains(templateExtensionType.Name));
                if (extensionToRemove != null)
                {
                    var existingExtensions = temp.WizardExtension.Except(new[] { extensionToRemove }).ToArray();
                    temp.WizardExtension = existingExtensions;
                    VsTemplateFile.Write(template);
                }
            }
        }
Beispiel #4
0
        private static string GetProjectItemUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => parent, parent);

            var directoryBase = System.IO.Path.GetDirectoryName(parent.PhysicalPath);
            var files         = Directory.EnumerateFiles(directoryBase);

            var contentProjectItem = template.TemplateContent.Items.OfType <VSTemplateTemplateContentProjectItem>().FirstOrDefault();

            if (contentProjectItem == null)
            {
                return(baseName);
            }

            var outputExtension = System.IO.Path.GetExtension(contentProjectItem.TargetFileName);

            var uniqueName = UniqueNameGenerator.EnsureUnique(
                baseName,
                newName => !files.Any(file => System.IO.Path.GetFileName(file).Equals(
                                          string.Format(CultureInfo.InvariantCulture, @"{0}{1}", System.IO.Path.GetFileNameWithoutExtension(newName), outputExtension),
                                          StringComparison.OrdinalIgnoreCase)));

            return(string.Format(
                       CultureInfo.InvariantCulture,
                       @"{0}{1}",
                       System.IO.Path.GetFileNameWithoutExtension(uniqueName),
                       System.IO.Path.GetExtension(baseName)));
        }
        private static string GetProjectItemUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => parent, parent);

            var directoryBase = System.IO.Path.GetDirectoryName(parent.PhysicalPath);
            var files = Directory.EnumerateFiles(directoryBase);

            var contentProjectItem = template.TemplateContent.Items.OfType<VSTemplateTemplateContentProjectItem>().FirstOrDefault();

            if (contentProjectItem == null)
            {
                return baseName;
            }

            var outputExtension = System.IO.Path.GetExtension(contentProjectItem.TargetFileName);

            var uniqueName = UniqueNameGenerator.EnsureUnique(
                baseName,
                newName => !files.Any(file => System.IO.Path.GetFileName(file).Equals(
                    string.Format(CultureInfo.InvariantCulture, @"{0}{1}", System.IO.Path.GetFileNameWithoutExtension(newName), outputExtension),
                    StringComparison.OrdinalIgnoreCase)));

            return string.Format(
                CultureInfo.InvariantCulture,
                @"{0}{1}",
                System.IO.Path.GetFileNameWithoutExtension(uniqueName),
                System.IO.Path.GetExtension(baseName));
        }
Beispiel #6
0
        /// <summary>
        /// Gets the <see cref="IVsTemplate"/> interface once it is sited.
        /// <seealso cref="AssetReference.OnSited"/>
        /// </summary>
        protected override void OnSited()
        {
            base.OnSited();
            IConfigurationService config = GetService <IConfigurationService>(true);

            // Only look for base path if it's relative.
            if (!Path.IsPathRooted(base.AssetName))
            {
                base.AssetName = new FileInfo(Path.Combine(
                                                  config.BasePath + @"\Templates\", base.AssetName)).FullName;
                base.AssetName = new CompatibleUri(base.AssetName).LocalPath;
            }
            if (!File.Exists(this.AssetName))
            {             // Template does not exist, check with the Guidance package and update the template path
                int    relPathStartBefore = 0;
                string probeTemplateName  = this.AssetName;
                while (!File.Exists(this.AssetName))
                {
                    int relPathStart = probeTemplateName.IndexOf(@"\Templates\", relPathStartBefore, StringComparison.InvariantCultureIgnoreCase);
                    if (relPathStart == -1 || relPathStart <= relPathStartBefore)
                    {
                        throw new FileNotFoundException(Properties.Resources.Templates_TemplateNotFound, this.AssetName);
                    }
                    relPathStartBefore = relPathStart;
                    string relPath = probeTemplateName.Substring(relPathStart + 1);
                    this.AssetName = Path.Combine(config.BasePath, relPath);
                }
            }
            IVsTemplatesService infosvc = GetService <IVsTemplatesService>(true);

            this.template = infosvc.GetTemplate(base.AssetName);
        }
 public UnfoldParentResolver(ISolution solution, IUriReferenceService uriService, IProductElement currentElement, IVsTemplate template)
 {
     this.solution       = solution;
     this.uriService     = uriService;
     this.currentElement = currentElement;
     this.theTemplate    = template;
 }
Beispiel #8
0
        /// <summary>
        /// Executes when the wizard starts.
        /// </summary>
        public virtual void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            Guard.NotNull(() => customParams, customParams);
            Guard.NotNull(() => replacementsDictionary, replacementsDictionary);

            this.TemplateFile = (string)customParams[0];
            this.TemplateSchema = VsTemplateFile.Read(this.TemplateFile);
            this.activity = tracer.StartActivity(Resources.TemplateWizard_Unfolding, this.GetType().Name, this.TemplateFile);
        }
Beispiel #9
0
        public static void SetTemplateId(this IVsTemplate template, string templateId)
        {
            Guard.NotNull(() => template, template);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            temp.TemplateData.TemplateID = templateId;
        }
Beispiel #10
0
        public static void SetName(this IVsTemplate template, string name)
        {
            Guard.NotNull(() => template, template);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            temp.TemplateData.Name.Value = name;
        }
Beispiel #11
0
        /// <summary>
        /// Executes when the wizard starts.
        /// </summary>
        public virtual void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            Guard.NotNull(() => customParams, customParams);
            Guard.NotNull(() => replacementsDictionary, replacementsDictionary);

            this.TemplateFile   = (string)customParams[0];
            this.TemplateSchema = VsTemplateFile.Read(this.TemplateFile);
            this.activity       = tracer.StartActivity(Resources.TemplateWizard_Unfolding, this.GetType().Name, this.TemplateFile);
        }
Beispiel #12
0
        public static void SetDefaultName(this IVsTemplate template, string defaultName)
        {
            Guard.NotNull(() => template, template);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            temp.TemplateData.DefaultName = defaultName;
        }
Beispiel #13
0
 private CommandID CreateBitmap(IVsTemplate template)
 {
     if (!string.IsNullOrEmpty(template.IconFileName))
     {
         string fileIcon = new FileInfo(template.FileName).Directory + "\\" + template.IconFileName;
         return(LoadBitmap(fileIcon));
     }
     return(ShellCmdDef.MapIconToBitmap(template.Icon));
 }
Beispiel #14
0
        public static void SetDescription(this IVsTemplate template, string description)
        {
            Guard.NotNull(() => template, template);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            temp.TemplateData.Description.Value = description;
        }
Beispiel #15
0
        public ProjectTemplate(MRUTemplateInfo2 info, IVsTemplate vsTemplateOrNull)
        {
            _info       = info;
            _vsTemplate = vsTemplateOrNull;

            this.Icon = vsTemplateOrNull?.MediumThumbnailImage; // ?? new BitmapImage(new Uri("/Nostalgia;Icons/NewFileCollection/NewFileCollection_16x.png", UriKind.Relative));

            this.IsPinned = info.IsPinned;
            this.Command  = new DelegateCommand(this.DoCreateProject);
        }
Beispiel #16
0
        private void AddTemplateCommand(IVsTemplate template)
        {
            if (template.Kind == TemplateKind.Solution)
            {
                return;
            }
            Configuration.RecipeHostData hostData = null;
            if (template.ExtensionData != null && !string.IsNullOrEmpty(template.ExtensionData.Recipe))
            {
                Configuration.Recipe recipeConfig = GetRecipeConfig(template.ExtensionData.Recipe);
                if (recipeConfig != null && recipeConfig.HostData != null && recipeConfig.HostData.CommandBar != null)
                {
                    hostData = recipeConfig.HostData;
                    // Set the host data to null to avoid registering two commands
                    recipeConfig.HostData = null;
                }
            }
            int       priority = CTCBuilder.defaultPriority;
            CommandID icon     = CreateBitmap(template);

            if (hostData != null)
            {
                hostData.Icon      = new Configuration.Icon();
                hostData.Icon.Guid = icon.Guid.ToString();
                hostData.Icon.ID   = icon.ID;
                priority           = hostData.Priority;
            }
            ;
            Button myButton = new Button(template.Command,
                                         this.PackageGroup.Group,
                                         priority,
                                         icon,
                                         CommandType.Button,
                                         Util.DisabledDefault,
                                         guidancePackage.Caption + "." + template.Name);

            AddCommand(myButton, hostData);
            if (hostData == null)
            {
                // Add the template command in the standard places
                CommandID parentCommand = null;
                if (template.Kind == TemplateKind.ProjectItem)
                {
                    parentCommand = ShellCmdDef.GetPredefinedCommandID(Configuration.CommandBarName.ProjectAdd);
                    AddGroupPlacement(myButton, parentCommand);
                }
                else if (template.Kind == TemplateKind.Project)
                {
                    parentCommand = ShellCmdDef.GetPredefinedCommandID(Configuration.CommandBarName.SolutionAdd);
                    AddGroupPlacement(myButton, parentCommand);
                }
                parentCommand = ShellCmdDef.GetPredefinedCommandID(Configuration.CommandBarName.SolutionFolderAdd);
                AddGroupPlacement(myButton, parentCommand);
            }
        }
Beispiel #17
0
        public static void SetHidden(this IVsTemplate template, bool hidden)
        {
            Guard.NotNull(() => template, template);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            temp.TemplateData.HiddenSpecified = hidden;
            temp.TemplateData.Hidden          = hidden;
            VsTemplateFile.Write(temp);
        }
Beispiel #18
0
        public TemplateMenuCommand(IVsTemplate template, GuidancePackage guidancePackage, Microsoft.Practices.ComponentModel.ServiceContainer serviceProvider)
            : base(guidancePackage, serviceProvider, template.Command)
        {
            this.template = template;
            string templateMenuName = String.Format(
                CultureInfo.CurrentCulture,
                Microsoft.Practices.RecipeFramework.VisualStudio.Properties.Resources.Templates_ContextMenu,
                this.template.Name);

            this.Text = templateMenuName;
        }
Beispiel #19
0
        public static void AddWizardExtension(this IVsTemplate template, string templateExtensionFullTypeName)
        {
            Guard.NotNull(() => template, template);
            Guard.NotNullOrEmpty(() => templateExtensionFullTypeName, templateExtensionFullTypeName);

            var templateType = Type.GetType(templateExtensionFullTypeName, false, true);

            if (templateType != null)
            {
                template.AddWizardExtension(templateType);
            }
        }
        private void ProcessT4Templates()
        {
            T4UnfoldAction action   = new T4UnfoldAction();
            UnfoldTemplate template = (UnfoldTemplate)UnfoldTemplate.UnfoldingTemplates.Peek();

            if (template.Template.VSKind == WizardRunKind.AsMultiProject)
            {
                // We dont process any T4 template for a multiproject template
                return;
            }
            try
            {
                package.Add(action);
                IConfigurationService configService = package.GetService <IConfigurationService>(true);
                IVsTemplate           vsTemplate    = template.Template;
                Configuration.Recipe  recipe        = null;
                if (vsTemplate != null && vsTemplate.ExtensionData != null && !string.IsNullOrEmpty(vsTemplate.ExtensionData.Recipe))
                {
                    recipe = configService.CurrentPackage[vsTemplate.ExtensionData.Recipe];
                }
                if (recipe != null && recipe.Arguments != null)
                {
                    IDictionaryService           dictService = GetService <IDictionaryService>();
                    PropertyDescriptorCollection properties  = TypeDescriptor.GetProperties(action);
                    foreach (Configuration.Argument recipeArg in recipe.Arguments)
                    {
                        object value = dictService.GetValue(recipeArg.Name);
                        properties[recipeArg.Name].SetValue(action, value);
                    }
                }
                action.Project = template.generatedProject;
                action.ProjectItemCollection = template.generatedItems;
                action.Execute();
            }
            catch (Exception ex)
            {
                // We will swallow the exception, the erroneous references did not get added
                ErrorHelper.Show(this, ex);
            }
            finally
            {
                if (action != null)
                {
                    package.Remove(action);
                    action.Dispose();
                    action = null;
                }
            }
        }
Beispiel #21
0
 private void LoadTemplateData(Dictionary <string, string> replacementsDictionary, string templateFileName)
 {
     try
     {
         templateFileName        = new CompatibleUri(templateFileName).LocalPath;
         this.templateDictionary = new TemplateDictionaryService(replacementsDictionary);
         IVsTemplatesService templatesService =
             (IVsTemplatesService)GetService(typeof(IVsTemplatesService));
         this.template = templatesService.GetTemplate(templateFileName);
     }
     catch (Exception e)
     {
         ErrorHelper.Show((IUIService)GetService(typeof(IUIService)), e, Properties.Resources.Templates_InvalidWizardData);
         throw new WizardCancelledException();
     }
 }
Beispiel #22
0
        /// <summary>
        /// Writes a .vstemplate file from the given instance.
        /// </summary>
        public static void Write(IVsTemplate templateInstance, string templateFilename)
        {
            var hasFragment = templateFilename.Contains('?');

            if (hasFragment || templateFilename.EndsWith(TemplateArchiveFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                var vsTemplateFileName = templateInstance.TemplateFileName;

                var tempDir = UncompressToTempDir(templateFilename);

                var tempFile = Path.Combine(tempDir, vsTemplateFileName);
                File.SetAttributes(tempFile, FileAttributes.Normal);
                // call recursivly for the .vstemplate file in the temp directory)
                Write(templateInstance, tempFile);

                VsHelper.CheckOut(templateFilename);

                new ZipFileCompressor(
                    templateFilename,
                    tempDir,
                    Directory
                    .GetFiles(tempDir, @"*.*", SearchOption.AllDirectories)
                    .Select(x => x.Replace(tempDir + Path.DirectorySeparatorChar, ""))
                    .ToArray(),
                    true,
                    true);
            }
            else if (templateFilename.EndsWith(TemplateFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                VsHelper.CheckOut(templateFilename);

                using (var file = new StreamWriter(templateFilename, false))
                    using (var writer = XmlWriter.Create(file, new XmlWriterSettings {
                        Indent = true
                    }))
                    {
                        var namespaces = new XmlSerializerNamespaces(new[] { TemplateDefaultNamespace });
                        Serializer.Serialize(writer, templateInstance, namespaces);
                    }
            }
            else
            {
                throw new InvalidOperationException(Resources.VsTemplateFile_ErrorUnsupportedVsTemplateExtension);
            }
        }
Beispiel #23
0
        public static void AddWizardExtension(this IVsTemplate template, Type templateExtensionType)
        {
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => templateExtensionType, templateExtensionType);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;
            var doc  = new XmlDocument();

            var newExtension = new VSTemplateWizardExtension[]
            {
                new VSTemplateWizardExtension
                {
                    Assembly      = new[] { new XmlNode[] { doc.CreateTextNode(templateExtensionType.Assembly.GetName().FullName) } },
                    FullClassName = new[] { new XmlNode[] { doc.CreateTextNode(templateExtensionType.FullName) } }
                }
            };

            if (temp.WizardExtension == null)
            {
                temp.WizardExtension = newExtension;
                VsTemplateFile.Write(template);
            }
            else
            {
                if (temp.WizardExtension.GetExtension(templateExtensionType) == null)
                {
                    if (temp.WizardExtension.Any(ext =>
                                                 (ext.Assembly[0] as XmlNode[])[0].Value.Contains(templateExtensionType.Assembly.GetName().Name) &&
                                                 (ext.FullClassName[0] as XmlNode[])[0].Value.Contains(templateExtensionType.Name)))
                    {
                        RemoveWizardExtension(template, templateExtensionType);
                    }

                    var existingExtensions = temp.WizardExtension;

                    temp.WizardExtension = existingExtensions.Concat(newExtension).ToArray();
                    VsTemplateFile.Write(template);
                }
            }
        }
Beispiel #24
0
        public string GetUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => parent, parent);

            if (template.Type == VsTemplateType.ProjectGroup)
            {
                return(baseName);
            }
            else if (template.Type == VsTemplateType.Project)
            {
                return(GetProjectUniqueName(baseName));
            }
            else if (template.Type == VsTemplateType.Item)
            {
                return(GetProjectItemUniqueName(baseName, template, parent));
            }

            throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                                                          Resources.UnfoldPathHelper_TemplateTypeIsNotSupported, template));
        }
Beispiel #25
0
        public string GetUniqueName(string baseName, IVsTemplate template, IItemContainer parent)
        {
            Guard.NotNull(() => baseName, baseName);
            Guard.NotNull(() => parent, parent);

            if (template.Type == VsTemplateType.ProjectGroup)
            {
                return baseName;
            }
            else if (template.Type == VsTemplateType.Project)
            {
                return GetProjectUniqueName(baseName);
            }
            else if (template.Type == VsTemplateType.Item)
            {
                return GetProjectItemUniqueName(baseName, template, parent);
            }

            throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                Resources.UnfoldPathHelper_TemplateTypeIsNotSupported, template));
        }
Beispiel #26
0
 /// <summary>
 /// See <see cref="IDisposable.Dispose"/>.
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (this.template != null)
     {
         this.template = null;
     }
     if (this.templateDictionary != null)
     {
         this.templateDictionary = null;
     }
     if (UnfoldTemplate.UnfoldingTemplates.Count > 0 && UnfoldTemplate.UnfoldingTemplates.Peek() == this)
     {
         UnfoldTemplate.UnfoldingTemplates.Pop();
     }
     if (openedItems != null)
     {
         openedItems.Clear();
         openedItems = null;
     }
     // Will automatically remove this component from its container.
     base.Dispose(disposing);
 }
Beispiel #27
0
        private bool IsTemplateVisible(string templateFileName, Guid projectFactory)
        {
            if (!File.Exists(templateFileName))
            {
                return(false);
            }
            string folder = Path.GetDirectoryName(templateFileName);

            if (IsCustomTemplateFolder(folder, projectFactory))
            {
                try
                {
                    IVsTemplatesService templatesService =
                        (IVsTemplatesService)GetService(typeof(IVsTemplatesService));
                    string[] vszParts = Path.GetFileNameWithoutExtension(templateFileName).Split('x');
                    if (vszParts.Length == 2)
                    {
                        Guid        package   = new Guid(vszParts[0]);
                        int         iTemplate = int.Parse(vszParts[1], NumberStyles.HexNumber);
                        IVsTemplate template  = templatesService.GetTemplate(package, iTemplate);
                        if (projectFactory.Equals(Guid.Empty))
                        {
                            return(template != null && template.IsVisibleInAddNewDialogBox);
                        }
                        else
                        {
                            return(template != null && template.IsVisibleInAddNewDialogBox && template.ProjectFactory.Equals(projectFactory));
                        }
                    }
                }
                catch
                {
                    return(false);
                }
                return(false);
            }
            return(true);
        }
Beispiel #28
0
        internal void ValidateHidden()
        {
            if (!string.IsNullOrEmpty(settings.TemplateAuthoringUri))
            {
                IItemContainer item = GetVsTemplateProjectItem();

                if (item != null)
                {
                    //Doing all the validation in one method to avoid the performance impact of reading the file from disc
                    IVsTemplate template = VsTemplateFile.Read(item.PhysicalPath);
                    if (settings.CreateElementOnUnfold && template.TemplateData.Hidden.HasValue && template.TemplateData.Hidden.Value)
                    {
                        //should not be hidden if created on unfold
                        context.LogWarning(
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Resources.Validate_TemplateSettingsHiddenIsInvalidWhenCreateOnUnfold,
                                settings.OwnerElement.Name),
                            Resources.Validate_TemplateSettingsHiddenIsInvalidWhenCreateOnUnfoldCode, settings.SettingsElement as ModelElement);
                    }
                }
            }
        }
Beispiel #29
0
        public static void SetWizardData(this IVsTemplate template, string name, string value)
        {
            Guard.NotNull(() => template, template);
            Guard.NotNull(() => name, name);
            Guard.NotNull(() => value, value);
            Guard.OfType(() => template, template, typeof(VSTemplate));

            var temp = (VSTemplate)template;

            var doc         = new XmlDocument();
            var dataElement = doc.CreateElement(name, "http://schemas.microsoft.com/developer/vstemplate/2005");

            dataElement.InnerText = value;

            var newData = new VSTemplateWizardData[]
            {
                new VSTemplateWizardData
                {
                    Any = new[] { dataElement }
                }
            };

            if (temp.WizardData == null)
            {
                temp.WizardData = newData;
                VsTemplateFile.Write(template);
            }
            else if (!temp.WizardData.Any(ext =>
                                          ext.Any.Count(e => e.Name == name && e.InnerText == value) > 0))
            {
                var existingData = temp.WizardData;

                temp.WizardData[0].Any = existingData[0].Any.Concat(new[] { dataElement }).ToArray();
                VsTemplateFile.Write(template);
            }
        }
Beispiel #30
0
        internal void ValidateAuthoringUriIsValidAndTemplateIsConfiguredCorrectly(bool validatingTemplate)
        {
            try
            {
                if (!string.IsNullOrEmpty(settings.TemplateAuthoringUri))
                {
                    IItemContainer item = GetVsTemplateProjectItem();
                    if (item != null)
                    {
                        //Doing all the validation in one method to avoid the performance impact of reading the file from disc
                        IVsTemplate template = VsTemplateFile.Read(item.PhysicalPath);
                        if (template == null)
                        {
                            if (!(settings.OwnerElement.Root.PatternModel.IsInTailorMode()))
                            {
                                context.LogError(
                                    string.Format(
                                        CultureInfo.CurrentCulture,
                                        Resources.Validate_TemplateSettingsAssociatedTemplateIsNotAValidTemplateFile,
                                        settings.OwnerElement.Name),
                                    Resources.Validate_TemplateSettingsAssociatedTemplateIsNotAValidTemplateFileCode, settings.SettingsElement as ModelElement);
                            }
                            return;
                        }

                        if (!settings.TemplateUri.EndsWith(template.TemplateData.TemplateID, StringComparison.OrdinalIgnoreCase))
                        {
                            //wrong id
                            context.LogError(
                                string.Format(
                                    CultureInfo.CurrentCulture,
                                    Resources.Validate_TemplateSettingsTemplateIdDoesNotMatchReferencedTemplate,
                                    this.name),
                                Resources.Validate_TemplateSettingsTemplateIdDoesNotMatchReferencedTemplateCode, settings.SettingsElement as ModelElement);
                        }

                        if (!((template.Type == VsTemplateType.Item && settings.TemplateUri.StartsWith(VsTemplateUri.GetUriBase(VsTemplateType.Item), StringComparison.OrdinalIgnoreCase)) ||
                              (template.Type == VsTemplateType.Project && settings.TemplateUri.StartsWith(VsTemplateUri.GetUriBase(VsTemplateType.Project), StringComparison.OrdinalIgnoreCase)) ||
                              (template.Type == VsTemplateType.ProjectGroup && settings.TemplateUri.StartsWith(VsTemplateUri.GetUriBase(VsTemplateType.ProjectGroup), StringComparison.OrdinalIgnoreCase))))
                        {
                            //wrong uri for type
                            context.LogError(
                                string.Format(
                                    CultureInfo.CurrentCulture,
                                    Resources.Validate_TemplateSettingsTemplateTypeDoesNotMatchReferencedTemplate,
                                    settings.OwnerElement.Name, template.Type),
                                Resources.Validate_TemplateSettingsTemplateTypeDoesNotMatchReferencedTemplateCode, settings.SettingsElement as ModelElement);
                        }

                        var elementReplacementsWizard = template.WizardExtension.GetExtension(TemplateWizardInfo.ElementReplacementsTemplateWizardFullTypeName);

                        if (validatingTemplate)
                        {
                            var instantiationWizard = template.WizardExtension.GetExtension(TemplateWizardInfo.InstantiationTemplateWizardFullTypeName);
                            if (instantiationWizard == null || elementReplacementsWizard == null)
                            {
                                //wizards not present
                                context.LogWarning(
                                    string.Format(
                                        CultureInfo.CurrentCulture,
                                        Resources.Validate_TemplateSettingsWizardsNotPresentInTemplate,
                                        settings.OwnerElement.Name),
                                    Resources.Validate_TemplateSettingsWizardsNotPresentInTemplateCode, settings.SettingsElement as ModelElement);
                            }
                            else if (template.WizardExtension.ToList().IndexOf(instantiationWizard) > template.WizardExtension.ToList().IndexOf(elementReplacementsWizard))
                            {
                                //wizards in wrong order
                                context.LogWarning(
                                    string.Format(
                                        CultureInfo.CurrentCulture,
                                        Resources.Validate_TemplateSettingsWizardOrderIsNotCorrect,
                                        settings.OwnerElement.Name),
                                    Resources.Validate_TemplateSettingsWizardOrderIsNotCorrectCode, settings.SettingsElement as ModelElement);
                            }
                        }
                        else
                        {
                            if (elementReplacementsWizard == null)
                            {
                                //wizards not present
                                context.LogWarning(
                                    string.Format(
                                        CultureInfo.CurrentCulture,
                                        Resources.Validate_TemplateSettingsWizardsNotPresentInTemplate,
                                        settings.OwnerElement.Name),
                                    Resources.Validate_TemplateSettingsWizardsNotPresentInTemplateCode, settings.SettingsElement as ModelElement);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tracer.Error(
                    ex,
                    Resources.ValidationMethodFailed_Error,
                    Reflector <TemplateValidator> .GetMethod(n => n.ValidateAuthoringUriIsValidAndTemplateIsConfiguredCorrectly(true)).Name);

                throw;
            }
        }
Beispiel #31
0
        protected override object ObtainDataImpl()
        {
            // TODO seems some resources need to be disposed


            // ITemplateProvider

            // IVsDialogService, IVsDialogService2, IVsDialogService3, IVsTemplateProviderFactory
            var sDialogService   = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsDialogService));
            var rawDialogService = (SVsDialogService)sDialogService;
            //var vsTemplateProviderFactory = (IVsTemplateProviderFactory)sDialogService;
            //var vsDialogService2 = (Microsoft.VisualStudio.Shell.Interop.IVsDialogService2)sDialogService;
            var vsTemplateProvider = rawDialogService.GetInstalledTemplateProvider(true);
            var extTree            = vsTemplateProvider.ExtensionsTree;

            // var tpl = extTree.Nodes[0].Extensions[0] as IVsTemplate;

            IEnumerable <object> ExpandTemplates(IVsExtensionsTreeNode root)
            {
                var stack = new Stack <IVsExtensionsTreeNode>();

                stack.Push(root);

                while (stack.Count > 0)
                {
                    var node = stack.Pop();

                    foreach (var item in node.Nodes)
                    {
                        stack.Push(item);
                    }

                    foreach (var item in node.Extensions)
                    {
                        yield return(item);
                    }
                }
            }

            var allTemplates = ExpandTemplates(extTree).OfType <IVsTemplate>().ToList();

            //var dte = (DTE2)await ServiceProvider.GetGlobalServiceAsync(typeof(DTE));
            //EnvDTE90.Templates

            // var _settingsManager = ((await this._asyncServiceProvider.GetServiceAsync(typeof(Microsoft.Internal.VisualStudio.Shell.Interop.SVsSettingsPersistenceManager))) as ISettingsManager);
            var settingsManager = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsSettingsPersistenceManager)) as ISettingsManager;

            var result = new List <ProjectTemplate>();

            var templatesList = settingsManager.GetOrCreateList("VS.IDE.Platform.ProjectTemplateMru", false);

            // var filtersList = settingsManager.GetOrCreateList("VS.IDE.Platform.ProjectTemplateFilters", false);

            foreach (string key in templatesList.Keys)
            {
                var templateInfo = templatesList.GetValueOrDefault <MRUTemplateInfo2>(key, null);

                // for an unknown reason template ids are messy and are unable to match sometimes, like for Core Console App template
                IVsTemplate vsTemplate = allTemplates.FirstOrDefault(t => !string.IsNullOrEmpty(t.NormalizedId()) && t.NormalizedId().Equals(templateInfo.Id, StringComparison.OrdinalIgnoreCase));
                // if (vsTemplate != null)
                // {
                result.Add(new ProjectTemplate(templateInfo, vsTemplate));
                // }
            }

            result.Sort((a, b) => b.LastAccessed.CompareTo(a.LastAccessed));

            return(result);
        }
Beispiel #32
0
 /// <summary>
 /// Writes a .vstemplate file back to its <see cref="IVsTemplate.PhysicalPath"/> location.
 /// </summary>
 public static void Write(IVsTemplate templateInstance)
 {
     Write(templateInstance, templateInstance.PhysicalPath);
 }
 /// <summary>
 /// Writes a .vstemplate file back to its <see cref="IVsTemplate.PhysicalPath"/> location.
 /// </summary>
 public static void Write(IVsTemplate templateInstance)
 {
     Write(templateInstance, templateInstance.PhysicalPath);
 }
        /// <summary>
        /// Writes a .vstemplate file from the given instance.
        /// </summary>
        public static void Write(IVsTemplate templateInstance, string templateFilename)
        {
            var hasFragment = templateFilename.Contains('?');
            if (hasFragment || templateFilename.EndsWith(TemplateArchiveFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                var vsTemplateFileName = templateInstance.TemplateFileName;

                var tempDir = UncompressToTempDir(templateFilename);

                var tempFile = Path.Combine(tempDir, vsTemplateFileName);
                File.SetAttributes(tempFile, FileAttributes.Normal);
                // call recursivly for the .vstemplate file in the temp directory)
                Write(templateInstance, tempFile);

                VsHelper.CheckOut(templateFilename);

                new ZipFileCompressor(
                    templateFilename,
                    tempDir,
                    Directory
                        .GetFiles(tempDir, @"*.*", SearchOption.AllDirectories)
                        .Select(x => x.Replace(tempDir + Path.DirectorySeparatorChar, ""))
                        .ToArray(),
                    true,
                    true);
            }
            else if (templateFilename.EndsWith(TemplateFileExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                VsHelper.CheckOut(templateFilename);

                using (var file = new StreamWriter(templateFilename, false))
                using (var writer = XmlWriter.Create(file, new XmlWriterSettings { Indent = true }))
                {
                    var namespaces = new XmlSerializerNamespaces(new[] { TemplateDefaultNamespace });
                    Serializer.Serialize(writer, templateInstance, namespaces);
                }
            }
            else
            {
                throw new InvalidOperationException(Resources.VsTemplateFile_ErrorUnsupportedVsTemplateExtension);
            }
        }
Beispiel #35
0
        void EnvDTE.IDTWizard.Execute(object Application, int hwndOwner, ref object[] ContextParams, ref object[] CustomParams, ref EnvDTE.wizardResult retval)
        {
            IVsTemplate vsTemplate = null;

            try
            {
                DTE dte = new DTETemplate((DTE)Application);
                CustomParams[0] = Environment.ExpandEnvironmentVariables((string)CustomParams[0]);

                if (!Path.IsPathRooted((string)CustomParams[0]) && CustomParams.Length >= 2)
                {
                    var guidancePackageName = (string)CustomParams[1];

                    var guidancePackageConfigurationFile = RecipeManager.GetConfigurationFile(RecipeManagerPackage.Singleton, guidancePackageName);

                    if (!string.IsNullOrEmpty(guidancePackageConfigurationFile))
                    {
                        var template = Path.Combine(Path.GetDirectoryName(guidancePackageConfigurationFile), (string)CustomParams[0]);

                        if (File.Exists(template))
                        {
                            CustomParams[0] = template;
                        }
                    }
                }
                string templateFileName             = (string)CustomParams[0];
                IVsTemplatesService templateService = (IVsTemplatesService)
                                                      ServiceHelper.GetService(
                    (IRecipeManagerService)
                    new VsServiceProvider(Application).GetService(typeof(IRecipeManagerService)),
                    typeof(IVsTemplatesService), this);
                vsTemplate = templateService.GetTemplate(templateFileName);
                string wizardKind = ((string)ContextParams[0]).ToUpper(CultureInfo.InvariantCulture);
                if (wizardKind == Constants.vsWizardNewProject)
                {
                    string destDir = (string)ContextParams[2];
                    //Web projects can pass in an empty directory, if so don't create the dest directory.
                    if ((new System.Uri(destDir)).IsFile)
                    {
                        Directory.CreateDirectory(destDir);
                    }

                    //If adding the project as exclusive, close the current solution then check to see if a
                    //  solution name is specified. If so, then create Ona solution with that name.
                    if (((bool)ContextParams[4]) == true)
                    {
                        vsPromptResult promptResult = dte.ItemOperations.PromptToSave;
                        if (promptResult == vsPromptResult.vsPromptResultCancelled)
                        {
                            retval = wizardResult.wizardResultCancel;
                            return;
                        }
                        dte.Solution.Close(false);
                        if (string.IsNullOrEmpty(((string)ContextParams[5])) == false)
                        {
                            dte.Solution.Create(destDir, ((string)ContextParams[5]));
                        }
                        ContextParams[4] = false;
                    }
                    // Create a new Solution Folder for the multiproject template
                    else if (vsTemplate.VSKind == WizardRunKind.AsMultiProject)
                    {
                        string folderName = (string)ContextParams[1];
                        if (dte.SelectedItems.Count == 1)
                        {
                            object item = DteHelper.GetTarget(dte);
                            if (item is Solution2)
                            {
                                ((Solution2)item).AddSolutionFolder(folderName);
                            }
                            else if (item is Project)
                            {
                                SolutionFolder slnFolder = (SolutionFolder)(((Project)item).Object);
                                slnFolder.AddSolutionFolder(folderName);
                            }
                        }
                    }
                }

                // Pre-fill state with context parameters.
                context = new System.Collections.Specialized.HybridDictionary();
                // See http://msdn.microsoft.com/library/en-us/vsintro7/html/vxlrfcontextparamsenum.asp
                string kind = ((string)ContextParams[0]).ToUpper();
                if (kind == Constants.vsWizardNewProject.ToUpper())
                {
                    FillNewProject(ContextParams, context);
                }
                else if (kind == Constants.vsWizardAddSubProject.ToUpper())
                {
                    FillAddSubProject(ContextParams, context);
                }
                else if (kind == Constants.vsWizardAddItem.ToUpper())
                {
                    FillAddItem(ContextParams, context);
                }

                IDTWizard wizard = new Microsoft.VisualStudio.TemplateWizard.Wizard();
                wizard.Execute(dte, hwndOwner, ref ContextParams, ref CustomParams, ref retval);
            }
            catch (Exception ex)
            {
                retval = wizardResult.wizardResultCancel;
                if (!(ex is COMException) || ((COMException)ex).ErrorCode != VSConstants.E_ABORT)
                {
                    ErrorHelper.Show(this.Site, ex);
                }
            }
            finally
            {
                Debug.Assert(UnfoldTemplate.UnfoldingTemplates.Count == 0);
                UnfoldTemplate.UnfoldingTemplates.Clear();
            }
        }