Example #1
0
        internal static bool IsSelectable(ContentItem item, string selectableTypes, string selectableExtensions)
        {
            var baseTypesAndInterfaceNames = item.GetContentType().GetInterfaces().Select(i => i.Name)
                .Union(Utility.GetBaseTypesAndSelf(item.GetContentType()).Select(t => t.Name));

            bool isSelectableType = string.IsNullOrEmpty(selectableTypes)
                || selectableTypes.Split(',').Intersect(baseTypesAndInterfaceNames).Any();

            bool isSelectableExtension = string.IsNullOrEmpty(selectableExtensions)
                || selectableExtensions.Split(',').Contains(item.Url.ToUrl().Extension, StringComparer.InvariantCultureIgnoreCase);

            return isSelectableType && isSelectableExtension;
        }
Example #2
0
        /// <summary>Gets route data for for items this route handles.</summary>
        /// <param name="item">The item whose route to get.</param>
        /// <param name="routeValues">The route values to apply to the route data.</param>
        /// <returns>A route data object or null.</returns>
        public virtual RouteValueDictionary GetRouteValues(ContentItem item, RouteValueDictionary routeValues)
        {
            string actionName = "Index";
            if (routeValues.ContainsKey(ActionKey))
                actionName = (string)routeValues[ActionKey];

            string id = null;
            if (routeValues.ContainsKey(IdKey))
                id = (string)routeValues[IdKey];

            string controllerName = controllerMapper.GetControllerName(item.GetContentType());
            if (controllerName == null || !controllerMapper.ControllerHasAction(controllerName, actionName))
                return null;

            var values = new RouteValueDictionary(routeValues);

            foreach (var kvp in innerRoute.Defaults)
                if(!values.ContainsKey(kvp.Key))
                    values[kvp.Key] = kvp.Value;

            values[ControllerKey] = controllerName;
            values[ActionKey] = actionName;
            values[ContentItemKey] = item.ID;
            values[AreaKey] = innerRoute.DataTokens["area"];

            if (!string.IsNullOrEmpty(id))
            {
                values[IdKey] = id;
            }

            return values;
        }
Example #3
0
        internal static ILinkBuilder BuildLink(NodeAdapter adapter, ContentItem item, bool isSelected, string target, bool isSelectable)
        {
            INode node = item;
            string className = node.ClassNames;
            if (isSelected)
                className += "selected ";
            if (isSelectable)
                className += "selectable ";
            else
                className += "unselectable ";

            ILinkBuilder builder = Link.To(node)
                .Target(target)
                .Class(className)
                .Href(adapter.GetPreviewUrl(item))
                .Text("<img src='" + adapter.GetIconUrl(item) + "'/>" + node.Contents)
                .Attribute("id", item.Path.Replace('/', '_'))
                .Attribute("title", "#" + item.ID + ": " + N2.Context.Current.Definitions.GetDefinition(item).Title)
                .Attribute("data-id", item.ID.ToString())
                .Attribute("data-type", item.GetContentType().Name)
                .Attribute("data-path", item.Path)
                .Attribute("data-url", item.Url)
                .Attribute("data-page", item.IsPage.ToString().ToLower())
                .Attribute("data-zone", item.ZoneName)
                .Attribute("data-permission", adapter.GetMaximumPermission(item).ToString());

            if (isSelected)
                builder.Attribute("data-selected", "true");
            if (isSelectable)
                builder.Attribute("data-selectable", "true");

            builder.Href(adapter.GetPreviewUrl(item));

            return builder;
        }
Example #4
0
		public virtual bool IsIndexable(ContentItem item)
		{
			if (item.GetContentType().GetCustomAttributes(true).OfType<IIndexableType>().Any(it => !it.IsIndexable))
				return false;

			return true;
		}
Example #5
0
        /// <summary>Checks whether an item  may have versions.</summary>
        /// <param name="item">The item to check.</param>
        /// <returns>True if the item is allowed to have versions.</returns>
        public bool IsVersionable(ContentItem item)
        {
            var versionables = (VersionableAttribute[])item.GetContentType().GetCustomAttributes(typeof(VersionableAttribute), true);
            bool isVersionable = versionables.Length == 0 || versionables[0].Versionable == N2.Definitions.AllowVersions.Yes;

            return isVersionable;
        }
Example #6
0
 private static void CopyAutoImplementedProperties(ContentItem source, ContentItem destination)
 {
     foreach (var property in source.GetContentType().GetProperties().Where(pi => pi.IsInterceptable()))
     {
         destination[property.Name] = TryClone(source[property.Name]);
     }
 }
Example #7
0
        public PathData GetPath(ContentItem item, string remainingUrl)
        {
            int slashIndex = remainingUrl.IndexOf('/');

            string action = remainingUrl;
            string arguments = null;
            if(slashIndex > 0)
            {
                action = remainingUrl.Substring(0, slashIndex);
                arguments = remainingUrl.Substring(slashIndex + 1);
            }

            var controllerName = controllerMapper.GetControllerName(item.GetContentType());
            if (string.IsNullOrEmpty(action) || string.Equals(action, "Default.aspx", StringComparison.InvariantCultureIgnoreCase))
                action = "Index";

            foreach (string method in methods)
            {
                if (string.Equals(method, action, StringComparison.InvariantCultureIgnoreCase))
                {
                    return new PathData(item, null, action, arguments)
                    {
                        IsRewritable = false,
                        TemplateUrl = string.Format("~/{0}/{1}", controllerName, method, item.ID) // workaround for start pages
                    };
                }
            }

            return null;
        }
