コード例 #1
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var template = projectItem as Template;

            Assert.Cast(template, nameof(template));

            var property = ((ISourcePropertyBag)template).GetSourceProperty <string>(LayoutFileItemParser.LayoutFile);

            if (property == null)
            {
                return;
            }

            var standardValuesItem = template.StandardValuesItem;

            if (standardValuesItem == null)
            {
                return;
            }

            foreach (var layoutFileCompiler in LayoutFileCompilers)
            {
                if (layoutFileCompiler.CanCompile(context, standardValuesItem, property))
                {
                    layoutFileCompiler.Compile(context, standardValuesItem, property);
                    break;
                }
            }
        }
コード例 #2
0
        public void Process(ICompileContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            foreach (var provider in this.providers)
            {
                foreach (var syntaxTree in context.Compilation.SyntaxTrees)
                {
                    var model    = context.Compilation.GetSemanticModel(syntaxTree);
                    var rewriter = provider(model, context);
                    if (rewriter == null)
                    {
                        throw new InvalidOperationException("Rewriter generator cannot return null.");
                    }

                    var rootNode  = syntaxTree.GetRoot();
                    var rewritten = rewriter.Visit(rootNode);

                    if (rootNode != rewritten)
                    {
                        context.Compilation = context.Compilation.ReplaceSyntaxTree(
                            syntaxTree,
                            syntaxTree.WithRootAndOptions(rewritten, syntaxTree.Options));
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Create the factory for the given <paramref name="target" /> using the <paramref name="context" />
        /// to inform the type of object that is to be built, and for compile-time dependency resolution.
        /// </summary>
        /// <param name="target">Required.  The target to be compiled.</param>
        /// <param name="context">Required.  The current compilation context.</param>
        /// <exception cref="System.ArgumentException">context must be an instance of IExpressionCompileContext</exception>
        public Func <ResolveContext, object> CompileTarget(ITarget target, ICompileContext context)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (target is IFactoryProvider factoryProvider)
            {
                return(factoryProvider.Factory);
            }
            else if (target is IInstanceProvider instanceProvider)
            {
                return(instanceProvider.GetInstance);
            }

            if (context is IExpressionCompileContext exprContext)
            {
                return(BuildFactory(target, this.BuildResolveLambda(target, exprContext)));
            }
            else
            {
                throw new ArgumentException("context must be an instance of IExpressionCompileContext", nameof(context));
            }
        }
コード例 #4
0
 protected override IEnumerable <FieldInfo> GetBindableFields(
     ICompileContext context, Type type)
 {
     //filter the fields to those which have an InjectAttribute defined
     return(base.GetBindableFields(context, type)
            .Where(f => f.IsDefined(typeof(InjectAttribute))));
 }
コード例 #5
0
 // TODO: Check that succeed and fail are both called by child contexts?
 public static void Succeed(this ICompileContext context)
 {
     if (context.Success != null)
     {
         context.Append(Goto(context.Success));
     }
 }
コード例 #6
0
        protected virtual void CreateLayoutWithRendering([NotNull] ICompileContext context, [NotNull] Item item, Guid layoutId, Guid renderingId, [NotNull] string placeholderKey)
        {
            var writer = new StringBuilder();

            using (var output = Factory.XmlWriter(writer))
            {
                output.WriteStartElement("r");

                var deviceItems = item.Project.ProjectItems.OfType <Item>().Where(i => string.Equals(i.TemplateIdOrPath, "/sitecore/templates/System/Layout/Device", StringComparison.OrdinalIgnoreCase) || string.Equals(i.TemplateIdOrPath, "{B6F7EEB4-E8D7-476F-8936-5ACE6A76F20B}", StringComparison.OrdinalIgnoreCase));
                foreach (var deviceItem in deviceItems)
                {
                    if (!deviceItem.ItemIdOrPath.StartsWith("/sitecore/layout/Devices/"))
                    {
                        continue;
                    }

                    output.WriteStartElement("d");
                    output.WriteAttributeString("id", deviceItem.Uri.Guid.Format());
                    output.WriteAttributeString("l", layoutId.Format());

                    output.WriteStartElement("r");
                    output.WriteAttributeString("id", renderingId.Format());
                    output.WriteAttributeString("ph", placeholderKey);
                    output.WriteEndElement();

                    output.WriteEndElement();
                }

                output.WriteEndElement();
            }

            SetRenderingsField(context, item, writer.ToString());
        }
        /// <summary>
        /// Given a set of tag registrations for user controls, attempt to connect those tag registrations to actual
        /// .NET class types in the main website assembly.  This will update the Typename field for each TagRegistration
        /// where a matching class type is found; or if no matching class type is found, this will throw an exception.
        /// </summary>
        /// <param name="compileContext">The context in which errors should be reported.</param>
        /// <param name="tagRegistrations">The set of user-control registrations to resolve to real class types.</param>
        /// <param name="assemblies">The full set of preloaded assemblies.</param>
        /// <param name="assemblyDirectory">The directory where the main website DLL can be found.</param>
        /// <param name="rootPath">The real disk path to the root of the website's virtual directory.</param>
        /// <param name="currentDirectory">The current directory (for resolving relative paths).</param>
        public static void ResolveUserControls(ICompileContext compileContext, IEnumerable <TagRegistration> tagRegistrations, ReferencedAssembliesContext assemblies, string rootPath, string currentDirectory)
        {
            foreach (TagRegistration tagRegistration in tagRegistrations.Where(t => t.Kind == TagRegistrationKind.SingleUserControl))
            {
                compileContext.Verbose("Registering user control <{0}:{1}> as \"{2}\".", tagRegistration.TagPrefix, tagRegistration.TagName, tagRegistration.SourceFilename);

                compileContext.VerboseNesting++;

                string filename = VistualPathUtils.ResolveWebsitePath(compileContext, tagRegistration.SourceFilename, rootPath, currentDirectory);

                MarkupReader userControlReader = new MarkupReader();

                // todo: how to handle references to user controls not found within rootpath?
                Tag userControlMainDirective = userControlReader.ReadMainDirective(compileContext, filename, assemblies, rootPath);

                if (string.IsNullOrEmpty(userControlMainDirective.TagName) &&
                    string.Compare(userControlMainDirective.TagName, "control", StringComparison.InvariantCultureIgnoreCase) != 0)
                {
                    throw new RedesignerException("Cannot register user control \"{0}\":  Its main <% ... %> directive does not start with the \"Control\" keyword.  Is this actually a user control?", tagRegistration.SourceFilename);
                }

                string inheritsAttribute = userControlMainDirective["inherits"];
                if (string.IsNullOrEmpty(inheritsAttribute))
                {
                    throw new RedesignerException("Cannot register user control \"{0}\":  Its main <% Control ... %> directive is missing the required Inherits=\"...\" attribute.", tagRegistration.SourceFilename);
                }

                tagRegistration.Typename = inheritsAttribute;

                compileContext.Verbose("User control registered as type \"{0}\".", inheritsAttribute);
                compileContext.VerboseNesting--;
            }
        }
コード例 #8
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var include = context.Configuration.GetString(Constants.Configuration.BuildProjectCompileBinFilesInclude);
            if (string.IsNullOrEmpty(include))
            {
                return;
            }

            var binFile = projectItem as BinFile;
            Assert.Cast(binFile, nameof(binFile));

            var exclude = context.Configuration.GetString(Constants.Configuration.BuildProjectCompileBinFilesExclude);

            var pathMatcher = new PathMatcher(include, exclude);
            if (!pathMatcher.IsMatch(binFile.FilePath))
            {
                return;
            }

            try
            {
                var assembly = Assembly.LoadFrom(binFile.Snapshots.First().SourceFile.AbsoluteFileName);

                foreach (var type in assembly.GetExportedTypes())
                {
                    context.Pipelines.Resolve<BinFileCompilerPipeline>().Execute(context, binFile, type);
                }
            }
            catch (Exception ex)
            {
                context.Trace.TraceError(Msg.C1059, ex.Message, binFile.FilePath);
            }
        }
コード例 #9
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var rendering = projectItem as Rendering;
            if (rendering == null)
            {
                return;
            }

            var project = rendering.Project;
            var snapshot = rendering.Snapshots.First();
            var snapshotTextNode = new SnapshotTextNode(snapshot);
            var guid = StringHelper.GetGuid(project, rendering.ItemPath);
            var item = context.Factory.Item(project, snapshotTextNode, guid, rendering.DatabaseName, rendering.ItemName, rendering.ItemPath, rendering.TemplateIdOrPath);
            item.ItemNameProperty.AddSourceTextNode(new FileNameTextNode(rendering.ItemName, snapshot));
            item.OverwriteWhenMerging = true;

            var field = context.Factory.Field(item, snapshotTextNode, "Path", rendering.FilePath);
            field.ValueProperty.Flags = SourcePropertyFlags.IsFileName;
            item.Fields.Add(field);
            item.References.Add(new FileReference(item, field.ValueProperty));

            if (rendering.Placeholders.Any())
            {
                var placeholdersField = context.Factory.Field(item, TextNode.Empty, "Place Holders", string.Join(",", rendering.Placeholders));
                item.Fields.Add(placeholdersField);
            }

            var addedItem = rendering.Project.AddOrMerge(item);
            rendering.RenderingItemUri = addedItem.Uri;
        }
コード例 #10
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var serializationFile = projectItem as SerializationFile;
            if (serializationFile == null)
            {
                return;
            }

            var textDocument = (ITextSnapshot)serializationFile.Snapshots.First();
            var rootTextNode = textDocument.Root;
            if (rootTextNode == TextNode.Empty)
            {
                context.Trace.TraceError(Msg.C1050, Texts.Document_is_not_valid, textDocument.SourceFile.AbsoluteFileName, TextSpan.Empty);
                return;
            }

            var lines = textDocument.SourceFile.ReadAsLines();
            var itemBuilder = context.Factory.ItemBuilder();

            ParseItem(context, textDocument, itemBuilder, lines, 0);

            var item = itemBuilder.Build(serializationFile.Project, rootTextNode);
            item.IsEmittable = false;

            var addedItem = serializationFile.Project.AddOrMerge(item);
            serializationFile.SerializationItemUri = addedItem.Uri;
        }
