Exemplo n.º 1
0
 private static void AddCommentsToItem(CodeTypeDeclaration entity, ITemplateInfo template)
 {
     if (!string.IsNullOrEmpty(template.HelpText))
         entity.Comments.Add(new CodeCommentStatement("<summary>" + template.HelpText + "</summary>", true));
     else
         entity.Comments.Add(new CodeCommentStatement(string.Format("<summary>Represents the {0} template</summary>", template.FullPath), true));
 }
        /// <summary>
        /// Adds a concrete template to the state collection
        /// </summary>
        public TemplateInfo AddConcrete(ITemplateInfo item)
        {
            var templateInfo = new TemplateInfo(item, _parameters.ItemNamespace);

            templateInfo.FullName = _templateNovelizer.GetNovelFullTypeName(item.Name, item.FullPath);

            _templateLookup.Add(item.TemplateId, templateInfo);
            _templates.Add(templateInfo);

            return templateInfo;
        }
        protected virtual string GenerateTextSignature(ITemplateInfo templateItem)
        {
            List<string> keyElements = new List<string>();

            keyElements.Add(templateItem.FullPath); // full path will cover us for namespace changes
            keyElements.Add(templateItem.TemplateId.ToString()); // ID is used for creating new items and syncing

            foreach (var field in templateItem.OwnFields)
            {
                keyElements.Add(field.Name); // name determines property names
                keyElements.Add(field.Id.ToString()); // ID determines internal property lookups for speed
                keyElements.Add(field.Type); // type determines property Type
            }

            keyElements.Sort(); // sorting these gives us a standard order, so that merely reordering fields doesn't potentially invalidate the signature

            return string.Join("|", keyElements.ToArray());
        }
 public static string GetDefaultName(ITemplateInfo template)
 {
     return(template.GetDefaultName());
 }
Exemplo n.º 5
0
        // Attempts to invoke the template.
        // Warning: The _commandInput cannot be assumed to be in a state that is parsed for the template being invoked.
        //      So be sure to only get template-agnostic information from it. Anything specific to the template must be gotten from the ITemplateMatchInfo
        //      Or do a reparse if necessary (currently occurs in one error case).
        private async Task <CreationResultStatus> CreateTemplateAsync(ITemplateMatchInfo templateMatchDetails)
        {
            ITemplateInfo template = templateMatchDetails.Info;

            string fallbackName = new DirectoryInfo(_commandInput.OutputPath ?? Directory.GetCurrentDirectory()).Name;

            if (string.IsNullOrEmpty(fallbackName) || string.Equals(fallbackName, "/", StringComparison.Ordinal))
            {   // DirectoryInfo("/").Name on *nix returns "/", as opposed to null or "".
                fallbackName = null;
            }

            TemplateCreationResult instantiateResult;

            try
            {
                instantiateResult = await _templateCreator.InstantiateAsync(template, _commandInput.Name, fallbackName, _commandInput.OutputPath, templateMatchDetails.GetValidTemplateParameters(), _commandInput.SkipUpdateCheck, _commandInput.IsForceFlagSpecified, _commandInput.BaselineName).ConfigureAwait(false);
            }
            catch (ContentGenerationException cx)
            {
                Reporter.Error.WriteLine(cx.Message.Bold().Red());
                if (cx.InnerException != null)
                {
                    Reporter.Error.WriteLine(cx.InnerException.Message.Bold().Red());
                }

                return(CreationResultStatus.CreateFailed);
            }
            catch (TemplateAuthoringException tae)
            {
                Reporter.Error.WriteLine(tae.Message.Bold().Red());
                return(CreationResultStatus.CreateFailed);
            }

            string resultTemplateName = string.IsNullOrEmpty(instantiateResult.TemplateFullName) ? TemplateName : instantiateResult.TemplateFullName;

            switch (instantiateResult.Status)
            {
            case CreationResultStatus.Success:
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.CreateSuccessful, resultTemplateName));

                if (!string.IsNullOrEmpty(template.ThirdPartyNotices))
                {
                    Reporter.Output.WriteLine(string.Format(LocalizableStrings.ThirdPartyNotices, template.ThirdPartyNotices));
                }

                HandlePostActions(instantiateResult);
                break;

            case CreationResultStatus.CreateFailed:
                Reporter.Error.WriteLine(string.Format(LocalizableStrings.CreateFailed, resultTemplateName, instantiateResult.Message).Bold().Red());
                break;

            case CreationResultStatus.MissingMandatoryParam:
                if (string.Equals(instantiateResult.Message, "--name", StringComparison.Ordinal))
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.MissingRequiredParameter, instantiateResult.Message, resultTemplateName).Bold().Red());
                }
                else
                {
                    // TODO: rework to avoid having to reparse.
                    // The canonical info could be in the ITemplateMatchInfo, but currently isn't.
                    TemplateListResolver.ParseTemplateArgs(template, _hostDataLoader, _commandInput);

                    IReadOnlyList <string> missingParamNamesCanonical = instantiateResult.Message.Split(new[] { ',' })
                                                                        .Select(x => _commandInput.VariantsForCanonical(x.Trim())
                                                                                .DefaultIfEmpty(x.Trim()).First())
                                                                        .ToList();
                    string fixedMessage = string.Join(", ", missingParamNamesCanonical);
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.MissingRequiredParameter, fixedMessage, resultTemplateName).Bold().Red());
                }
                break;

            case CreationResultStatus.OperationNotSpecified:
                break;

            case CreationResultStatus.InvalidParamValues:
                TemplateUsageInformation usageInformation = TemplateUsageHelp.GetTemplateUsageInformation(template, EnvironmentSettings, _commandInput, _hostDataLoader, _templateCreator);
                string invalidParamsError = InvalidParameterInfo.InvalidParameterListToString(usageInformation.InvalidParameters);
                Reporter.Error.WriteLine(invalidParamsError.Bold().Red());
                Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, $"{CommandName} {TemplateName}").Bold().Red());
                break;

            default:
                break;
            }

            return(instantiateResult.Status);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Adds the versioning control attribute to the interface
        /// </summary>
        /// <example>[RepresentsSitecoreTemplate("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}", "Dn8cOiiO0ckeD/NPjd9Q8nJuPSk=")]</example>
        private void AddVersionAttributeToInterface(CodeTypeDeclaration interfaceType, ITemplateInfo template)
        {
            var attribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(RepresentsSitecoreTemplateAttribute)));

            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(template.TemplateId.ToString())));
            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(_signatureProvider.GenerateTemplateSignature(template))));
            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(_parameters.ConfigurationName)));

            interfaceType.CustomAttributes.Add(attribute);
        }
