Example #1
1
 protected virtual void WriteChild(XmlTextWriter writer, ContentItem child)
 {
     using (ElementWriter childElement = new ElementWriter("child", writer))
     {
         childElement.WriteAttribute("id", child.ID);
     }
 }
Example #2
1
		internal static void Write(HierarchyNode<ContentItem> hierarchy, ContentItem selectedItem, IContentAdapterProvider adapters, ItemFilter filter, string selectableTypes, string selectableExtensions, bool excludeRoot, string target, TextWriter writer)
		{
			N2.Web.Tree.Using(hierarchy)
				.OpenTo(selectedItem)
				.Filters(filter)
				.IdProvider(n => "u" + n.Current.ID, n => "l" + n.Current.ID)
				.LinkWriter((n, w) =>
				{
					BuildLink(adapters.ResolveAdapter<NodeAdapter>(n.Current), n.Current, n.Current.Path == selectedItem.Path, target, IsSelectable(n.Current, selectableTypes, selectableExtensions)).WriteTo(w);
					if (n.Children.Count == 0 && adapters.ResolveAdapter<NodeAdapter>(n.Current).HasChildren(n.Current, filter))
					{
						var ul = new TagBuilder("ul");
						ul.AddCssClass("ajax");
						w.Write(ul.ToString(TagRenderMode.StartTag));

						var li = new TagBuilder("li");
						li.InnerHtml = "{url:" + Url.ParseTokenized("{ManagementUrl}/Content/Navigation/LoadTree.ashx")
							.AppendQuery("target", target)
							.AppendQuery(SelectionUtility.SelectedQueryKey, HttpUtility.UrlEncode(n.Current.Path))
							.AppendQuery("selectableTypes", selectableTypes)
							.AppendQuery("selectableExtensions", selectableExtensions)
							+ "}";
						w.Write(li.ToString());

						w.Write(ul.ToString(TagRenderMode.EndTag));
					}
				})
				.ExcludeRoot(excludeRoot)
				.WriteTo(writer);
		}
Example #3
0
 public void Read(XPathNavigator navigator, ContentItem item, ReadingJournal journal)
 {
     foreach (XPathNavigator detailCollectionElement in EnumerateChildren(navigator))
     {
         ReadDetailCollection(detailCollectionElement, item, journal);
     }
 }
Example #4
0
		/// <summary>Appends the creator node to the given collection.</summary>
		/// <param name="items"></param>
		/// <param name="engine"></param>
		/// <param name="parent"></param>
		/// <returns></returns>
		public static IEnumerable<ContentItem> AppendCreatorNode(this IEnumerable<ContentItem> items, IEngine engine, ContentItem parent)
		{
			if (parent.ID == 0)
				return items;

			return items.Union(new[] { new CreatorItem(engine, parent) });
		}
Example #5
0
	public Attachment(IAttachmentHandler handler, string url, ContentItem enclosingItem, byte[] fileContents)
	{
		_handler = handler;
		_url = url;
		_enclosingItem = enclosingItem;
		_fileContents = fileContents;
	}
Example #6
0
	public virtual ContentItem Navigate(ContentItem startingPoint, string path)
	{
		return startingPoint.GetChild(path)
			?? sources.ResolvePath(startingPoint, path).CurrentItem
			?? virtualNodes.Get(startingPoint.Path + path.TrimStart('/'))
			?? virtualNodes.Get(path);
	}
 public void Read(System.Xml.XPath.XPathNavigator navigator, ContentItem item, ReadingJournal journal)
 {
     foreach (XPathNavigator detailElement in EnumerateChildren(navigator))
     {
         ReadProperty(detailElement, item, journal);
     }
 }