コード例 #11
0
        /// <summary>
        /// Attempt to load the given assembly, by name, either from the GAC, or from the current directory.
        /// </summary>
        /// <param name="compileContext">The context in which errors should be reported.</param>
        /// <param name="name">The name of the assembly to load.</param>
        /// <returns>The loaded assembly, or null if it could not be found.</returns>
        private static Assembly TryToLoadAssembly(ICompileContext compileContext, string name)
        {
            Assembly assembly;

            try
            {
                assembly = Assembly.Load(name);
                compileContext.Verbose("Found it in the GAC.");
            }
            catch (Exception)
            {
                try
                {
                    compileContext.Verbose("Assembly is not in GAC, trying again as a file in directory of website DLL.");
                    assembly = Assembly.LoadFrom(name);
                    compileContext.Verbose("Found it in the website directory.");
                }
                catch (Exception)
                {
                    try
                    {
                        compileContext.Verbose("Trying again with '.dll' added onto the end of the assembly name.");
                        assembly = Assembly.LoadFrom(name + ".dll");
                        compileContext.Verbose("Found it in the website directory.");
                    }
                    catch (Exception)
                    {
                        assembly = null;
                    }
                }
            }

            return(assembly);
        }
コード例 #12
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var sourcePropertyBag = projectItem as ISourcePropertyBag;

            Assert.Cast(sourcePropertyBag, nameof(sourcePropertyBag));

            var property = sourcePropertyBag.GetSourceProperty <string>(LayoutFileItemParser.LayoutFile);

            if (property == null)
            {
                return;
            }

            var compiled = false;

            foreach (var layoutFileCompiler in LayoutFileCompilers)
            {
                if (!layoutFileCompiler.CanCompile(context, projectItem, property))
                {
                    continue;
                }

                layoutFileCompiler.Compile(context, projectItem, property);
                compiled = true;
                break;
            }

            if (!compiled)
            {
                Trace.TraceError(Msg.C1063, Texts.Element_has_a__Layout_File__attribute__but_it_could_not_be_compiled, TraceHelper.GetTextNode(property), property.GetValue());
            }
        }