Exemplo n.º 7
0
        public async Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation)
        {
            // SettingsLoader.LoadTemplate is where the loc info should be read!!!
            // templateInfo knows enough to get at the loc, if any
            ITemplate template = _environmentSettings.SettingsLoader.LoadTemplate(templateInfo);

            if (template == null)
            {
                return(new TemplateCreationResult("Could not load template", CreationResultStatus.NotFound, templateInfo.Name));
            }

            string realName = name ?? template.DefaultName ?? fallbackName;
            // there should never be param errors here. If there are, the template is malformed, or the host gave an invalid value.
            IParameterSet templateParams = SetupDefaultParamValuesFromTemplateAndHost(template, realName, out IList <string> defaultParamsWithInvalidValues);

            if (defaultParamsWithInvalidValues.Any())
            {
                string message = string.Join(", ", defaultParamsWithInvalidValues);
                return(new TemplateCreationResult(message, CreationResultStatus.InvalidParamValues, template.Name));
            }

            ResolveUserParameters(template, templateParams, inputParameters, out IList <string> userParamsWithInvalidValues);
            if (userParamsWithInvalidValues.Any())
            {
                string message = string.Join(", ", userParamsWithInvalidValues);
                return(new TemplateCreationResult(message, CreationResultStatus.InvalidParamValues, template.Name));
            }

            bool missingParams = CheckForMissingRequiredParameters(templateParams, out IList <string> missingParamNames);

            if (missingParams)
            {
                return(new TemplateCreationResult(string.Join(", ", missingParamNames), CreationResultStatus.MissingMandatoryParam, template.Name));
            }

            if (template.IsNameAgreementWithFolderPreferred && string.IsNullOrEmpty(outputPath))
            {
                outputPath = name;
            }

            ICreationResult creationResult = null;
            string          targetDir      = outputPath ?? _environmentSettings.Host.FileSystem.GetCurrentDirectory();

            try
            {
                _paths.CreateDirectory(targetDir);
                Stopwatch         sw = Stopwatch.StartNew();
                IComponentManager componentManager = _environmentSettings.SettingsLoader.Components;

                IReadOnlyList <IFileChange> changes            = template.Generator.GetFileChanges(_environmentSettings, template, templateParams, componentManager, targetDir);
                IReadOnlyList <IFileChange> destructiveChanges = changes.Where(x => x.ChangeKind != ChangeKind.Create).ToList();

                if (!forceCreation && destructiveChanges.Count > 0)
                {
                    if (!_environmentSettings.Host.OnPotentiallyDestructiveChangesDetected(changes, destructiveChanges))
                    {
                        return(new TemplateCreationResult("Cancelled", CreationResultStatus.Cancelled, template.Name));
                    }
                }

                creationResult = await template.Generator.CreateAsync(_environmentSettings, template, templateParams, componentManager, targetDir).ConfigureAwait(false);

                sw.Stop();
                _environmentSettings.Host.OnTimingCompleted("Content generation time", sw.Elapsed);
                return(new TemplateCreationResult(string.Empty, CreationResultStatus.Success, template.Name, creationResult, outputPath));
            }
            catch (ContentGenerationException cx)
            {
                string message = cx.Message;
                if (cx.InnerException != null)
                {
                    message += Environment.NewLine + cx.InnerException.Message;
                }

                return(new TemplateCreationResult(message, CreationResultStatus.CreateFailed, template.Name));
            }
            catch (Exception ex)
            {
                return(new TemplateCreationResult(ex.Message, CreationResultStatus.CreateFailed, template.Name));
            }
        }