Example #8
0
        protected override void OnInit(EventArgs e)
        {
            selectedItem = Selection.ParseSelectionFromRequest();

            if (selectedItem != null)
            {
                itemsToDelete.CurrentItem = selectedItem;
                itemsToDelete.DataBind();

                ParameterCollection query = Parameter.Equal("State", ContentState.Deleted);
                if (selectedItem.ID != 0)
                    query &= (Parameter.Like(LinkTracker.Tracker.LinkDetailName, selectedItem.Url).Detail() | Parameter.Equal(null, selectedItem).Detail());
                else
                    query &= Parameter.Like(LinkTracker.Tracker.LinkDetailName, selectedItem.Url).Detail();
                var count = Engine.Persister.Repository.Count(query);

                if (count > 0)
                {
                    chkAllow.Text += " (" + count + ")";
                    rptReferencing.DataSource = Engine.Persister.Repository.Find(query.Take(10)).Where(Content.Is.Distinct());
                    rptReferencing.DataBind();
                    hlReferencingItems.Visible = (count > 10);
                }
                else
                    referencingItems.Visible = false;

                this.hlReferencingItems.NavigateUrl = "Dependencies.aspx?" + SelectionUtility.SelectedQueryKey + "=" + selectedItem.Path + "&returnUrl=" + Server.HtmlEncode(Request.RawUrl);
            }

            base.OnInit(e);
        }
        public override void SetUp()
        {
            base.SetUp();

            root = CreateOneItem<RootNode>(1, "root", null);
            start = CreateOneItem<RootNode>(2, "start", root);
            host = new Host(new ThreadContext(), root.ID, start.ID);

            fs = new FakeMappedFileSystem();
            fs.BasePath = AppDomain.CurrentDomain.BaseDirectory + @"\FileSystem\";

            vnf = new VirtualNodeFactory();
            config = new EditSection();

            injector = new FakeDependencyInjector();
            injector.injectors.Add(new EntityDependencySetter<IFileSystem>(fs));
            injector.injectors.Add(new EntityDependencySetter<IDependencyInjector>(injector));
            var sizeCache = new ImageSizeCache(new ConfigurationManagerWrapper { Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, config) });
            injector.injectors.Add(new EntityDependencySetter<ImageSizeCache>(sizeCache));
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            //initializer = new VirtualFolderInitializer(host, persister, fs, vnf, new Plugin.ConnectionMonitor().SetConnected(SystemStatusLevel.UpAndRunning), config, new ImageSizeCache(new ConfigurationManagerWrapper { Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, config) }), nodeProvider);
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            //nodeProvider = new FolderNodeProvider(fs, persister, injector);
            nodeProvider = new FolderNodeProvider(fs, persister.Repository, injector);
            initializer = new VirtualFolderInitializer(host, persister, fs, vnf, monitor = new Plugin.ConnectionMonitor().SetConnected(SystemStatusLevel.UpAndRunning), new UploadFolderSource(host, config), nodeProvider);
        }
Example #10
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 #11
0
 public ViewPageResult(ContentItem thePage, IControllerMapper controllerMapper, IWebContext webContext, IActionInvoker actionInvoker)
 {
     _thePage = thePage;
     _controllerMapper = controllerMapper;
     _webContext = webContext;
     _actionInvoker = actionInvoker;
 }
Example #12
0
 public override bool Match(ContentItem item)
 {
     foreach (ItemFilter filter in filters)
         if (!filter.Match(item))
             return false;
     return true;
 }
Example #13
0
	/// <summary>Reorders children according to OrderBy.</summary>
	/// <param name="item">The item whose children to re-order.</param>
	/// <returns>Items that were changed in the process of ordering. These items needs to be saved for the order to be persisted.</returns>
	public virtual IEnumerable<ContentItem> ReorderChildren(ContentItem item)
	{
		switch (OrderBy)
		{
			case SortBy.Updated:
				return ReorderBy(item, "Updated");
			case SortBy.UpdatedDescending:
				return ReorderBy(item, "Updated DESC");
			case SortBy.CurrentOrder:
				return Utility.UpdateSortOrder(item.Children);
			case SortBy.Expression:
				return ReorderBy(item, SortExpression);
			case SortBy.Published:
				return ReorderBy(item, "Published");
			case SortBy.PublishedDescending:
				return ReorderBy(item, "Published DESC");
			case SortBy.Title:
				return ReorderBy(item, "Title");
			case SortBy.Unordered:
			case SortBy.Append:
				return Enumerable.Empty<ContentItem>();
			default:
				throw new ArgumentException("Unknown sort order: " + OrderBy);
		}
	}