コード例 #13
0
        protected virtual int ParseFieldValue([NotNull] ICompileContext context, [NotNull] ITextSnapshot textSnapshot, [NotNull, ItemNotNull] string[] lines, [NotNull] FieldBuilder fieldBuilder, int startIndex, int contentLength, ref int lineLength)
        {
            string value;
            var    sb = new StringBuilder();

            for (var n = startIndex; n < lines.Length; n++)
            {
                var line = lines[n];
                lineLength += line.Length;

                if (sb.Length < contentLength)
                {
                    sb.Append(line);
                    sb.Append("\r\n");
                    continue;
                }

                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                value = sb.ToString().Trim().TrimEnd('\n', '\r');
                fieldBuilder.Value         = value;
                fieldBuilder.ValueTextNode = Factory.TextNode(textSnapshot, string.Empty, value, GetTextSpan(startIndex, 0, contentLength));
                return(n - 1);
            }

            value = sb.ToString().Trim().TrimEnd('\n', '\r');
            fieldBuilder.Value         = value;
            fieldBuilder.ValueTextNode = Factory.TextNode(textSnapshot, string.Empty, value, GetTextSpan(startIndex, 0, contentLength));
            return(lines.Length);
        }
コード例 #14
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var serializationFile = projectItem as SerializationFile;

            Assert.Cast(serializationFile, nameof(serializationFile));

            var textDocument = (ITextSnapshot)serializationFile.Snapshot;
            var rootTextNode = textDocument.Root;

            if (rootTextNode == TextNode.Empty)
            {
                Trace.TraceError(Msg.C1050, Texts.Document_is_not_valid, textDocument.SourceFile.AbsoluteFileName, TextSpan.Empty);
                return;
            }

            var lines       = textDocument.SourceFile.ReadAsLines();
            var itemBuilder = new ItemBuilder(Factory);

            ParseItem(context, textDocument, itemBuilder, lines);

            var item = itemBuilder.Build(serializationFile.Project, rootTextNode);

            item.IsEmittable = false;

            item.References.AddRange(ReferenceParser.ParseReferences(item, item.TemplateIdOrPathProperty));
            foreach (var field in item.Fields)
            {
                item.References.AddRange(ReferenceParser.ParseReferences(field));
            }

            var addedItem = context.Project.AddOrMerge(item);

            serializationFile.SerializationItemUri = addedItem.Uri;
        }
コード例 #15
0
        protected virtual void CreateTemplate([NotNull] ICompileContext context, [NotNull] IProject project, [NotNull] Item templateItem)
        {
            var template = Factory.Template(templateItem.Database, templateItem.Uri.Guid, templateItem.ItemName, templateItem.ItemIdOrPath).With(templateItem.SourceTextNode, false, templateItem.IsImport);

            template.IsSynthetic = true;

            var baseTemplateField = templateItem.Fields.FirstOrDefault(f => f.FieldName == Constants.FieldNames.BaseTemplate);

            if (baseTemplateField != null)
            {
                template.BaseTemplatesProperty.SetValue(baseTemplateField.ValueProperty);
            }

            var iconField = templateItem.Fields.FirstOrDefault(f => f.FieldName == Constants.FieldNames.Icon);

            if (iconField != null)
            {
                template.IconProperty.SetValue(iconField.ValueProperty);
            }

            foreach (var sectionItem in templateItem.Children)
            {
                var templateSection = Factory.TemplateSection(template, sectionItem.Uri.Guid).With(sectionItem.SourceTextNode);
                templateSection.IsSynthetic = true;
                template.Sections.Add(templateSection);
                templateSection.SectionNameProperty.SetValue(sectionItem.ItemNameProperty);

                var sectionIconField = sectionItem.Fields.FirstOrDefault(f => f.FieldName == Constants.FieldNames.Icon);
                if (sectionIconField != null)
                {
                    templateSection.IconProperty.SetValue(sectionIconField.ValueProperty);
                }

                var sectionSortorderField = sectionItem.Fields.FirstOrDefault(f => f.FieldName == Constants.FieldNames.SortOrder);
                if (sectionSortorderField != null)
                {
                    if (int.TryParse(sectionSortorderField.Value, out var sortorder))
                    {
                        templateSection.SortorderProperty.SetValue(sortorder);
                    }
                }

                foreach (var fieldItem in sectionItem.Children)
                {
                    var templateField = Factory.TemplateField(template, fieldItem.Uri.Guid).With(fieldItem.SourceTextNode);
                    templateField.IsSynthetic = true;
                    templateSection.Fields.Add(templateField);
                    templateField.FieldNameProperty.SetValue(fieldItem.ItemNameProperty);

                    var typeField = fieldItem.Fields.FirstOrDefault(f => f.FieldName == Constants.FieldNames.Type);
                    if (typeField != null)
                    {
                        templateField.TypeProperty.SetValue(typeField.ValueProperty);
                    }
                }
            }

            project.AddOrMerge(template);
        }