Exemplo n.º 8
0
 public Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation, string baselineName)
 {
     return(InstantiateAsync(templateInfo, name, fallbackName, outputPath, inputParameters, skipUpdateCheck, forceCreation, baselineName, false));
 }
Exemplo n.º 9
0
 protected virtual IEnumerable <TextFile> ProcessMethodsWithBody(ITemplateInfo templateInfo)
 {
     return(this.ProcessMethods(templateInfo, this.MethodsWithBody));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Check's whether a template should be reloaded or not.
        /// </summary>
        /// <param name="info">template information</param>
        /// <returns>
        /// true if template is OK; false if it do not exist or are old.
        /// </returns>
        public bool CheckTemplate(ITemplateInfo info)
        {
			if(HasTemplate(info.Filename))
                return File.GetLastWriteTime(_pathPrefix + info.Filename) <= info.CompiledWhen;

            return false;
        }
Exemplo n.º 11
0
        private static bool IsTemplateHiddenByHostFile(ITemplateInfo templateInfo, IHostSpecificDataLoader hostDataLoader)
        {
            HostSpecificTemplateData hostData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo);

            return(hostData.IsHidden);
        }
        private ITemplateEngineHost LoadHostWithLocalizationTemplates(string locale, out ISettingsLoader settingsLoaderOut, out ITemplateInfo localizationTemplate)
        {
            var env = _helper.CreateEnvironment(locale);

            env.SettingsLoader.Components.Register(typeof(TemplatesFactory));
            settingsLoaderOut = env.SettingsLoader;

            IReadOnlyList <ITemplateInfo> localizedTemplates = settingsLoaderOut.GetTemplatesAsync(default).Result;
Exemplo n.º 13
0
        private Func <ITextTemplatingEngineHost, string> PreProcessTemplate(ITemplateInfo templateInfo)
        {
            var templateContent = File.ReadAllText(templateInfo.FullPath);

            string language;

            string[] references;
            var      className     = templateInfo.TemplateName.Replace(".", "_");
            var      dummyHost     = new CustomT4Host(templateInfo, this.TemplatesDirectory, null, null);
            var      generatedCode = this.T4Engine.PreprocessTemplate(templateContent, dummyHost, className, RuntimeTemplatesNamespace, out language, out references);

            var parameters = new CompilerParameters
            {
                OutputAssembly          = templateInfo.TemplateName + ".dll",
                GenerateInMemory        = false,
                GenerateExecutable      = false,
                IncludeDebugInformation = true,
            };

            var assemblyLocations = AppDomain.CurrentDomain
                                    .GetAssemblies()
                                    .Where(a => !a.IsDynamic)
                                    .Select(a => a.Location);

            parameters.ReferencedAssemblies.AddRange(assemblyLocations.ToArray());

            parameters.TreatWarningsAsErrors = false;

            var provider = new CSharpCodeProvider();

            var results = provider.CompileAssemblyFromSource(parameters, generatedCode);

            if (results.Errors.Count > 0)
            {
                var realError = false;
                for (int i = 0; i < results.Errors.Count; i++)
                {
                    if (!results.Errors[i].IsWarning)
                    {
                        realError = true;
                    }
                    Console.WriteLine((results.Errors[i].IsWarning?"Warning":"Error") + "(" + i.ToString() + "): " + results.Errors[i].ToString());
                }

                if (realError)
                {
                    throw new InvalidOperationException("Template error.");
                }
            }

            var assembly          = results.CompiledAssembly;
            var templateClassType = assembly.GetType(RuntimeTemplatesNamespace + "." + className);

            dynamic templateClassInstance = Activator.CreateInstance(templateClassType);

            return((ITextTemplatingEngineHost host) =>
            {
                templateClassInstance.Host = host;
                return templateClassInstance.TransformText();
            });
        }
Exemplo n.º 14
0
        public static void ParseTemplateArgs(ITemplateInfo templateInfo, IHostSpecificDataLoader hostDataLoader, INewCommandInput commandInput)
        {
            HostSpecificTemplateData hostData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo);

            commandInput.ReparseForTemplate(templateInfo, hostData);
        }