Example #8
0
		private RouteValueDictionary GetRouteValues(HtmlHelper helper, ContentItem item)
		{
			Type itemType = item.GetContentType();
			string controllerName = controllerMapper.GetControllerName(itemType);
			if (string.IsNullOrEmpty(controllerName))
			{
				Engine.Logger.WarnFormat("Found no controller for type {0}", itemType);
				return null;
			}

			var values = new RouteValueDictionary();
			values[ContentRoute.ActionKey] = "Index";
			values[ContentRoute.ControllerKey] = controllerName;
			if (item.ID != 0)
				values[ContentRoute.ContentItemKey] = item.ID;
			else
				values[ContentRoute.ContentItemKey] = item;

			// retrieve the virtual path so we can figure out if this item is routed through an area
			var vpd = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, values);
			if (vpd == null)
				throw new InvalidOperationException("Unable to render " + item + " (" + controllerName + " did not match any route)");

			values["area"] = vpd.DataTokens["area"];
			return values;
		}
Example #9
0
 protected virtual void WriteDefaultAttributes(ElementWriter itemElement, ContentItem item)
 {
     itemElement.WriteAttribute("id", item.ID);
     itemElement.WriteAttribute("name", item.ID.ToString() == item.Name ? "" : item.Name);
     itemElement.WriteAttribute("parent", item.Parent != null ? item.Parent.ID.ToString() : string.Empty);
     itemElement.WriteAttribute("title", item.Title);
     itemElement.WriteAttribute("zoneName", item.ZoneName);
     itemElement.WriteAttribute("created", item.Created);
     itemElement.WriteAttribute("updated", item.Updated);
     itemElement.WriteAttribute("published", item.Published);
     itemElement.WriteAttribute("expires", item.Expires);
     itemElement.WriteAttribute("sortOrder", item.SortOrder);
     itemElement.WriteAttribute("url", parser.BuildUrl(item));
     itemElement.WriteAttribute("visible", item.Visible);
     itemElement.WriteAttribute("savedBy", item.SavedBy);
     itemElement.WriteAttribute("typeName", SerializationUtility.GetTypeAndAssemblyName(item.GetContentType()));
     itemElement.WriteAttribute("discriminator", definitions.GetDefinition(item.GetContentType()).Discriminator);
 }
 public virtual bool FilfilDependencies(ContentItem item)
 {
     bool dependenciesInjted = false;
     foreach (var provider in GetSetters(item.GetContentType()))
     {
         provider.Fulfil(item);
         dependenciesInjted = true;
     }
     return dependenciesInjted;
 }
			public ControllerWrapper(ContentItem item, IControllerMapper controllerMapper)
			{
				this.ID = "cw" + item.ID;
				ViewData = new ViewDataDictionary(item);
				this.item = item;
				this.controllerMapper = controllerMapper;
				itemType = item.GetContentType();
				controllerName = controllerMapper.GetControllerName(itemType);
				routes = RouteTable.Routes;
				httpContext = new HttpContextWrapper(HttpContext.Current);
			}
		public override void UpdateEditor(ContentItem item, Control editor)
		{
			ListControl lc = editor as ListControl;
			if (!editor.Page.IsPostBack)
			{
				lc.Items.Clear();
				lc.Items.AddRange(Engine.Definitions.GetTemplates(item.GetContentType()).Select(t => new ListItem(t.Title, t.Name ?? "")).ToArray());
			}

			base.UpdateEditor(item, editor);
		}
Example #13
0
        public PathData GetPath(ContentItem item, string remainingUrl)
        {
            if(string.IsNullOrEmpty(remainingUrl))
            {
                Type itemType = item.GetContentType();
                string virtualDirectory = ConventionTemplateDirectoryAttribute.GetDirectory(itemType);

                string templateName = otherTemplateName ?? itemType.Name;
                return new PathData(item, virtualDirectory + templateName + ".aspx");
            }
            return null;
        }
Example #14
0
		public virtual void RenderTemplate(HtmlHelper html, ContentItem model)
		{
			var renderer = model as Rendering.IContentRenderer
				?? RendererSelector.ResolveRenderer(model.GetContentType());
			if (renderer != null)
			{
				renderer.Render(new Rendering.ContentRenderingContext { Content = model, Html = html }, html.ViewContext.Writer);
				return;
			}

			Renderer.RenderTemplate(model, html);
		}
        public TemplateDefinition GetTemplate(ContentItem item)
        {
            string templateName = item["TemplateName"] as string;
            if(templateName == null)
                return null;

            return GetTemplates(item.GetContentType()).Where(t => t.Name == templateName).Select(t =>
            {
                t.Original = t.Template;
                t.Template = () => item;
                return t;
            }).FirstOrDefault();
        }
        public TemplateDefinition GetTemplate(ContentItem item)
        {
            string templateKey = item.TemplateKey;
            if(templateKey == null)
                return null;

            return GetTemplates(item.GetContentType()).Where(t => t.Name == templateKey).Select(t =>
            {
                t.OriginalFactory = t.TemplateFactory;
                t.TemplateFactory = () => item;
                return t;
            }).FirstOrDefault();
        }
Example #17
0
 private string ExecuteRelativityTransformers(ContentItem item, string detailName, string value)
 {
     var pi = item.GetContentType().GetProperty(detailName);
     if (pi != null)
     {
         var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
         foreach (IRelativityTransformer transformer in transformers)
         {
             if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                 value = transformer.Rebase(value, applicationPath, "~/");
         }
     }
     return value;
 }
        Control IDisplayable.AddTo(ContentItem item, string detailName, Control container)
        {
            if (!(item is IArticle)) throw new ArgumentException("The supplied item " + item.Path + "#" + item.ID + " of type '" + item.GetContentType().FullName + "' doesn't implement IArticle.", "item");

            WikiParser parser = Engine.Resolve<WikiParser>();
            WikiRenderer renderer = Engine.Resolve<WikiRenderer>();

            PlaceHolder ph = new PlaceHolder();
            container.Controls.Add(ph);

            renderer.AddTo(parser.Parse((string)item[detailName]), ph, item as IArticle);
            
            return ph;
        }
        public void RenderTemplate(ContentItem item, HtmlHelper helper)
        {
            Type itemType = item.GetContentType();
            string controllerName = controllerMapper.GetControllerName(itemType);
            if(string.IsNullOrEmpty(controllerName))
            {
                Trace.TraceWarning("Found no controller for type " + itemType);
                return;
            }

            RouteValueDictionary values = GetRouteValues(helper, item, controllerName);

            helper.RenderAction("Index", values);
        }