コード例 #16
0
        /// <summary>
        /// Called at the beginning of the compilation of a source file.
        /// </summary>
        public virtual void PreCompile(ICompileContext context)
        {
            this.Context = context;

            this.Messaging = context.Messaging;

            this.ParseHelper = context.ServiceProvider.GetService <IParseHelper>();
        }
コード例 #17
0
 public static void Advance(this ICompileContext context, int length)
 {
     if (length == 0)
     {
         return;
     }
     context.Append(AddAssign(context.Position, Constant(length)));
 }
コード例 #18
0
        public override void Compile(ICompileContext context)
        {
            var match = context.Cache(Default(typeof(string)));

            context.Child(regex, null, match, null, context.Failure);
            context.Succeed(Call(parseMethod, match, Constant(styles)));
            context.Release(match);
        }
コード例 #19
0
 public static void Succeed(this ICompileContext context, Expression value)
 {
     if (context.Result?.CanWrite() == true)
     {
         context.Append(Assign(context.Result, Convert(value, context.Result.Type)));
     }
     context.Succeed();
 }
コード例 #20
0
        /// <summary>
        /// Fetch the target that would be bound to this parameter given the passed <see cref="ICompileContext"/>
        /// </summary>
        /// <param name="context">The current compile context - a new one is created for the <see cref="Parameter"/> type</param>
        /// <returns>The target that should be used for the parameter, or null if no target could be found.
        ///
        /// Note that if the returned target's <see cref="ITarget.UseFallback"/> property is set to <c>true</c>,
        /// then it means either the parameter's default value is being used, or that the target fetched from the
        /// target container in the context is a stub (e.g. empty enumerable)</returns>
        /// <remarks>During compilation - you should not use the target returned by this function as a direct
        /// part of your expression tree - you should </remarks>
        public virtual ITarget Resolve(ICompileContext context)
        {
            if (Target is ResolvedTarget rezolvedTarget)
            {
                return(rezolvedTarget.Bind(context.NewContext(Parameter.ParameterType)));
            }

            return(Target);
        }
コード例 #21
0
        protected override MemberBinding CreateBinding(
            ICompileContext context, Type type, PropertyInfo prop)
        {
            //identical to above
            var attr = prop.GetCustomAttribute <InjectAttribute>();

            return(new MemberBinding(prop,
                                     new ResolvedTarget(attr.Type ?? prop.PropertyType)));
        }
コード例 #22
0
        /// <summary>
        /// Overrides the base to return bindings only for those members that were passed on construction.
        /// </summary>
        /// <param name="context">The current compile context</param>
        /// <param name="type">The type whose members are being bound (note this could be a type that's
        /// derived from the one on which the <paramref name="field"/> is declared.</param>
        /// <param name="field">The field being bound.</param>
        /// <returns>The binding to be applied to passed <paramref name="field"/> if it's a known field,
        /// otherwise <c>null</c></returns>
        protected override MemberBinding CreateBinding(ICompileContext context, Type type, FieldInfo field)
        {
            if (this.members.TryGetValue(new MemberInfoKey(field), out var binding))
            {
                return(binding);
            }

            return(null);
        }
コード例 #23
0
        /// <summary>
        /// Returns the <see cref="ITarget"/> that should be compiled as the body of the delegate.  If <see cref="BoundTarget"/>
        /// is not null and its <see cref="ITarget.UseFallback"/> is false, then no binding is performed.
        ///
        /// Otherwise, a suitable target is sought from the <paramref name="compileContext"/>.  If not found, then
        /// a <see cref="ResolvedTarget"/> is emitted with a fallback set to the <see cref="BoundTarget"/> if non-null,
        /// meaning that the delegate will actually perform a late-bound resolve operation on the container on which it's
        /// called.
        /// </summary>
        /// <param name="compileContext">The current compilation context, this is used to resolve the target to be bound.</param>
        /// <returns>The target to be compiled as the body of the factory.</returns>
        public ITarget Bind(ICompileContext compileContext)
        {
            if (BoundTarget != null && !BoundTarget.UseFallback)
            {
                return(BoundTarget);
            }

            return(compileContext.Fetch(ReturnType) ?? new ResolvedTarget(ReturnType, BoundTarget));
        }
        /// <summary>
        /// Create a .designer file for the given parsed markup.
        /// </summary>
        /// <param name="compileContext">The context in which errors should be reported.</param>
        /// <param name="markupInfo">The fully-parsed markup.</param>
        /// <returns>The contents of the .designer file, as a string.</returns>
        public string CreateDesigner(ICompileContext compileContext, MarkupInfo markupInfo)
        {
            compileContext.Verbose("");
            string inherits = markupInfo.MainDirective["inherits"];

            compileContext.Verbose("Generating designer file for {0} with the {1} controls found in the markup.", inherits, markupInfo.OutputControls.Count());

            // Get the actual runtime version from the System.Web assembly itself.
            string runtimeVersion = "0";
            var    sysWebAssembly = markupInfo.Assemblies.SystemWebAssembly;

            if (sysWebAssembly != null)
            {
                runtimeVersion = sysWebAssembly.ImageRuntimeVersion;
            }

            if (runtimeVersion.StartsWith("v"))
            {
                runtimeVersion = runtimeVersion.Substring(1);
            }

            // Construct the initial part of the .designer.cs file.
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat(DesignerStart, runtimeVersion + ".0", markupInfo.InheritsClassNamespace, markupInfo.InheritsClassName);

            // We must skip Content declarations, since those are not emitted as output.
            Type contentControl = typeof(System.Web.UI.WebControls.Content);

            // Spit out all of the controls.
            foreach (OutputControl outputControl in markupInfo.OutputControls)
            {
                string controlName = outputControl.Name;
                Type   controlType = outputControl.ReflectedControl.ControlType;

                if (contentControl.IsAssignableFrom(controlType))
                {
                    continue;
                }

                if (string.IsNullOrEmpty(controlName))
                {
                    compileContext.Verbose("Skipping unnamed {0} control.", controlType.FullName);
                    continue;
                }

                compileContext.Verbose("Adding control declaration: {1} {0}.", controlName, controlType.FullName);

                stringBuilder.AppendFormat(Declaration, controlName, controlType.FullName);
            }

            stringBuilder.Append(DesignerEnd);

            compileContext.Verbose("End generation of designer file.");

            return(stringBuilder.ToString());
        }