Exemplo n.º 15
0
 protected IEnumerable <TextFile> ProcessTemplate(ITemplateInfo templateInfo)
 {
     yield return(this.ProcessTemplate(templateInfo, null, templateInfo.BaseFileName()));
 }
Exemplo n.º 16
0
 private IEnumerable <TextFile> ProcessTypes(ITemplateInfo templateInfo, Func <IEnumerable <OdcmObject> > modelMethod)
 {
     return(this.FilterOdcmEnumerable(templateInfo, modelMethod)
            .Select(odcmType => this.ProcessTemplate(templateInfo, odcmType, className: odcmType.Name)));
 }
Exemplo n.º 17
0
 protected virtual IEnumerable <TextFile> ProcessNonCollectionMethods(ITemplateInfo templateInfo)
 {
     return(this.ProcessMethods(templateInfo, this.NonCollectionMethods));
 }
Exemplo n.º 18
0
 public static string GetCompositionFilter(this ITemplateInfo ti)
 {
     return(GetValueFromTag(ti, TagPrefix + "compositionFilter"));
 }
Exemplo n.º 19
0
        public async Task <ICreationResult> CreateAsync(ITemplateInfo info, string name, string outputPath, IReadOnlyDictionary <string, string> parameters, bool skipUpdateCheck, string baselineName)
        {
            TemplateCreationResult instantiateResult = await _templateCreator.InstantiateAsync(info, name, name, outputPath, parameters, skipUpdateCheck, forceCreation : false, baselineName : baselineName).ConfigureAwait(false);

            return(instantiateResult.ResultInfo);
        }
 public virtual string GenerateTemplateSignature(ITemplateInfo templateItem)
 {
     string signatureText = GenerateTextSignature(templateItem);
     return HashTextSignature(signatureText);
 }
Exemplo n.º 21
0
        /// <summary>
        /// Adds the versioning control attribute to the interface
        /// </summary>
        /// <example>[RepresentsSitecoreTemplate("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}", "Dn8cOiiO0ckeD/NPjd9Q8nJuPSk=")]</example>
        private void AddVersionAttributeToInterface(CodeTypeDeclaration interfaceType, ITemplateInfo template)
        {
            var attribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(RepresentsSitecoreTemplateAttribute)));

            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(template.TemplateId.ToString())));
            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(_signatureProvider.GenerateTemplateSignature(template))));
            attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(_parameters.ConfigurationName)));

            interfaceType.CustomAttributes.Add(attribute);
        }
Exemplo n.º 22
0
        public static void BuilderTemplate(ITemplateInfo templateinfo,ITemplateHost host)
        {
            Type type = host.BaseType;

            string typename = "_" + Guid.NewGuid().ToString("N");
            RazorTemplateEngine engine = CreateHost(type, "_" + type.Name, typename);

            AddNamespace(type.Namespace);
            GeneratorResults razorResults = null;
            using (System.IO.StreamReader reader = templateinfo.GetCode())
            {
                razorResults = engine.GenerateCode(reader);
                CSharpCodeProvider codeProvider = new CSharpCodeProvider();
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                string LastGeneratedCode = null;
                using (StringWriter writer = new StringWriter())
                {
                    codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                    templateinfo.Host.LastCompileSource = writer.ToString();
                }
                CompilerParameters compilerParameters = new CompilerParameters(new string[0]);
                compilerParameters.OutputAssembly = "tmp_assembly" + typename;
                compilerParameters.GenerateInMemory = false;
                AddDomainAssemblies();
                foreach (string item in ReferencedAssemblies)
                    compilerParameters.ReferencedAssemblies.Add(item);
                compilerParameters.GenerateInMemory = true;
                CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
                if (compilerResults.Errors.Count > 0)
                {
                    string errormessage = null;

                    int throwindex = 1;
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    reader.BaseStream.Seek(0, SeekOrigin.Begin);
                    using (System.IO.StreamReader line = new StreamReader(reader.BaseStream, reader.CurrentEncoding))
                    {

                        ParserResults presult = engine.ParseTemplate(line);

                        if (presult.ParserErrors.Count > 0)
                        {
                            throwindex = presult.ParserErrors[0].Location.LineIndex + 1;
                            errormessage = presult.ParserErrors[0].Message;
                            reader.BaseStream.Seek(0, SeekOrigin.Begin);
                            using (System.IO.StreamReader readcode = new StreamReader(reader.BaseStream, reader.CurrentEncoding))
                            {
                                string code = readcode.ReadLine();
                                while (code != null)
                                {
                                    sb.AppendLine(code);
                                    code = readcode.ReadLine();

                                }
                            }

                        }
                        else
                        {
                            throwindex = compilerResults.Errors[0].Line;
                            errormessage = compilerResults.Errors[0].ErrorText;
                            sb.Append(LastGeneratedCode);
                        }

                    }

                    templateinfo.CompileError = errormessage;
                    throw new RazorException(templateinfo.CompileError);

                }
                templateinfo.Assembly = compilerResults.CompiledAssembly;
                templateinfo.TemplateType = compilerResults.CompiledAssembly.GetType("_" + type.Name + "." + typename);

            }
        }