Example #20
0
        public void WriteTitleBar(TextWriter writer, ContentItem item, string returnUrl)
        {
            var definition = definitions.GetDefinition(item.GetContentType());

            writer.Write("<div class='titleBar ");
            writer.Write(definition.Discriminator);
            writer.Write("'>");

            WriteCommand(writer, "Edit part", "command edit", Url.Parse(managementUrls.GetEditExistingItemUrl(item)).AppendQuery("returnUrl", returnUrl).Encode());
            WriteCommand(writer, "Delete part", "command delete", Url.Parse(managementUrls.GetDeleteUrl(item)).AppendQuery("returnUrl", returnUrl).Encode());
            WriteTitle(writer, definition);

            writer.Write("</div>");
        }
 protected override IEnumerable<ContentDetail> GetDetails(ContentItem item)
 {
     ItemDefinition definition = definitions.GetDefinition(item.GetContentType());
     foreach (ContentDetail detail in item.Details.Values)
     {
         foreach (IEditable editable in definition.Editables)
         {
             if (detail.Name == editable.Name)
             {
                 yield return detail;
                 break;
             }
         }
     }
 }
Example #22
0
        public virtual void RenderPart(HtmlHelper html, ContentItem part, TextWriter writer = null)
        {
            var renderer = part as Rendering.IContentRenderer
                           ?? RendererSelector.ResolveRenderer(part.GetContentType());

            if (renderer != null)
            {
                renderer.Render(new Rendering.ContentRenderingContext {
                    Content = part, Html = html
                }, writer ?? html.ViewContext.Writer);
                return;
            }

            logger.WarnFormat("Using legacy template rendering for part {0}", part);
            new LegacyTemplateRenderer(Engine.Resolve <IControllerMapper>()).RenderTemplate(part, html);
        }
        public TemplateDefinition GetTemplate(ContentItem item)
        {
            string templateKey = item.TemplateKey;

            if (templateKey == null)
            {
                return(null);
            }

            return(GetTemplates(item.GetContentType()).Where(t => t.Name == templateKey).Select(t =>
            {
                t.OriginalFactory = t.TemplateFactory;
                t.TemplateFactory = () => item;
                return t;
            }).FirstOrDefault());
        }
Example #24
0
        /// <summary>Checks the root node in the database. Throws an exception if there is something really wrong with it.</summary>
        /// <returns>A diagnostic string about the root node.</returns>
        public override string CheckRootItem()
        {
            int         rootID   = host.DefaultSite.RootItemID;
            ContentItem rootItem = persister.Get(rootID);

            if (rootItem != null)
            {
                return(String.Format("Root node OK, id: {0}, name: {1}, type: {2}, discriminator: {3}, published: {4} - {5}",
                                     rootItem.ID, rootItem.Name, rootItem.GetContentType(),
                                     map.GetOrCreateDefinition(rootItem), rootItem.Published, rootItem.Expires));
            }
            else
            {
                return("No root item found with the id: " + rootID);
            }
        }
Example #25
0
        public TemplateDefinition GetTemplate(ContentItem item)
        {
            string templateName = item["TemplateName"] as string;

            if (templateName == null)
            {
                return(null);
            }

            return(GetTemplates(item.GetContentType()).Where(t => t.Name == templateName).Select(t =>
            {
                t.Original = t.Template;
                t.Template = item;
                return t;
            }).FirstOrDefault());
        }
        /// <summary>Checks the root node in the database. Throws an exception if there is something really wrong with it.</summary>
        /// <returns>A diagnostic string about the root node.</returns>
        public string CheckStartPage()
        {
            int         startID   = host.DefaultSite.StartPageID;
            ContentItem startPage = persister.Get(startID);

            if (startPage != null)
            {
                return(String.Format("Start page OK, id: {0}, name: {1}, type: {2}, discriminator: {3}, published: {4} - {5}",
                                     startPage.ID, startPage.Name, startPage.GetContentType(),
                                     map.GetOrCreateDefinition(startPage), startPage.Published, startPage.Expires));
            }
            else
            {
                return("No start page found with the id: " + startID);
            }
        }
Example #27
0
        /// <summary>Resolves a path based on the remaining url.</summary>
        /// <param name="item">The current item beeing navigated.</param>
        /// <param name="remainingUrl">The url remaining from previous segments.</param>
        /// <returns>A path data object that may be empty.</returns>
        public static PathData GetPath(ContentItem item, string remainingUrl)
        {
            IPathFinder[] finders = PathDictionary.GetFinders(item.GetContentType());

            foreach (IPathFinder finder in finders)
            {
                PathData data = finder.GetPath(item, remainingUrl);
                if (data != null)
                {
                    data.StopItem = item;
                    return(data);
                }
            }

            return(PathData.None(item, remainingUrl));
        }
		private void SetLinkedItems(XPathNavigator navigator, ReadingJournal journal, ContentItem item, string name)
		{
			var items = new ItemList();
			foreach (XPathNavigator itemElement in EnumerateChildren(navigator))
			{
				SetLinkedItem(itemElement.Value, journal, (foundItem) =>
					{
						items.Add(foundItem);
						var property = item.GetContentType().GetProperty(name);
						if (property != null)
							item[name] = items.ConvertTo(property.PropertyType, name);
						else
							item[name] = items;
					}, itemElement.GetAttribute("versionKey", ""));
			}
		}