コード例 #25
0
        public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;
            if (item == null)
            {
                return false;
            }

            return item.SourceTextNodes.Select(n => n.GetAttributeValue("Template.CreateFromFields")).Any(value => string.Equals(value, "true", StringComparison.OrdinalIgnoreCase));
        }
コード例 #26
0
        public BinFileCompilerPipeline Execute([NotNull] ICompileContext context, [NotNull] BinFile binFile, [NotNull] Type type)
        {
            Context = context;
            BinFile = binFile;
            Type    = type;

            Execute();

            return(this);
        }
コード例 #27
0
        /// <summary>
        /// Load and parse the given .designer file.
        /// </summary>
        /// <param name="compileContext">The context in which to report errors during the parse.</param>
        /// <param name="filename">The name of the .designer file to load and parse.</param>
        /// <returns>The parsed version of the .designer file.</returns>
        public DesignerInfo LoadDesignerFile(ICompileContext compileContext, string filename)
        {
            _compileContext = compileContext;
            _line           = 0;

            Verbose("Loading .designer file from disk.");

            string designerText = File.ReadAllText(filename);

            return(ParseDesignerText(compileContext, designerText));
        }
コード例 #28
0
ファイル: Common.cs プロジェクト: dazinator/Redesigner
        /// <summary>
        /// Generate a replacement .designer.cs file for the given markup file, overwriting the existing
        /// .designer.cs file if there is one.
        /// </summary>
        public static bool GenerateDesignerForFilename(ICompileContext compileContext, string filename, IEnumerable <TagRegistration> tagRegistrations, AssemblyLoader assemblies, string assemblyDirectory, string rootPath)
        {
            string designer;
            string designerFilename = filename + ".designer.cs";

            // Load the markup from the .aspx or .ascx file.
            MarkupReader markup = new MarkupReader();
            MarkupInfo   markupInfo;

            try
            {
                markupInfo = markup.LoadMarkup(compileContext, filename, tagRegistrations, assemblies, assemblyDirectory, rootPath);
            }
            catch (Exception e)
            {
                compileContext.Error("{0}: Failed to load markup file:\r\n{1}", filename, e.Message);
                compileContext.Verbose("Stopping file processing due to exception.  Stack trace:\r\n{0}", e.StackTrace);
                return(false);
            }

            // If we're not inheriting a real class, there's no reason for a designer file to exist.
            if (markupInfo.ClassType == null)
            {
                compileContext.Verbose("Skipping generating designer file because markup does not have an Inherits=\"...\" attribute.", filename);
                return(true);
            }

            // Generate the output text for the new .designer.cs file.
            try
            {
                DesignerWriter designerWriter = new DesignerWriter();
                designer = designerWriter.CreateDesigner(compileContext, markupInfo);
            }
            catch (Exception e)
            {
                compileContext.Error("{0}: Cannot regenerate designer file:\r\n{1}", filename, e.Message);
                compileContext.Verbose("Stopping file processing due to exception.  Stack trace:\r\n{0}", e.StackTrace);
                return(false);
            }

            // Save the output .designer.cs file to disk.
            try
            {
                File.WriteAllText(designerFilename, designer, Encoding.UTF8);
            }
            catch (Exception e)
            {
                compileContext.Error("{0}: Cannot open designer file for writing:\r\n{1}", designerFilename, e.Message);
                compileContext.Verbose("Stopping file processing due to exception.  Stack trace:\r\n{0}", e.StackTrace);
                return(false);
            }

            return(true);
        }
コード例 #29
0
        public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;

            if (item == null)
            {
                return(false);
            }

            return(item.GetTextNodes().Select(n => n.GetAttributeValue("Template.CreateFromFields")).Any(value => string.Equals(value, "true", StringComparison.OrdinalIgnoreCase)));
        }
コード例 #30
0
        protected override MemberBinding CreateBinding(
            ICompileContext context, Type type, FieldInfo field)
        {
            //the base method merely creates a new MemberBinding, bound to a new ResolvedTarget
            //whose type is set to the field type.
            //This is similar except we read the InjectAttribute's ResolveType, and use that
            //type if it's not null.
            var attr = field.GetCustomAttribute <InjectAttribute>();

            return(new MemberBinding(field, new ResolvedTarget(attr.Type ?? field.FieldType)));
        }