Exemplo n.º 23
0
 protected virtual IEnumerable <TextFile> ProcessStreamProperties(ITemplateInfo templateInfo)
 {
     return(this.ProcessProperties(templateInfo, this.CurrentModel.GetStreamProperties));
 }
Exemplo n.º 24
0
 protected virtual IEnumerable <TextFile> ProcessEntityReferenceProperties(ITemplateInfo templateInfo)
 {
     return(this.ProcessTypes(templateInfo, this.CurrentModel.GetEntityReferenceTypes));
 }
Exemplo n.º 25
0
        /// <summary>
        /// Adds static and instance properties to an entity type to allow access to its TemplateID programmatically
        /// </summary>
        private static void AddTemplateIdPropertiesToEntity(CodeTypeDeclaration entity, ITemplateInfo template)
        {
            var templateNameStaticProperty = new CodeMemberProperty
            {
                Type = new CodeTypeReference(typeof(string)),
                Name = "TemplateName",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Static
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateNameStaticProperty.Comments.Add(new CodeCommentStatement("<summary>The name of the Sitecore Template that this class represents</summary>", true));

            templateNameStaticProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(template.Name)));

            entity.Members.Add(templateNameStaticProperty);

            var templateIdStaticProperty = new CodeMemberProperty
            {
                Type = new CodeTypeReference(typeof(ID)),
                Name = "ItemTemplateId",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Static
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateIdStaticProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("new Sitecore.Data.ID(\"" + template.TemplateId + "\")")));

            templateIdStaticProperty.Comments.Add(new CodeCommentStatement("<summary>The ID of the Sitecore Template that this class represents</summary>", true));

            entity.Members.Add(templateIdStaticProperty);

            var templateIdInstanceProperty = new CodeMemberProperty
            {
                Type = new CodeTypeReference(typeof(ID)),
                Name = "TemplateId",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Override
                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateIdInstanceProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("ItemTemplateId")));

            templateIdInstanceProperty.Comments.Add(new CodeCommentStatement("<summary>The ID of the Sitecore Template that this class represents</summary>", true));

            entity.Members.Add(templateIdInstanceProperty);
        }
Exemplo n.º 26
0
#pragma warning disable RECS0154 // Parameter is never used - but used by method which takes an action which is passed a template
        public static string GetRandomName(ITemplateInfo template)
#pragma warning restore RECS0154 // Parameter is never used
        {
            return(Path.GetRandomFileName().Replace(".", ""));
        }
Exemplo n.º 27
0
 /// <summary>
 /// Check's whether a template should be reloaded or not.
 /// </summary>
 /// <param name="info">template information</param>
 /// <returns>
 /// true if template is OK; false if it do not exist or are old.
 /// </returns>
 public bool CheckTemplate(ITemplateInfo info)
 {
     return HasTemplate (info.Filename);
 }