Example #29
0
        public virtual void WriteDetail(ContentItem item, ContentDetail detail, XmlTextWriter writer)
        {
            using (ElementWriter detailElement = new ElementWriter("detail", writer))
            {
                detailElement.WriteAttribute("name", detail.Name);
                detailElement.WriteAttribute("typeName", SerializationUtility.GetTypeAndAssemblyName(detail.ValueType));

                if (detail.ValueType == typeof(object))
                {
                    string base64representation = SerializationUtility.ToBase64String(detail.Value);
                    detailElement.Write(base64representation);
                }
                else if (detail.ValueType == typeof(ContentItem))
                {
                    detailElement.Write(detail.LinkValue.HasValue ? detail.LinkValue.Value.ToString() : "0");
                }
                else if (detail.ValueType == typeof(string))
                {
                    string value = detail.StringValue;

                    if (!string.IsNullOrEmpty(value))
                    {
                        if (value.StartsWith(applicationPath, StringComparison.InvariantCultureIgnoreCase))
                        {
                            var pi = item.GetContentType().GetProperty(detail.Name);
                            if (pi != null)
                            {
                                var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
                                foreach (IRelativityTransformer transformer in transformers)
                                {
                                    if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                                        value = transformer.Rebase(value, applicationPath, "~/");
                                }
                            }
                        }

                        detailElement.WriteCData(value);
                    }
                }
                else if(detail.ValueType == typeof(DateTime)) {
                    detailElement.Write(ElementWriter.ToUniversalString(detail.DateTimeValue));
                }
                else {
                    detailElement.Write(detail.Value.ToString());
                }
            }
        }
Example #30
0
 private object PrepareStringDetail(ContentItem item, string name, string value)
 {
     if (value.StartsWith("~"))
     {
         var pi = item.GetContentType().GetProperty(name);
         if (pi != null)
         {
             var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
             foreach (IRelativityTransformer transformer in transformers)
             {
                 if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                     value = transformer.Rebase(value, "~/", applicationPath);
             }
         }
     }
     return value;
 }
		public void Read(XPathNavigator navigator, ContentItem item, ReadingJournal journal)
		{
			IDictionary<string, IAttachmentHandler> attachments = _explorer.Map<IAttachmentHandler>(item.GetContentType());
			
			foreach(XPathNavigator attachmentElement in EnumerateChildren(navigator))
			{
				string name = attachmentElement.GetAttribute("name", string.Empty);
				if(attachments.ContainsKey(name))
				{
					XPathNavigator attachmentContents = navigator.CreateNavigator();
					attachmentContents.MoveToFirstChild();
					Attachment a = attachments[name].Read(attachmentContents, item);
					if(a != null)
						journal.Report(a);
				}
			}
		}