コード例 #31
0
        public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;

            if (item == null)
            {
                return(false);
            }

            return(((ISourcePropertyBag)item).ContainsSourceProperty(LayoutFileItemParser.LayoutFile));
        }
コード例 #32
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;
            Assert.Cast(item, nameof(item));

            var fileName = item.GetValue<string>(LayoutPage)?.Trim() ?? string.Empty;
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            var property = item.GetProperty<string>(LayoutPage);

            // find page html file
            var rendering = item.Project.Files.FirstOrDefault(i => string.Equals(i.FilePath, fileName, StringComparison.OrdinalIgnoreCase));
            if (rendering == null)
            {
                context.Trace.TraceError(Msg.C1047, Texts.Rendering_reference_not_found, TraceHelper.GetTextNode(property), fileName);
            }

            // find MvcLayout
            var layoutItem = item.Project.ProjectItems.OfType<Item>().FirstOrDefault(i => i.ItemIdOrPath == "/sitecore/layout/Layouts/MvcLayout");
            if (layoutItem == null)
            {
                context.Trace.TraceError(Msg.C1048, Texts.Layout_reference_not_found, TraceHelper.GetTextNode(property), "/sitecore/layout/Layouts/MvcLayout");
            }

            if (rendering == null || layoutItem == null)
            {
                return;
            }

            var sourceFile = rendering.Snapshots.First().SourceFile;

            var writer = new StringWriter();
            var output = new XmlTextWriter(writer);
            output.Formatting = Formatting.Indented;

            var buildContext = new BuildContext(context, sourceFile, output, item, layoutItem);

            var literalRendering = FindRendering(buildContext, "Literal", string.Empty, TextSpan.Empty);
            if (literalRendering == null)
            {
                return;
            }

            buildContext.Placeholder = layoutItem["Place Holders"];
            buildContext.LiteralRendering = literalRendering;

            ParseHtml(buildContext);

            SetRenderingsField(buildContext, buildContext.Item, writer.ToString());
        }
コード例 #33
0
 public override void Compile(ICompileContext context)
 {
     if (_prefix != null)
     {
         context.Child(_prefix, "(Prefix)", null, null, context.Failure);
     }
     context.Child(_inner, null, context.Result, null, context.Failure);
     if (_suffix != null)
     {
         context.Child(_suffix, "(Suffix)", null, null, context.Failure);
     }
     context.Succeed();
 }
コード例 #34
0
        protected void SetRenderingsField([NotNull] ICompileContext context, [NotNull] Item item, [NotNull] string value)
        {
            var field = item.Fields["__Renderings"];

            if (field == null)
            {
                field = Factory.Field(item, "__Renderings", value);
                item.Fields.Add(field);
            }
            else
            {
                field.Value = value;
            }
        }
コード例 #35
0
        public NodeRewriter(SemanticModel model, ICompileContext context)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            this.model   = model;
            this.context = context;
        }
コード例 #36
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var unicornFile = projectItem as UnicornFile;
            Assert.Cast(unicornFile, nameof(unicornFile));

            var snapshot = unicornFile.Snapshots.First();

            try
            {
                CompileUnicornFile(context, snapshot, unicornFile);
            }
            catch (NotImplementedException)
            {
                // using stub Sitecore.Kernel assembly in unit tests
            }
        }
コード例 #37
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var mediaFile = projectItem as MediaFile;
            if (mediaFile == null)
            {
                return;
            }

            var project = mediaFile.Project;
            var snapshot = mediaFile.Snapshots.First();

            var guid = StringHelper.GetGuid(project, mediaFile.ItemPath);
            var item = context.Factory.Item(project, new SnapshotTextNode(snapshot), guid, mediaFile.DatabaseName, mediaFile.ItemName, mediaFile.ItemPath, string.Empty);
            item.ItemNameProperty.AddSourceTextNode(new FileNameTextNode(mediaFile.ItemName, snapshot));
            item.TemplateIdOrPathProperty.SetValue("/sitecore/templates/System/Media/Unversioned/File");
            item.IsEmittable = false;
            item.OverwriteWhenMerging = true;
            item.MergingMatch = MergingMatch.MatchUsingSourceFile;

            var addedItem = project.AddOrMerge(item);
            mediaFile.MediaItemUri = addedItem.Uri;
        }
コード例 #38
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            // todo: restrict the assemblies and types to compile to increase performance

            var binFile = projectItem as BinFile;
            Assert.Cast(binFile, nameof(binFile));

            try
            {
                var assembly = Assembly.ReflectionOnlyLoadFrom(binFile.Snapshots.First().SourceFile.AbsoluteFileName);

                foreach (var type in assembly.GetExportedTypes())
                {
                    context.Pipelines.Resolve<BinFileCompilerPipeline>().Execute(context, binFile, type);
                }
            }
            catch (Exception ex)
            {
                context.Trace.TraceError(ex.Message, binFile.FilePath);
            }

        }
コード例 #39
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var mediaFile = projectItem as MediaFile;
            Assert.Cast(mediaFile, nameof(mediaFile));

            var extension = Path.GetExtension(mediaFile.Snapshots.First().SourceFile.AbsoluteFileName).TrimStart('.').ToLowerInvariant();

            var templateIdOrPath = context.Configuration.GetString(Constants.Configuration.BuildProjectMediaTemplate + ":" + extension, "/sitecore/templates/System/Media/Unversioned/File");

            var project = mediaFile.Project;
            var snapshot = mediaFile.Snapshots.First();

            var guid = StringHelper.GetGuid(project, mediaFile.ItemPath);
            var item = context.Factory.Item(project, new SnapshotTextNode(snapshot), guid, mediaFile.DatabaseName, mediaFile.ItemName, mediaFile.ItemPath, string.Empty);
            item.ItemNameProperty.AddSourceTextNode(new FileNameTextNode(mediaFile.ItemName, snapshot));
            item.TemplateIdOrPathProperty.SetValue(templateIdOrPath);
            item.IsEmittable = false;
            item.OverwriteWhenMerging = true;
            item.MergingMatch = MergingMatch.MatchUsingSourceFile;

            var addedItem = project.AddOrMerge(item);
            mediaFile.MediaItemUri = addedItem.Uri;
        }