Exemplo n.º 28
0
        public async Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation, string baselineName, bool dryRun)
        {
            // SettingsLoader.LoadTemplate is where the loc info should be read!!!
            // templateInfo knows enough to get at the loc, if any
            ITemplate template = _environmentSettings.SettingsLoader.LoadTemplate(templateInfo, baselineName);

            try
            {
                if (template == null)
                {
                    return(new TemplateCreationResult("Could not load template", CreationResultStatus.NotFound, templateInfo.Name));
                }

                string realName = name ?? fallbackName ?? template.DefaultName;

                if (string.IsNullOrEmpty(realName))
                {
                    return(new TemplateCreationResult("--name", CreationResultStatus.MissingMandatoryParam, template.Name));
                }

                if (template.IsNameAgreementWithFolderPreferred && string.IsNullOrEmpty(outputPath))
                {
                    outputPath = name;
                }

                ICreationResult creationResult = null;
                string          targetDir      = outputPath ?? _environmentSettings.Host.FileSystem.GetCurrentDirectory();

                try
                {
                    if (!dryRun)
                    {
                        _paths.CreateDirectory(targetDir);
                    }

                    Stopwatch         sw = Stopwatch.StartNew();
                    IComponentManager componentManager = _environmentSettings.SettingsLoader.Components;

                    // setup separate sets of parameters to be used for GetCreationEffects() and by CreateAsync().
                    if (!TryCreateParameterSet(template, realName, inputParameters, out IParameterSet effectParams, out TemplateCreationResult resultIfParameterCreationFailed))
                    {
                        return(resultIfParameterCreationFailed);
                    }

                    ICreationEffects            creationEffects    = template.Generator.GetCreationEffects(_environmentSettings, template, effectParams, componentManager, targetDir);
                    IReadOnlyList <IFileChange> changes            = creationEffects.FileChanges;
                    IReadOnlyList <IFileChange> destructiveChanges = changes.Where(x => x.ChangeKind != ChangeKind.Create).ToList();

                    if (!forceCreation && destructiveChanges.Count > 0)
                    {
                        if (!_environmentSettings.Host.OnPotentiallyDestructiveChangesDetected(changes, destructiveChanges))
                        {
                            return(new TemplateCreationResult("Cancelled", CreationResultStatus.Cancelled, template.Name));
                        }
                    }

                    if (!TryCreateParameterSet(template, realName, inputParameters, out IParameterSet creationParams, out resultIfParameterCreationFailed))
                    {
                        return(resultIfParameterCreationFailed);
                    }

                    if (!dryRun)
                    {
                        creationResult = await template.Generator.CreateAsync(_environmentSettings, template, creationParams, componentManager, targetDir).ConfigureAwait(false);
                    }

                    sw.Stop();
                    _environmentSettings.Host.LogTiming("Content generation time", sw.Elapsed, 0);
                    return(new TemplateCreationResult(string.Empty, CreationResultStatus.Success, template.Name, creationResult, targetDir, creationEffects));
                }
                catch (ContentGenerationException cx)
                {
                    string message = cx.Message;
                    if (cx.InnerException != null)
                    {
                        message += Environment.NewLine + cx.InnerException.Message;
                    }

                    return(new TemplateCreationResult(message, CreationResultStatus.CreateFailed, template.Name));
                }
                catch (Exception ex)
                {
                    return(new TemplateCreationResult(ex.Message, CreationResultStatus.CreateFailed, template.Name));
                }
            }
            finally
            {
                ReleaseMountPoints(template);
            }
        }
        private async Task TrackItemGenAsync(string eventToTrack, ITemplateInfo template, GenSourceEnum genSource, string appProjectType, string appFx, TemplateCreationResult result)
        {
            GenStatusEnum telemetryStatus = result.Status == CreationResultStatus.Success ? GenStatusEnum.Completed : GenStatusEnum.Error;

            await TrackItemGenAsync(eventToTrack, telemetryStatus, appProjectType, appFx, template.Name, genSource, result.Status, result.Message);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Adds static and instance properties to an entity type to allow access to its TemplateID programmatically
        /// </summary>
        private static void AddTemplateIdPropertiesToEntity(CodeTypeDeclaration entity, ITemplateInfo template)
        {
            var templateNameStaticProperty = new CodeMemberProperty
            {
                Type   = new CodeTypeReference(typeof(string)),
                Name   = "TemplateName",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Static
                             // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateNameStaticProperty.Comments.Add(new CodeCommentStatement("<summary>The name of the Sitecore Template that this class represents</summary>", true));

            templateNameStaticProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(template.Name)));

            entity.Members.Add(templateNameStaticProperty);

            var templateIdStaticProperty = new CodeMemberProperty
            {
                Type   = new CodeTypeReference(typeof(ID)),
                Name   = "ItemTemplateId",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Static
                             // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateIdStaticProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("new Sitecore.Data.ID(\"" + template.TemplateId + "\")")));

            templateIdStaticProperty.Comments.Add(new CodeCommentStatement("<summary>The ID of the Sitecore Template that this class represents</summary>", true));

            entity.Members.Add(templateIdStaticProperty);

            var templateIdInstanceProperty = new CodeMemberProperty
            {
                Type   = new CodeTypeReference(typeof(ID)),
                Name   = "TemplateId",
                HasGet = true,
                HasSet = false,
                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                Attributes = MemberAttributes.Public | MemberAttributes.Override
                             // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            };

            templateIdInstanceProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("ItemTemplateId")));

            templateIdInstanceProperty.Comments.Add(new CodeCommentStatement("<summary>The ID of the Sitecore Template that this class represents</summary>", true));

            entity.Members.Add(templateIdInstanceProperty);
        }
Exemplo n.º 31
0
 public FilteredTemplateInfo(ITemplateInfo info, IReadOnlyList <MatchInfo> matchDisposition)
 {
     Info             = info;
     MatchDisposition = matchDisposition;
 }