Example #14
0
		/// <summary>Creates a navigation using unordered list elements.</summary>
		public static N2.Web.Tree Tree(this HtmlHelper html,
			ContentItem startsFrom = null,
			ContentItem current = null,
			int takeLevels = 2,
			bool parallelRoot = true,
			bool appendCreatorNode = false,
			ItemFilter filter = null,
			object htmlAttributes = null)
		{
			if (startsFrom == null) startsFrom = html.StartPage();
			if (current == null) current = html.CurrentPage();
			if (filter == null) filter = new NavigationFilter(html.ViewContext.HttpContext.User, html.ContentEngine().SecurityManager);

			var builder = parallelRoot
				? (HierarchyBuilder)new ParallelRootHierarchyBuilder(startsFrom, takeLevels)
				: (HierarchyBuilder)new TreeHierarchyBuilder(startsFrom, takeLevels);

			if (builder == null)
				throw new ArgumentException("builder == null");

			if (appendCreatorNode && ControlPanelExtensions.GetControlPanelState(html).IsFlagSet(ControlPanelState.DragDrop))
				builder.GetChildren = (i) => i == null ? null : i.Children.FindNavigatablePages().Where(filter).AppendCreatorNode(html.ContentEngine(), i);
			else
				builder.GetChildren = (i) => i == null ? null : i.Children.FindNavigatablePages().Where(filter);

			var tree = N2.Web.Tree.Using(builder);
			if (htmlAttributes != null)
				tree.Tag(ApplyToRootUl(htmlAttributes));

			ClassifyAnchors(startsFrom, current, parallelRoot, tree);

			return tree;
		}
Example #15
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 #16
0
        public UpdateContentItemAction(IView view, IController con, ContentItem item, PropertyDescriptor property, object previousValue)
        {
            _view = view;
            _con = con;

            _state = ContentItemState.Get(item);

            var name = property.Name;
            var value = previousValue;

            if (name == "Importer")
            {
                name = "ImporterName";
                value = ((ImporterTypeDescription)value).TypeName;
            }

            if (name == "Processor")
            {
                name = "ProcessorName";
                value = ((ProcessorTypeDescription)value).TypeName;
            }

            var field = _state.GetType().GetMember(name).SingleOrDefault() as FieldInfo;
            if (field == null)
            {
                if (!_state.ProcessorParams.ContainsKey(name))
                    throw new Exception();

                _state.ProcessorParams[name] = value;
            }
            else
            {
                field.SetValue(_state, value);
            }
        }
Example #17
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 #18
0
        public Displayable(HtmlHelper helper, string propertyName, ContentItem currentItem)
            : base(helper, currentItem)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            this.propertyName = propertyName;
        }
Example #19
0
		/// <summary>Gets the url for the navigation frame.</summary>
		/// <param name="selectedItem">The currently selected item.</param>
		/// <returns>An url.</returns>
		public virtual string GetNavigationUrl(ContentItem selectedItem)
		{
			if (selectedItem == null)
				return null;

			return Url.Parse(EditTreeUrl).AppendQuery(SelectionUtility.SelectedQueryKey, selectedItem.Path);
		}
Example #20
0
 protected override bool IsStartPage(ContentItem item)
 {
     foreach (Site site in Host.Sites)
         if (IsStartPage(item, site))
             return true;
     return base.IsStartPage(item);
 }
		public override bool UpdateItem(ContentItem item, Control editor)
		{
			TextBox tb = (TextBox)editor;
			string[] rows = tb.Text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
			for (int i = item.Children.Count - 1; i >= 0; --i)
			{
				int index = Array.FindIndex(rows, delegate(string row)
													  {
														  return row == item.Children[i].Title;
													  }
					);
				if (index < 0)
					Context.Persister.Delete(item.Children[i]);
			}
			for (int i = 0; i < rows.Length; i++)
			{
				ContentItem child = FindChild(item, rows[i]);
				if (child == null)
				{
					child = new Option();
					child.Title = rows[i];
					child.AddTo(item);
				}
				child.SortOrder = i;

				editor.RegisterItemToSave(child);
			}

			return true;
		}