コード例 #40
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;
            if (item == null)
            {
                return;
            }

            var templateIdOrPathTextNode = item.SourceTextNodes.Select(n => n.GetAttribute("Template")).FirstOrDefault(t => t != null);
            if (templateIdOrPathTextNode == null)
            {
                context.Trace.TraceError(Msg.C1051, Texts.The__Template__attribute_must_be_specified_when__Template_CreateFromFields__equals_true_, TraceHelper.GetTextNode(item));
            }

            var itemTextNode = item.SourceTextNodes.First();
            var itemIdOrPath = item.TemplateIdOrPath;

            var itemName = itemIdOrPath.Mid(itemIdOrPath.LastIndexOf('/') + 1);
            var guid = StringHelper.GetGuid(item.Project, itemTextNode.GetAttributeValue("Template.Id", itemIdOrPath));
            var template = context.Factory.Template(item.Project, guid, itemTextNode, item.DatabaseName, itemName, itemIdOrPath);

            template.ItemNameProperty.AddSourceTextNode(templateIdOrPathTextNode);
            template.ItemNameProperty.Flags = SourcePropertyFlags.IsQualified;

            template.IconProperty.Parse("Template.Icon", itemTextNode);
            template.BaseTemplatesProperty.Parse("Template.BaseTemplates", itemTextNode, Constants.Templates.StandardTemplate);
            template.ShortHelpProperty.Parse("Template.ShortHelp", itemTextNode);
            template.LongHelpProperty.Parse("Template.LongHelp", itemTextNode);
            template.IsEmittable = !string.Equals(itemTextNode.GetAttributeValue(Constants.Fields.IsEmittable), "False", StringComparison.OrdinalIgnoreCase);
            template.IsImport = item.IsImport || string.Equals(itemTextNode.GetAttributeValue(Constants.Fields.IsExtern), "True", StringComparison.OrdinalIgnoreCase);

            if (!template.IsImport)
            {
                template.References.AddRange(context.ReferenceParser.ParseReferences(template, template.BaseTemplatesProperty));
            }

            if (item.Fields.Any())
            {
                var templateSectionGuid = StringHelper.GetGuid(projectItem.Project, template.ItemIdOrPath + "/Fields");

                // section
                var templateSection = context.Factory.TemplateSection(template, templateSectionGuid, TextNode.Empty);
                template.Sections.Add(templateSection);
                templateSection.SectionNameProperty.SetValue("Fields");
                templateSection.IconProperty.SetValue("Applications/16x16/form_blue.png");

                // fields
                var nextSortOrder = 0;
                foreach (var field in item.Fields)
                {
                    var childNode = field.SourceTextNodes.First();

                    // ignore standard fields
                    if (item.Project.Options.StandardTemplateFields.Contains(field.FieldName, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var templateField = template.Sections.SelectMany(s => s.Fields).FirstOrDefault(f => f.FieldName == field.FieldName);
                    if (templateField == null)
                    {
                        var templateFieldGuid = StringHelper.GetGuid(projectItem.Project, template.ItemIdOrPath + "/Fields/" + field.FieldName);
                        templateField = context.Factory.TemplateField(template, templateFieldGuid, childNode);
                        templateSection.Fields.Add(templateField);

                        templateField.FieldNameProperty.SetValue(field.FieldNameProperty);
                        templateField.TypeProperty.Parse("Field.Type", childNode, "Single-Line Text");
                        templateField.SortOrderProperty.Parse("Field.SortOrder", childNode, nextSortOrder);
                    }
                    else
                    {
                        // todo: multiple sources?
                        templateField.FieldNameProperty.AddSourceTextNode(field.FieldNameProperty.SourceTextNode);
                        templateField.TypeProperty.ParseIfHasAttribute("Field.Type", childNode);
                        templateField.SortOrderProperty.ParseIfHasAttribute("Field.SortOrder", childNode);
                    }

                    templateField.Shared |= string.Equals(childNode.GetAttributeValue("Field.Sharing"), "Shared", StringComparison.OrdinalIgnoreCase);
                    templateField.Unversioned |= string.Equals(childNode.GetAttributeValue("Field.Sharing"), "Unversioned", StringComparison.OrdinalIgnoreCase);
                    templateField.SourceProperty.ParseIfHasAttribute("Field.Source", childNode);
                    templateField.ShortHelpProperty.ParseIfHasAttribute("Field.ShortHelp", childNode);
                    templateField.LongHelpProperty.ParseIfHasAttribute("Field.LongHelp", childNode);

                    nextSortOrder = templateField.SortOrder + 100;

                    // todo: added multiple times if merged
                    template.References.AddRange(context.ReferenceParser.ParseReferences(template, templateField.SourceProperty));
                }
            }

            item.Project.AddOrMerge(template);
        }
コード例 #41
0
 public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
 {
     return projectItem is MediaFile;
 }
コード例 #42
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var unicornFile = projectItem as UnicornFile;
            Assert.Cast(unicornFile, nameof(unicornFile));

            var snapshot = unicornFile.Snapshots.First();

            // todo: use real Unicorn configuration instead of hacking it
            var formatter = new YamlSerializationFormatter(null, new AllFieldFilter());
            using (var stream = new FileStream(snapshot.SourceFile.AbsoluteFileName, FileMode.Open))
            {
                var serializedItem = formatter.ReadSerializedItem(stream, unicornFile.ShortName);

                var guid = serializedItem.Id;
                var databaseName = serializedItem.DatabaseName ?? unicornFile.DatabaseName;
                var itemIdOrPath = serializedItem.Path;
                var itemName = serializedItem.Name;
                var templateIdOrPath = serializedItem.TemplateId.Format();

                var item = context.Factory.Item(unicornFile.Project, snapshot, guid, databaseName, itemName, itemIdOrPath, templateIdOrPath);
                item.ItemNameProperty.AddSourceTextNode(snapshot);
                item.IsEmittable = false;
                item.IsImport = false;

                item.References.AddRange(context.ReferenceParser.ParseReferences(item, item.TemplateIdOrPathProperty));

                foreach (var sharedField in serializedItem.SharedFields)
                {
                    var field = context.Factory.Field(item);

                    if (!string.IsNullOrEmpty(sharedField.NameHint))
                    {
                        field.FieldName = sharedField.NameHint;
                    }

                    field.FieldId = sharedField.FieldId;
                    field.Value = sharedField.Value;

                    context.ReferenceParser.ParseReferences(item, field.ValueProperty);
                }

                foreach (var version in serializedItem.Versions)
                {
                    foreach (var versionedField in version.Fields)
                    {
                        var field = context.Factory.Field(item);

                        if (!string.IsNullOrEmpty(versionedField.NameHint))
                        {
                            field.FieldName = versionedField.NameHint;
                        }

                        field.FieldId = versionedField.FieldId;
                        field.Value = versionedField.Value;
                        field.Language = version.Language.ToString();
                        field.Version = version.VersionNumber;

                        context.ReferenceParser.ParseReferences(item, field.ValueProperty);
                    }
                }

                unicornFile.Project.AddOrMerge(item);
            }
        }