Exemplo n.º 32
0
        private IReadOnlyDictionary <string, ICacheParameter> LocalizeCacheParameters(ITemplateInfo template, ILocalizationLocator localizationInfo)
        {
            if (localizationInfo == null || localizationInfo.ParameterSymbols == null)
            {
                return(template.CacheParameters);
            }

            IReadOnlyDictionary <string, ICacheParameter> templateCacheParameters = template.CacheParameters;
            IReadOnlyDictionary <string, IParameterSymbolLocalizationModel> localizedParameterSymbols = localizationInfo.ParameterSymbols;


            Dictionary <string, ICacheParameter> localizedCacheParams = new Dictionary <string, ICacheParameter>();

            foreach (KeyValuePair <string, ICacheParameter> templateParam in templateCacheParameters)
            {
                if (localizedParameterSymbols.TryGetValue(templateParam.Key, out IParameterSymbolLocalizationModel localizationForParam))
                {   // there is loc info for this symbol
                    ICacheParameter localizedParam = new CacheParameter
                    {
                        DataType     = templateParam.Value.DataType,
                        DefaultValue = templateParam.Value.DefaultValue,
                        Description  = localizationForParam.Description ?? templateParam.Value.Description
                    };

                    localizedCacheParams.Add(templateParam.Key, localizedParam);
                }
                else
                {
                    localizedCacheParams.Add(templateParam.Key, templateParam.Value);
                }
            }

            return(localizedCacheParams);
        }
Exemplo n.º 33
0
		public ItemTemplateFieldInfo(TemplateFieldItem field, ITemplateInfo template) : this(field)
		{
			Assert.ArgumentNotNull(template, "template");
			
			Template = template;
		}
 private static bool AlreadyAdded(UserSelection userSelection, ITemplateInfo item)
 {
     return(userSelection.Pages.Any(p => p.template.Identity == item.Identity) || userSelection.Features.Any(f => f.template.Identity == item.Identity));
 }
        /// <summary>
        /// Adds a interface template to the state collection
        /// </summary>
        public TemplateInfo AddInterface(ITemplateInfo item, string interfaceSuffix)
        {
            if (_friendInterfaceLookup.ContainsKey(item.TemplateId)) throw new InvalidOperationException("The template " + item.FullPath + " is already added as a friend interface and cannot be added again.");

            var templateInfo = new TemplateInfo(item, _parameters.InterfaceNamespace);

            string interfaceName = "I" + item.Name.AsIdentifier() + interfaceSuffix;
            string interfaceFullPath = item.FullPath.Substring(0, item.FullPath.LastIndexOf('/') + 1) + interfaceName;

            templateInfo.FullName = _interfaceNovelizer.GetNovelFullTypeName(interfaceName, interfaceFullPath);

            _interfaceLookup.Add(item.TemplateId, templateInfo);
            _interfaces.Add(templateInfo);

            return templateInfo;
        }
Exemplo n.º 36
0
        private List<ITemplateInfo> GetRecursiveBaseTemplates(ITemplateInfo parent)
        {
            // let's keep it our little secret that this is an iterative method, not recursive ;)

            var parentBases = new Queue<ITemplateInfo>(parent.BaseTemplates.Where(x => x.Name.ToUpperInvariant() != "STANDARD TEMPLATE")); // we just want NON-standard base templates
            var bases = new Dictionary<ID, ITemplateInfo>();
            while (parentBases.Count > 0)
            {
                var currentBase = parentBases.Dequeue();

                // already processed this template; skip it (e.g. a template cycle), or if it's the parent template
                if (bases.ContainsKey(currentBase.TemplateId) || currentBase.TemplateId.Equals(parent.TemplateId)) continue;

                // add grandparent base templates to processing queue
                var newBases = currentBase.BaseTemplates.Where(x => x.Name.ToUpperInvariant() != "STANDARD TEMPLATE");
                foreach(var newBase in newBases) parentBases.Enqueue(newBase);

                // add parent base template to bases
                bases.Add(currentBase.TemplateId, currentBase);
            }

            return bases.Values.ToList();
        }
        private static void LoadAndStoreTemplate(ITemplateInfo template, Encoding encoding = null)
        {
            template.Template = encoding != null ? Reader.Read(template.Path, encoding) : Reader.Read(template.Path);

            if (CachedTemplates.ContainsKey(template.Path))
            {
                CachedTemplates[template.Path] = template;
            }
            else
            {
                CachedTemplates.Add(template.Path, template);
            }
        }
 private static bool Match(IEnumerable <QueryNode> query, ITemplateInfo template)
 {
     return(Match(query, template.GetQueryableProperties()));
 }
Exemplo n.º 39
0
 protected virtual IEnumerable <TextFile> ProcessMethods(ITemplateInfo templateInfo)
 {
     return(this.ProcessMethods(templateInfo, this.CurrentModel.GetMethods));
 }