Example #32
0
        public override void RenderTemplate(System.Web.Mvc.HtmlHelper html, ContentItem model)
        {
            string @class = "";
            if (model is BootstrapContainer)
            {
                @class = "container";
                if ((model as BootstrapContainer).Fluid)
                    @class += "-fluid";
            }
            else if (model is BootstrapSpan)
            {
                @class = "span" + (model as BootstrapSpan).Columns.ToString();
            }
            else if (model is BootstrapRow)
            {
                @class = "row";
                if ((model.Parent as BootstrapContainer).Fluid)
                    @class += "-fluid";
            }

            if (DesignMode)
            {
                string title = model.GetContentType().Name;
                html.ViewContext.Writer.Write(String.Format(
            @"

            <div style=""border: 1px solid #ccc; padding: 3px 3px 8px 3px; margin: 4px; width: 100%;"">
            <div style=""text-transform: uppercase; font-weight: bold; font-size: 8pt;"">{0}</div>
            <div>", title));
            }
            else
                html.ViewContext.Writer.Write(String.Format(@"<div class=""{0}"">", @class));

            html.DroppableZone(model, "Content").Render();

            if (DesignMode)
            {
                html.ViewContext.Writer.Write(@"

            </div>
            <div style=""clear: both;""></div>
            </div>");
            }
            else
                html.ViewContext.Writer.Write("</div>");
        }
Example #33
0
        protected override IEnumerable <ContentDetail> GetDetails(ContentItem item)
        {
            ItemDefinition definition = definitions.GetDefinition(item.GetContentType());

            foreach (ContentDetail detail in item.Details.Values)
            {
                foreach (IEditable editable in definition.Editables)
                {
                    if (detail.Name == editable.Name)
                    {
                        yield return(detail);

                        break;
                    }
                }
            }
        }
Example #34
0
        private string ExecuteRelativityTransformers(ContentItem item, string detailName, string value)
        {
            var pi = item.GetContentType().GetProperty(detailName);

            if (pi != null)
            {
                var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
                foreach (IRelativityTransformer transformer in transformers)
                {
                    if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                    {
                        value = transformer.Rebase(value, applicationPath, "~/");
                    }
                }
            }
            return(value);
        }
        private ExtendedContentInfo CreateExtendedContextData(ContentItem item, bool resolveVersions = false)
        {
            if (item == null)
            {
                return(null);
            }

            var data = new ExtendedContentInfo
            {
                Created       = item.Created.ToString("o"),
                Expires       = item.Expires.HasValue ? item.Expires.Value.ToString("o") : null,
                IsPage        = item.IsPage,
                Published     = item.Published.HasValue ? item.Published.Value.ToString("o") : null,
                SavedBy       = item.SavedBy,
                Updated       = item.Updated.ToString("o"),
                Visible       = item.Visible,
                ZoneName      = item.ZoneName,
                VersionIndex  = item.VersionIndex,
                Url           = item.Url,
                ReadProtected = !engine.SecurityManager.IsAuthorized(item, new GenericPrincipal(new GenericIdentity(""), null)),
                TypeName      = item.GetContentType().Name
            };

            if (resolveVersions)
            {
                var draftInfo = engine.Resolve <DraftRepository>().GetDraftInfo(item);
                data.Draft = CreateExtendedContextData(draftInfo != null ? engine.Resolve <IVersionManager>().GetVersion(item, draftInfo.VersionIndex) : null);
                if (data.Draft != null)
                {
                    data.Draft.SavedBy = draftInfo.SavedBy;
                    data.Draft.Updated = draftInfo.Saved.ToString("o");
                }
                data.VersionOf = CreateExtendedContextData(item.VersionOf);
            }
            ;
            if (item.State == ContentState.Waiting)
            {
                DateTime?futurePublishDate = (DateTime?)item["FuturePublishDate"];
                if (futurePublishDate.HasValue)
                {
                    data.FuturePublishDate = futurePublishDate.Value.ToString("o");
                }
            }
            return(data);
        }
Example #36
0
        /// <summary>Gets route data for for items this route handles.</summary>
        /// <param name="item">The item whose route to get.</param>
        /// <param name="routeValues">The route values to apply to the route data.</param>
        /// <returns>A route data object or null.</returns>
        public virtual RouteValueDictionary GetRouteValues(ContentItem item, RouteValueDictionary routeValues)
        {
            string actionName = "Index";

            if (routeValues.ContainsKey(ActionKey))
            {
                actionName = (string)routeValues[ActionKey];
            }

            string id = null;

            if (routeValues.ContainsKey(IdKey))
            {
                id = (string)routeValues[IdKey];
            }

            string controllerName = controllerMapper.GetControllerName(item.GetContentType());

            if (controllerName == null || !controllerMapper.ControllerHasAction(controllerName, actionName))
            {
                return(null);
            }

            var values = new RouteValueDictionary(routeValues);

            foreach (var kvp in innerRoute.Defaults)
            {
                if (!values.ContainsKey(kvp.Key))
                {
                    values[kvp.Key] = kvp.Value;
                }
            }

            values[ControllerKey]  = controllerName;
            values[ActionKey]      = actionName;
            values[ContentItemKey] = item.ID;
            values[AreaKey]        = innerRoute.DataTokens["area"];

            if (!string.IsNullOrEmpty(id))
            {
                values[IdKey] = id;
            }

            return(values);
        }
Example #37
0
		public void Write(ContentItem item, XmlTextWriter writer)
		{
			IList<IAttachmentHandler> attachments = explorer.Find<IAttachmentHandler>(item.GetContentType());
			if(attachments.Count > 0)
			{
				using(new ElementWriter("attachments", writer))
				{
					foreach(IAttachmentHandler attachment in attachments)
					{
						using (ElementWriter attachmentElement = new ElementWriter("attachment", writer))
						{
							attachmentElement.WriteAttribute("name", attachment.Name);
							attachment.Write(item, writer);
						}
					}
				}
			}
		}
 public void Write(ContentItem item, XmlTextWriter writer)
 {
     IList<IAttachmentHandler> attachments = explorer.Find<IAttachmentHandler>(item.GetContentType());
     if(attachments.Count > 0)
     {
         using(new ElementWriter("attachments", writer))
         {
             foreach(IAttachmentHandler attachment in attachments)
             {
                 using (ElementWriter attachmentElement = new ElementWriter("attachment", writer))
                 {
                     attachmentElement.WriteAttribute("name", attachment.Name);
                     attachment.Write(fs, item, writer);
                 }
             }
         }
     }
 }
Example #39
0
 protected virtual void WriteDefaultAttributes(ElementWriter itemElement, ContentItem item)
 {
     itemElement.WriteAttribute("id", item.ID);
     itemElement.WriteAttribute("name", item.ID.ToString() == item.Name ? "" : item.Name);
     itemElement.WriteAttribute("parent", item.Parent != null ? item.Parent.ID.ToString() : string.Empty);
     itemElement.WriteAttribute("title", item.Title);
     itemElement.WriteAttribute("zoneName", item.ZoneName);
     itemElement.WriteAttribute("created", item.Created);
     itemElement.WriteAttribute("updated", item.Updated);
     itemElement.WriteAttribute("published", item.Published);
     itemElement.WriteAttribute("expires", item.Expires);
     itemElement.WriteAttribute("sortOrder", item.SortOrder);
     itemElement.WriteAttribute("url", parser.BuildUrl(item));
     itemElement.WriteAttribute("visible", item.Visible);
     itemElement.WriteAttribute("savedBy", item.SavedBy);
     itemElement.WriteAttribute("typeName", SerializationUtility.GetTypeAndAssemblyName(item.GetContentType()));
     itemElement.WriteAttribute("discriminator", definitions.GetDefinition(item.GetContentType()).Discriminator);
 }
		public PathData GetPath(ContentItem item, string remainingUrl)
		{
			if (remainingUrl != null && (remainingUrl.ToLowerInvariant() == "Default.aspx" || remainingUrl.Contains("/")))
				return null;

			if (item == null)
				throw new ArgumentNullException("item");

			Type itemType = item.GetContentType();

			string templateName = _otherTemplateName ?? itemType.Name;

			string action = remainingUrl ?? DefaultAction;

			if (ActionDoesNotExistOnController(item, action))
				return null;

			return new PathData(item, templateName, action, String.Empty);
		}
Example #41
0
 private string PrepareStringDetail(ContentItem item, string name, string value)
 {
     if (value.StartsWith("~"))
     {
         var pi = item.GetContentType().GetProperty(name);
         if (pi != null)
         {
             var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
             foreach (IRelativityTransformer transformer in transformers)
             {
                 if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                 {
                     value = transformer.Rebase(value, "~/", applicationPath);
                 }
             }
         }
     }
     return(value);
 }
Example #42
0
        internal static ILinkBuilder BuildLink(NodeAdapter adapter, ContentItem item, bool isSelected, string target, bool isSelectable)
        {
            var node = adapter.GetTreeNode(item);
            string className = node.CssClass;
            if (isSelected)
                className += " selected";
            if (isSelectable)
                className += " selectable";
            else
                className += " unselectable";

            StringBuilder text = new StringBuilder();
            if (!string.IsNullOrEmpty(node.IconClass))
                text.AppendFormat("<b class='{0}'></b> ", node.IconClass);
            else if (!string.IsNullOrEmpty(node.IconUrl))
                text.AppendFormat("<img src='{0}' alt='icon'/>", node.IconUrl);
            if (string.IsNullOrEmpty(node.Title))
                text.Append(Utility.GetLocalResourceString("NoName") ?? "(no name)");
            else
                text.Append(node.Title);

            foreach (var mi in node.MetaInformation)
            {
                text.AppendFormat(" <span class='meta {0}' title='{1}'>{2}</span>", mi.Key, mi.Value.ToolTip, mi.Value.Text);
            }

            var builder = new Link(text.ToString(), node.ToolTip, node.Target ?? target, node.PreviewUrl, className)
                .Attribute("id", item.Path.Replace('/', '_'))
                .Attribute("data-id", item.ID.ToString())
                .Attribute("data-type", item.GetContentType().Name)
                .Attribute("data-path", item.Path)
                .Attribute("data-url", item.Url)
                .Attribute("data-page", item.IsPage.ToString().ToLower())
                .Attribute("data-zone", item.ZoneName)
                .Attribute("data-permission", node.MaximumPermission.ToString());

            if (isSelected)
                builder.Attribute("data-selected", "true");
            if (isSelectable)
                builder.Attribute("data-selectable", "true");

            return builder;
        }
        public override void UpdateEditor(ContentItem item, Control editor)
        {
            ItemEditorList listEditor = (ItemEditorList)editor;
            listEditor.ParentItem = item;
            listEditor.ZoneName = ZoneName;

            // filtering of children by property generic type
            PropertyInfo info = item.GetContentType().GetProperty(Name);
            if (info != null)
            {
                foreach (Type argument in info.PropertyType.GetGenericArguments())
                {
                    if (typeof(ContentItem).IsAssignableFrom(argument) || argument.IsInterface)
                    {
                        listEditor.MinimumType = argument;
                        break;
                    }
                }
            }
        }
Example #44
0
        public TemplateDefinition GetTemplate(ContentItem item)
        {
            //var httpContext = _httpContextProvider.Get();
            //if (httpContext != null)
            //    if (RegistrationExtensions.GetRegistrationExpression(httpContext) != null)
            //        return null;

            var templateKey = item.TemplateKey;

            if (templateKey == null)
            {
                return(null);
            }

            return(GetTemplates(item.GetContentType()).Where(t => t.Name == templateKey).Select(t =>
            {
                t.OriginalFactory = t.TemplateFactory;
                t.TemplateFactory = () => item;
                return t;
            }).FirstOrDefault());
        }
Example #45
0
        /// <summary>Check if an item can be created.</summary>
        /// <param name="item"></param>
        /// <param name="parent"></param>
        /// <returns>The exception that would be thrown if the item was created.</returns>
        public Exception GetCreateException(ContentItem item, ContentItem parent)
        {
            ItemDefinition parentDefinition = definitions.GetDefinition(parent);
            ItemDefinition itemDefinition   = definitions.GetDefinition(item);

            if (parentDefinition == null)
            {
                throw new InvalidOperationException("Couldn't find a definition for the parent item '" + parent + "' of type '" + parent.GetContentType() + "'");
            }
            if (itemDefinition == null)
            {
                throw new InvalidOperationException("Couldn't find a definition for the item '" + item + "' of type '" + item.GetContentType() + "'");
            }

            if (!parentDefinition.IsChildAllowed(definitions, parent, itemDefinition))
            {
                return(new NotAllowedParentException(itemDefinition, parent.GetContentType()));
            }

            return(null);
        }
Example #46
0
        public void CanReReadProperties_WithStrangeCharacters()
        {
            string      weirdo = "<[{zuuuuagh}]> & co?!=!";
            XmlableItem item   = CreateOneItem <XmlableItem>(1, "<[{zuuuuagh}]> co!=!", null);

            item.Title    = weirdo;
            item.ZoneName = weirdo;
            item.SavedBy  = weirdo;

            XPathNavigator sr       = SerializeAndReadOutput(item);
            ItemXmlReader  reader   = CreateReader();
            ContentItem    readItem = reader.Read(sr).RootItem;

            Assert.AreNotSame(item, readItem);
            Assert.AreEqual(typeof(XmlableItem), readItem.GetContentType());
            Assert.AreEqual(1, readItem.ID);
            Assert.AreEqual("<[{zuuuuagh}]> co!=!", readItem.Name);
            Assert.AreEqual(weirdo, readItem.Title);
            Assert.AreEqual(weirdo, readItem.ZoneName);
            Assert.AreEqual(weirdo, readItem.SavedBy);
        }
        private void SetLinkedItems(XPathNavigator navigator, ReadingJournal journal, ContentItem item, string name)
        {
            var items = new ItemList();

            foreach (XPathNavigator itemElement in EnumerateChildren(navigator))
            {
                SetLinkedItem(itemElement.Value, journal, (foundItem) =>
                {
                    items.Add(foundItem);
                    var property = item.GetContentType().GetProperty(name);
                    if (property != null)
                    {
                        item[name] = items.ConvertTo(property.PropertyType, name);
                    }
                    else
                    {
                        item[name] = items;
                    }
                }, itemElement.GetAttribute("versionKey", ""));
            }
        }
Example #48
0
        /// <summary>
        /// Returns a <see cref="ViewPageResult"/> which calls the default action for the controller that handles the current page.
        /// </summary>
        /// <returns></returns>
        protected internal virtual ViewPageResult ViewPage(ContentItem thePage)
        {
            if (thePage == null)
            {
                throw new ArgumentNullException("thePage");
            }

            if (!thePage.IsPage)
            {
                throw new InvalidOperationException("Item " + thePage.GetContentType().Name + " is not a page type and cannot be rendered on its own.");
            }

            if (thePage == CurrentItem)
            {
                throw new InvalidOperationException("The page passed into ViewPage was the current page. This would cause an infinite loop.");
            }

            var mapper     = Engine.Resolve <IControllerMapper>();
            var webContext = Engine.Resolve <IWebContext>();

            return(new ViewPageResult(thePage, mapper, webContext, ActionInvoker));
        }
Example #49
0
        internal string PrepareStringDetail(ContentItem item, string name, string value, bool encoded)
        {
            if (encoded)
            {
                value = HttpUtility.HtmlDecode(value);
            }
            var pi = item.GetContentType().GetProperty(name);

            if (pi != null)
            {
                var transformers = pi.GetCustomAttributes(typeof(IRelativityTransformer), false);
                foreach (IRelativityTransformer transformer in transformers)
                {
                    if (transformer.RelativeWhen == RelativityMode.Always || transformer.RelativeWhen == RelativityMode.ImportingOrExporting)
                    {
                        value = transformer.Rebase(value, "~/", applicationPath);
                    }
                }
            }

            return(value);
        }
Example #50
0
        public override void UpdateEditor(ContentItem item, Control editor)
        {
            ItemEditorList listEditor = (ItemEditorList)editor;

            listEditor.ParentItem = item;
            listEditor.ZoneName   = ZoneName;

            // filtering of children by property generic type
            PropertyInfo info = item.GetContentType().GetProperty(Name);

            if (info != null)
            {
                foreach (Type argument in info.PropertyType.GetGenericArguments())
                {
                    if (typeof(ContentItem).IsAssignableFrom(argument) || argument.IsInterface)
                    {
                        listEditor.MinimumType = argument;
                        break;
                    }
                }
            }
        }
Example #51
0
        private ControllerContext BuildPageControllerContext(ControllerContext context)
        {
            string controllerName = _controllerMapper.GetControllerName(_thePage.GetContentType());

            var routeData = context.RouteData;

            routeData.ApplyCurrentItem(controllerName, "Index", _thePage, null);
            if (context.RouteData.DataTokens.ContainsKey(ContentRoute.ContentPartKey))
            {
                routeData.ApplyContentItem(ContentRoute.ContentPartKey, context.RouteData.DataTokens[ContentRoute.ContentPartKey] as ContentItem);
            }

            var requestContext = new RequestContext(context.HttpContext, routeData);

            var controller = (ControllerBase)ControllerBuilder.Current.GetControllerFactory()
                             .CreateController(requestContext, controllerName);

            controller.ControllerContext = new ControllerContext(requestContext, controller);
            controller.ViewData.ModelState.Merge(context.Controller.ViewData.ModelState);

            return(controller.ControllerContext);
        }
Example #52
0
        private TemplateDefinition CreateTemplateInfo(ContentItem template)
        {
            var clone = template.Clone(true);

            clone.SetDetail(TemplateDescription, null, typeof(string));
            clone.Title           = "";
            clone.Name            = null;
            clone["TemplateName"] = template.Name;
            var info = new TemplateDefinition
            {
                Name        = template.Name,
                Title       = template.Title,
                Description = template.GetDetail(TemplateDescription, ""),
                TemplateUrl = template.Url,
                Definition  = definitions.GetDefinition(template.GetContentType()).Clone(),
                Template    = clone,
                Original    = template
            };

            info.Definition.Template = template.Name;
            return(info);
        }
Example #53
0
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            RegisterClientScripts();

            string defaultDirectoryPath = "";

            if (UseDefaultUploadDirectory)
            {
                var         selection = new SelectionUtility(this, Context.GetEngine());
                ContentItem item      = selection.SelectedItem;
                var         start     = Find.ClosestOf <IStartPage>(item);
                Type        itemType  = item.GetContentType();
                if (start != null)
                {
                    var slug = N2.Context.Current.Resolve <Slug>();
                    defaultDirectoryPath = string.Format("{0}/content/{1}", start.Name, slug.Create(itemType.Name));
                }
                else
                {
                    defaultDirectoryPath = string.Format("/");
                }
            }

            PopupButton.Attributes["onclick"] = string.Format(OpenPopupFormat,
                                                              N2.Web.Url.ResolveTokens(BrowserUrl ?? Engine.ManagementPaths.MediaBrowserUrl.ToUrl().AppendQuery("mc=true")),
                                                              Input.ClientID,
                                                              PopupOptions,
                                                              PreferredSize,
                                                              !string.IsNullOrWhiteSpace(SelectableExtensions) ? SelectableExtensions : ImageExtensions,
                                                              defaultDirectoryPath,
                                                              InitialPath
                                                              );

            ClearButton.Attributes["onclick"] = "n2MediaSelection.clearMediaSelector('" + Input.ClientID + "'); return false;";

            ShowButton.Attributes["onclick"] = ThumbnailButton.Attributes["onclick"] = "n2MediaSelection.showMediaSelectorOverlay('" + Input.ClientID + "'); return false;";
        }
Example #54
0
        public static IDisplayable GetDisplayableAttribute(string propertyName, ContentItem item, bool swallowExceptions)
        {
            if (item == null)
            {
                return(ThrowUnless(swallowExceptions, new ArgumentNullException("item")));
            }

            PropertyInfo pi = item.GetContentType().GetProperty(propertyName);

            if (pi == null)
            {
                return(ThrowUnless(swallowExceptions, new N2Exception("No property '{0}' found on the item #{1} of type '{2}'.", propertyName, item.ID, item.GetContentType())));
            }
            else
            {
                IDisplayable[] attributes = (IDisplayable[])pi.GetCustomAttributes(typeof(IDisplayable), false);
                if (attributes.Length == 0)
                {
                    return(ThrowUnless(swallowExceptions, new N2Exception("No attribute implementing IDisplayable found on the property '{0}' of the item #{1} of type {2}", propertyName, item.ID, item.GetContentType())));
                }
                return(attributes[0]);
            }
        }
Example #55
0
        private TemplateDefinition CreateTemplateInfo(ContentItem template)
        {
            var info = new TemplateDefinition
            {
                Name            = template.Name,
                Title           = template.Title,
                Description     = template.GetDetail(TemplateDescription, ""),
                TemplateUrl     = template.Url,
                Definition      = map.GetOrCreateDefinition(template.GetContentType(), template.Name),
                TemplateFactory = () =>
                {
                    var clone = template.Clone(true);
                    clone.SetDetail(TemplateDescription, null, typeof(string));
                    clone.Title       = "";
                    clone.Name        = null;
                    clone.TemplateKey = template.Name;
                    return(clone);
                },
                OriginalFactory = () => template
            };

            return(info);
        }
Example #56
0
        /// <summary>
        /// Rebases a single item.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="fromUrl"></param>
        /// <param name="toUrl"></param>
        /// <returns></returns>
        public static IEnumerable <RebaseInfo> Rebase(ContentItem item, string fromUrl, string toUrl)
        {
            var rebasedLinks = new List <RebaseInfo>();

            foreach (var pi in item.GetContentType().GetProperties())
            {
                if (pi.CanRead == false || pi.CanWrite == false)
                {
                    continue;
                }

                foreach (IRelativityTransformer transformer in pi.GetCustomAttributes(typeof(IRelativityTransformer), false))
                {
                    if (transformer.RelativeWhen != RelativityMode.Always && transformer.RelativeWhen != RelativityMode.Rebasing)
                    {
                        continue;
                    }

                    string original = item.GetDetail(pi.Name) as string;

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

                    string rebased = transformer.Rebase(original, fromUrl, toUrl);
                    if (!string.Equals(original, rebased))
                    {
                        item.SetDetail(pi.Name, rebased, typeof(string));
                        rebasedLinks.Add(new RebaseInfo {
                            ItemID = item.ID, ItemTitle = item.Title, ItemPath = item.Path, PropertyName = pi.Name
                        });
                    }
                }
            }
            return(rebasedLinks);
        }
Example #57
0
        private ContentItem VersionAndSave(ContentItem item, IDictionary <string, Control> addedEditors, IPrincipal user)
        {
            using (ITransaction tx = persister.Repository.BeginTransaction())
            {
                if (ShouldCreateVersionOf(item))
                {
                    SaveVersion(item);
                }

                DateTime?initialPublished = item.Published;
                bool     wasUpdated       = UpdateItem(definitions.GetDefinition(item.GetContentType()), item, addedEditors, user).Length > 0;
                DateTime?updatedPublished = item.Published;

                // the item was the only version of an unpublished item - publish it
                if (initialPublished == null && updatedPublished == null)
                {
                    item.Published = Utility.CurrentTime();
                    stateChanger.ChangeTo(item, ContentState.Published);
                    wasUpdated = true;
                }

                if (wasUpdated || IsNew(item))
                {
                    if (item.VersionOf == null)
                    {
                        stateChanger.ChangeTo(item, ContentState.Published);
                    }
                    item.VersionIndex++;
                    persister.Save(item);
                }

                tx.Commit();

                OnItemSaved(new ItemEventArgs(item));
                return(item);
            }
        }
        /// <summary>Find out if a principal has a certain permission for an item.</summary>
        /// <param name="item">The item to check against.</param>
        /// <param name="user">The principal to check for allowance.</param>
        /// <param name="permission">The type of permission to map against.</param>
        /// <returns>True if the item has public access or the principal is allowed to access it.</returns>
        public virtual bool IsAuthorized(IPrincipal user, ContentItem item, Permission permission)
        {
            if (permission == Permission.None)
            {
                return(true);
            }
            if (item == null)
            {
                return(IsAuthorized(user, permission));
            }
            if (permission == Permission.Read)
            {
                return(IsAuthorized(item, user));
            }

            foreach (PermissionRemapAttribute remap in item.GetContentType().GetCustomAttributes(typeof(PermissionRemapAttribute), true))
            {
                permission = remap.Remap(permission);
            }

            return(Administrators.Authorizes(user, item, permission) ||
                   Editors.Authorizes(user, item, permission) ||
                   Writers.Authorizes(user, item, permission));
        }
Example #59
0
        private ContentItem VersionOnly(ContentItem item, IDictionary <string, Control> addedEditors, IPrincipal user)
        {
            using (ITransaction tx = persister.Repository.BeginTransaction())
            {
                if (ShouldCreateVersionOf(item))
                {
                    item = SaveVersion(item);
                }

                bool wasUpdated = UpdateItem(definitions.GetDefinition(item.GetContentType()), item, addedEditors, user).Length > 0;
                if (wasUpdated || IsNew(item))
                {
                    item.Published = null;
                    stateChanger.ChangeTo(item, ContentState.Draft);
                    item.VersionIndex++;
                    persister.Save(item);
                }

                tx.Commit();

                OnItemSaved(new ItemEventArgs(item));
                return(item);
            }
        }
Example #60
0
        /// <summary>Shorthand for resolving an adapter.</summary>
        /// <typeparam name="T">The type of adapter to get.</typeparam>
        /// <param name="engine">Used to resolve the provider.</param>
        /// <param name="item">The item whose adapter to get.</param>
        /// <returns>The most relevant adapter.</returns>
        internal static T GetContentAdapter <T>(this IEngine engine, ContentItem item) where T : AbstractContentAdapter
        {
            Type itemType = item != null?item.GetContentType() : typeof(ContentItem);

            return(engine.Resolve <IContentAdapterProvider>().ResolveAdapter <T>(itemType));
        }