コード例 #43
0
        public override void Compile(ICompileContext context, IProjectItem projectItem)
        {
            var item = projectItem as Item;
            Assert.Cast(item, nameof(item));

            var value = item.GetValue<string>(LayoutHtmlfile)?.Trim() ?? string.Empty;
            if (string.IsNullOrEmpty(value))
            {
                return;
            }

            var property = item.GetProperty<string>(LayoutHtmlfile);

            var rendering = item.Project.ProjectItems.OfType<Rendering>().FirstOrDefault(i => string.Equals(i.FilePath, value, StringComparison.OrdinalIgnoreCase));
            if (rendering == null)
            {
                context.Trace.TraceError(Msg.C1047, Texts.Rendering_reference_not_found, TraceHelper.GetTextNode(property), value);
            }

            var layoutItem = item.Project.ProjectItems.OfType<Item>().FirstOrDefault(i => i.ItemIdOrPath == "/sitecore/layout/Layouts/MvcLayout");
            if (layoutItem == null)
            {
                context.Trace.TraceError(Msg.C1048, Texts.Layout_reference_not_found, TraceHelper.GetTextNode(property), "/sitecore/layout/Layouts/MvcLayout");
            }

            if (rendering == null || layoutItem == null)
            {
                return;
            }

            var renderingItemUri = rendering.RenderingItemUri;
            if (renderingItemUri == ProjectItemUri.Empty)
            {
                RetryCompilation(projectItem);
                return;
            }

            var renderingId = renderingItemUri.Guid.Format();

            var writer = new StringWriter();
            var output = new XmlTextWriter(writer);
            output.Formatting = Formatting.Indented;

            output.WriteStartElement("r");

            var deviceItems = item.Project.ProjectItems.OfType<Item>().Where(i => string.Equals(i.TemplateIdOrPath, "/sitecore/templates/System/Layout/Device", StringComparison.OrdinalIgnoreCase) || string.Equals(i.TemplateIdOrPath, "{B6F7EEB4-E8D7-476F-8936-5ACE6A76F20B}", StringComparison.OrdinalIgnoreCase));
            foreach (var deviceItem in deviceItems)
            {
                if (!deviceItem.ItemIdOrPath.StartsWith("/sitecore/layout/Devices/"))
                {
                    continue;
                }

                output.WriteStartElement("d");
                output.WriteAttributeString("id", deviceItem.Uri.Guid.Format());
                output.WriteAttributeString("l", layoutItem.Uri.Guid.Format());

                output.WriteStartElement("r");
                output.WriteAttributeString("id", renderingId);
                output.WriteAttributeString("ph", "Page.Body");
                output.WriteEndElement();

                output.WriteEndElement();
            }

            output.WriteEndElement();

            var field = item.Fields["__Renderings"];
            if (field == null)
            {
                field = context.Factory.Field(item, TextNode.Empty, "__Renderings", writer.ToString());
                item.Fields.Add(field);
            }
            else
            {
                field.Value = writer.ToString();
            }
        }
コード例 #44
0
 public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
 {
     var item = projectItem as Item;
     return item != null && item.ContainsProperty(LayoutHtmlfile);
 }
コード例 #45
0
 public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
 {
     return projectItem is Rendering;
 }
コード例 #46
0
 public abstract void Compile(ICompileContext context, IProjectItem projectItem);
コード例 #47
0
 public override bool CanCompile(ICompileContext context, IProjectItem projectItem)
 {
     return projectItem is SerializationFile;
 }
コード例 #48
0
 public abstract bool CanCompile(ICompileContext context, IProjectItem projectItem);