Exemplo n.º 40
0
        /// <summary>
        /// Checks the template.
        /// </summary>
        /// <param name="info">Template information, filename must be set.</param>
        /// <returns>true if template exists and have been compiled.</returns>
        private bool CheckTemplate(ITemplateInfo info)
        {
            if (info == null)
                return false;

			foreach (ITemplateLoader loader in _templateLoaders)
				if (loader.HasTemplate(info.Filename))
					return loader.CheckTemplate(info);

        	return false;
        }
Exemplo n.º 41
0
 internal static string GetTemplateHelpCommand(string commandName, ITemplateInfo template)
 {
     return(GetTemplateHelpCommand(commandName, template.ShortName));
 }
Exemplo n.º 42
0
 public static IEnumerable <ITemplateInfo> GetAllDependencies(ITemplateInfo template, string framework, string platform)
 {
     return(GetDependencies(template, framework, platform, new List <ITemplateInfo>()));
 }
Exemplo n.º 43
0
 internal static string GetTemplateHelpCommand(string commandName, ITemplateInfo template)
 {
     return($"dotnet {commandName} {template.ShortName} --help");
 }
 public bool IsStale(ITemplateInfo template)
 {
     var storedTemplate = CachedTemplates[template.Path];
     return template.LastWriteTime > storedTemplate.LastWriteTime;
 }
        /// <summary>
        /// Checks if a given Sitecore template has a corresponding interface. This method does NOT check any base templates this template may have for synchronization.
        /// </summary>
        public TemplateComparisonResult IsTemplateSynchronized(ITemplateInfo template)
        {
            var signature = _signatureProvider.GenerateTemplateSignature(template);
            ModelTemplateReference reference;

            if (ModelDictionary.TryGetValue(template.TemplateId.ToString(), out reference))
                return new TemplateComparisonResult(
                    template.TemplateId.ToString(),
                    GetTemplateName(template),
                    GetModelName(reference),
                    signature,
                    reference.Metadata.VersionSignature);

            return new TemplateComparisonResult(template.TemplateId.ToString(), GetTemplateName(template), null, signature, null);
        }
Exemplo n.º 46
0
		/// <summary>
		/// Always returns true since a resource won't be updated during execution
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
    	public bool CheckTemplate(ITemplateInfo info)
    	{
    		return true;
    	}
 protected static string GetTemplateName(ITemplateInfo template)
 {
     return template.FullPath.Substring("/sitecore/templates".Length);
 }
Exemplo n.º 48
0
        /// <summary>
        /// Generates an interface for each template that the current template derives from, recursively.
        /// </summary>
        private TemplateInfo GenerateInheritedInterfaces(ITemplateInfo template, TemplateGenerationMetadata templateData)
        {
            var existingInterface = templateData.GetInterface(template.TemplateId);
            if (existingInterface != null) return existingInterface;

            var interfaceInfo = templateData.AddInterface(template, _parameters.InterfaceSuffix);

            var fieldKeys = GetBaseFieldSet();
            fieldKeys.Add(interfaceInfo.TypeName); // member names cannot be the same as their enclosing type
            fieldKeys.Add(template.Name.AsIdentifier()); // prevent any fields from being generated that would conflict with a concrete item name as well as the interface name

            // create interface properties
            foreach (var field in template.OwnFields)
            {
                if (_templateInputProvider.IsFieldIncluded(field.Id))
                {
                    string propertyName = field.Name.AsNovelIdentifier(fieldKeys);

                    var fieldInfo = new FieldPropertyInfo(field);
                    fieldInfo.FieldPropertyName = propertyName;
                    fieldInfo.SearchFieldName = _indexFieldNameTranslator.GetIndexFieldName(field.Name);
                    fieldInfo.FieldType = _fieldMappingProvider.GetFieldType(field);

                    if (fieldInfo.FieldType == null)
                    {
                        Log.Warn("Synthesis: Field type resolution for " + field.Template.Name + "::" + field.Name + " failed; no mapping found for field type " + field.Type, this);
                        continue; // skip adding the field for generation
                    }

                    // record usage of the property name
                    fieldKeys.Add(propertyName);

                    // add the field to the metadata
                    interfaceInfo.FieldsToGenerate.Add(fieldInfo);
                }
            }

            // add base interface inheritance
            foreach (var baseTemplate in template.BaseTemplates)
            {
                if (baseTemplate.Name.ToUpperInvariant() != StandardTemplate)
                {
                    // recursively generate base templates' interfaces as needed
                    var baseInterface = GenerateInheritedInterfaces(baseTemplate, templateData);
                    if (baseInterface != null)
                        interfaceInfo.InterfacesImplemented.Add(baseInterface); // assign interface implementation
                }
            }

            return interfaceInfo;
        }
Exemplo n.º 49
0
 protected virtual IEnumerable <TextFile> ProcessCollectionReferences(ITemplateInfo templateInfo)
 {
     return(this.ProcessProperties(templateInfo, this.CollectionReferenceProperties));
 }