Example #22
0
        private string GetClassName(ContentItem item)
        {
            var className = new StringBuilder();
	        var currentTime = N2.Utility.CurrentTime();
            if (!item.Published.HasValue || item.Published > currentTime)
                className.Append("unpublished ");
            else if (item.Published > currentTime.AddDays(-1))
                className.Append("day ");
            else if (item.Published > currentTime.AddDays(-7))
                className.Append("week ");
            else if (item.Published > currentTime.AddMonths(-1))
                className.Append("month ");

            if (item.Expires.HasValue && item.Expires <= currentTime)
                className.Append("expired ");

            if (!item.Visible)
                className.Append("invisible ");

            if (item.AlteredPermissions != Permission.None && item.AuthorizedRoles != null &&
                item.AuthorizedRoles.Count > 0)
                className.Append("locked ");

            return className.ToString();
        }
        public bool Transform(ContentItem item)
        {
            string text = item[Name] as string;
            if(text != null)
            {
                string detailName = Name + "_Tokens";
                int i = 0;
                var p = new Parser(new TemplateAnalyzer());
                foreach (var c in p.Parse(text).Where(c => c.Command != Parser.TextCommand))
                {
                    var dc = item.GetDetailCollection(detailName, true);
                    var cd = ContentDetail.Multi(detailName, stringValue: c.Tokens.Select(t => t.Fragment).StringJoin(), integerValue: c.Tokens.First().Index);
                    cd.EnclosingItem = item;
                    cd.EnclosingCollection = dc;

                    if (dc.Details.Count > i)
                        dc.Details[i] = cd;
                    else
                        dc.Details.Add(cd);
                    i++;
                }
                if (i > 0)
                {
                    var dc = item.GetDetailCollection(detailName, true);
                    for (int j = dc.Details.Count - 1; j >= i; j--)
                    {
                        dc.Details.RemoveAt(j);
                    }
                    return true;
                }
            }
            return false;
        }
Example #24
0
 private static bool IsAuthorized(object possiblySecurable, IPrincipal user, ContentItem item)
 {
     var securable = possiblySecurable as ISecurable;
     if (securable != null && securable.AuthorizedRoles != null && !PermissionMap.IsInRoles(user, securable.AuthorizedRoles))
         return false;
     return true;
 }
Example #25
0
		public override void Save(ContentItem item)
		{
			using (var tx = repository.BeginTransaction())
			{
				// update updated date unless it's a version being saved
				if (!item.VersionOf.HasValue)
					item.Updated = Utility.CurrentTime();
				// empty string names not allowed, null is replaced with item id
				if (string.IsNullOrEmpty(item.Name))
					item.Name = null;

				item.AddTo(item.Parent);
				
				// make sure the ordering is the same next time these siblings are loaded
				var unsavedItems = item.Parent.EnsureChildrenSortOrder();
				foreach (var itemToSave in unsavedItems.Union(new [] { item }))
				{
					repository.SaveOrUpdate(itemToSave);
				}

				// ensure a name, fallback to id
				if (string.IsNullOrEmpty(item.Name))
				{
					item.Name = item.ID.ToString();
					repository.SaveOrUpdate(item);
				}

				tx.Commit();
			}
		}
Example #26
0
 private static bool IsPermitted(ISecurityManager security, object possiblyPermittable, IPrincipal user, ContentItem item)
 {
     var permittable = possiblyPermittable as IPermittable;
     if (permittable != null && permittable.RequiredPermission > Permission.Read && !security.IsAuthorized(user, item, permittable.RequiredPermission))
         return false;
     return true;
 }
Example #27
0
        public override bool IsApplicable(ContentItem contentItem)
        {
            if (!contentItem.IsPage)
                return false;

            return base.IsApplicable(contentItem);
        }
Example #28
0
	public override Control AddTo(ContentItem item, string detailName, Control container)
	{
		Control displayer = (Control)Activator.CreateInstance(ControlType);
		Utility.SetProperty(displayer, ControlPropertyName, item[detailName]);
		container.Controls.Add(displayer);
		return displayer;
	}
Example #29
0
 protected ContentContextBase (ContentItem contentItem) {
     ContentItem = contentItem;
     Id = contentItem.Id;
     ContentType = contentItem.ContentType;
     ContentItemRecord = contentItem.Record;
     ContentManager = contentItem.ContentManager;
 }
Example #30
0
        public DraggableToolbar(ContentItem item, ItemDefinition definition)
        {
            if (definition == null) throw new ArgumentNullException("definition");

            this.currentItem = item;
            this.definition = definition;
        }