Example #1
0
        public void CanEvaluateContentItemProperty()
        {
            item1.AddTo(item2);
            object value = N2.Utility.Evaluate(item1, "Parent");

            Assert.AreEqual(item2, value);
        }
Example #2
0
        public void MoveTo(ContentItem item, ContentItem parent, int index)
        {
            if (item.Parent != parent || !parent.Children.Contains(item))
            {
                item.AddTo(parent);
            }
            else if (parent.Children.Contains(item) && parent.Children.Last() != item)
            {
                item.AddTo(null);
                item.AddTo(parent);
            }

            IList <ContentItem> siblings = parent.Children;

            Utility.MoveToIndex(siblings, item, index);
            using (var tx = persister.Repository.BeginTransaction())
            {
                persister.Repository.SaveOrUpdate(item);
                foreach (ContentItem updatedItem in Utility.UpdateSortOrder(siblings))
                {
                    persister.Repository.SaveOrUpdate(updatedItem);
                }
                tx.Commit();
            }
        }
Example #3
0
        public void MoveTo(ContentItem item, ContentItem parent)
        {
            if (item.Parent == parent)
            {
                // move it last
                item.AddTo(null);
                item.AddTo(parent);
            }
            else if (item.Parent == null || !parent.Children.Contains(item))
            {
                item.AddTo(parent);
                if (ItemMoved != null)
                {
                    ItemMoved.Invoke(this, new DestinationEventArgs(item, parent));
                }
            }

            using (var tx = persister.Repository.BeginTransaction())
            {
                foreach (ContentItem updatedItem in Utility.UpdateSortOrder(parent.Children))
                {
                    persister.Repository.SaveOrUpdate(updatedItem);
                }
                tx.Commit();
            }
        }
Example #4
0
        protected virtual void HandleParentRelation(ContentItem item, string parent, string parentVersionKey, ReadingJournal journal)
        {
            int parentID = 0;

            if (int.TryParse(parent, out parentID) && parentID != 0)
            {
                ContentItem parentItem = journal.Find(parentID);
                if (parentItem != null)
                {
                    item.AddTo(parentItem);
                }
                else
                {
                    journal.Register(parentID, (laterParent) => item.AddTo(laterParent), isChild: true);
                }
            }
            if (!string.IsNullOrEmpty(parentVersionKey))
            {
                ContentItem parentItem = journal.Find(parentVersionKey);
                if (parentItem != null)
                {
                    item.AddTo(parentItem);
                }
                else
                {
                    journal.Register(parentVersionKey, (laterParent) => item.AddTo(laterParent), isChild: true);
                }
            }
        }
Example #5
0
        public void CanEvalueateAReallyLongExperssion()
        {
            item1.AddTo(item2);
            item2.AddTo(item3);
            item3.AddTo(item4);
            item4.AddTo(item5);
            object value = N2.Utility.Evaluate(item1, "Parent.Parent.Parent.Parent.ID");

            Assert.AreEqual(5, value);
        }
Example #6
0
        private string CreateItem(TemplateDefinition template, NameValueCollection request)
        {
            var path = new PathData(navigator.Navigate(request["below"]));

            if (!versionRepository.TryParseVersion(request[PathData.VersionIndexQueryKey], request[PathData.VersionKeyQueryKey], path))
            {
                path.CurrentItem = versions.AddVersion(path.CurrentItem, asPreviousVersion: false);
            }
            var page = path.CurrentItem;

            ContentItem item = activator.CreateInstance(template.Definition.ItemType, page);

            item.ZoneName    = request["zone"];
            item.TemplateKey = template.Name;

            string beforeVersionKey = request["beforeVersionKey"];
            string beforeSortOrder  = request["beforeSortOrder"];
            string belowVersionKey  = request["belowVersionKey"];
            string before           = request["before"];

            if (!string.IsNullOrEmpty(beforeVersionKey))
            {
                var beforeSibling = page.FindDescendantByVersionKey(beforeVersionKey);
                if (beforeSibling != null && beforeSibling.Parent != null)
                {
                    beforeSibling.Parent.InsertChildBefore(item, beforeSibling.SortOrder);
                }
                else
                {
                    item.AddTo(page);
                }
            }
            else
            {
                var parentToAddTo = page;
                if (!string.IsNullOrEmpty(belowVersionKey))
                {
                    parentToAddTo = page.FindDescendantByVersionKey(belowVersionKey)
                                    ?? page;
                }

                if (string.IsNullOrEmpty(beforeSortOrder))
                {
                    item.AddTo(parentToAddTo);
                }
                else
                {
                    int index = int.Parse(beforeSortOrder);
                    parentToAddTo.InsertChildBefore(item, index);
                }
            }

            versionRepository.Save(page);
            return(request["returnUrl"].ToUrl().SetQueryParameter(PathData.VersionIndexQueryKey, page.VersionIndex));
        }
Example #7
0
        public void Insert_AtIndex_MoveToNonLast()
        {
            item2.AddTo(item1);
            item3.AddTo(item1);
            item4.AddTo(item1);
            item5.AddTo(item1);

            N2.Utility.Insert(item2, item1, 2);

            Assert.AreEqual(item2, item1.Children[1]);
            Assert.AreEqual(4, item1.Children.Count);
        }
Example #8
0
		public void MoveTo(ContentItem item, ContentItem parent)
		{
			if (item.Parent == parent)
			{
				// move it last
				item.AddTo(null);
				item.AddTo(parent);
			}
			else if (item.Parent == null || !parent.Children.Contains(item))
				item.AddTo(parent);

		    UpdateSortOrderAndSave(parent);
		}
Example #9
0
		public void MoveTo(ContentItem item, ContentItem parent, int index)
		{
			if (item.Parent != parent || !parent.Children.Contains(item))
				item.AddTo(parent);
			else if (parent.Children.Contains(item) && parent.Children.Last() != item)
			{
				item.AddTo(null);
				item.AddTo(parent);
			}

			IList<ContentItem> siblings = parent.Children;
			Utility.MoveToIndex(siblings, item, index);
            UpdateSortOrderAndSave(parent);
   		}
        public void MoveTo(ContentItem item, ContentItem parent)
        {
            if (item.Parent == parent)
            {
                // move it last
                item.AddTo(null);
                item.AddTo(parent);
            }
            else if (item.Parent == null || !parent.Children.Contains(item))
            {
                item.AddTo(parent);
            }

            UpdateSortOrderAndSave(parent);
        }
Example #11
0
		public void MoveTo(ContentItem item, NodePosition position, ContentItem relativeTo)
		{
            if (relativeTo == null) throw new ArgumentNullException("item");
            if (relativeTo == null) throw new ArgumentNullException("relativeTo");
            if (relativeTo.Parent == null) throw new ArgumentException("The supplied item '" + relativeTo + "' has no parent to add to.", "relativeTo");
            
			if (item.Parent == null 
				|| item.Parent != relativeTo.Parent
				|| !item.Parent.Children.Contains(item))
				item.AddTo(relativeTo.Parent);

			IList<ContentItem> siblings = item.Parent.Children;
			
			int itemIndex = siblings.IndexOf(item);
			int relativeToIndex = siblings.IndexOf(relativeTo);
			
            if(itemIndex < 0)
            {
                if(position == NodePosition.Before)
                    siblings.Insert(relativeToIndex, item);
                else
                    siblings.Insert(relativeToIndex + 1, item);
            }
		    else if(itemIndex < relativeToIndex && position == NodePosition.Before)
				MoveTo(item, relativeToIndex - 1);
			else if (itemIndex > relativeToIndex && position == NodePosition.After)
				MoveTo(item, relativeToIndex + 1);
			else
				MoveTo(item, relativeToIndex);
		}
Example #12
0
        private LinkButton CreateButton(Control container, TemplateDefinition template)
        {
            var button = new LinkButton
            {
                ID   = "iel" + ID + "_" + template.Definition.GetDiscriminatorWithTemplateKey().Replace('/', '_'),
                Text = string.IsNullOrEmpty(template.Definition.IconUrl)
                    ? string.Format("<b class='{0}'></b> {1}", template.Definition.IconClass, template.Definition.Title)
                    : string.Format("<img src='{0}' alt='ico'/>{1}", template.Definition.IconUrl, template.Definition.Title),
                ToolTip          = template.Definition.ToolTip,
                CausesValidation = false,
                CssClass         = "addButton"
            };
            var closureDefinition = template.Definition;

            button.Command += (s, a) =>
            {
                var path = EnsureDraft(ParentItem);

                UpdateItemFromTopEditor(path);

                ContentItem item = CreateItem(closureDefinition);
                item.AddTo(path.CurrentItem, ZoneName);
                Utility.UpdateSortOrder(path.CurrentItem.Children).ToList();

                var cvr = Engine.Resolve <ContentVersionRepository>();
                cvr.Save(path.CurrentPage);

                RedirectToVersionOfSelf(path.CurrentPage);
            };
            container.Controls.Add(button);
            return(button);
        }
Example #13
0
        private void SaveAction(ContentItem item)
        {
            if (item is IActiveContent)
            {
                (item as IActiveContent).Save();
            }
            else
            {
                using (ITransaction transaction = itemRepository.BeginTransaction())
                {
                    if (item.VersionOf == null)
                    {
                        item.Updated = Utility.CurrentTime();
                    }
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        item.Name = null;
                    }

                    item.AddTo(item.Parent);
                    EnsureSortOrder(item);

                    itemRepository.SaveOrUpdate(item);
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        item.Name = item.ID.ToString();
                        itemRepository.SaveOrUpdate(item);
                    }

                    transaction.Commit();
                }
            }
            Invoke(ItemSaved, new ItemEventArgs(item));
        }
Example #14
0
        /// <summary>Copies an item and all sub-items to a destination</summary>
        /// <param name="source">The item to copy</param>
        /// <param name="destination">The destination below which to place the copied item</param>
        /// <param name="includeChildren">Whether child items should be copied as well.</param>
        /// <returns>The copied item</returns>
        public virtual ContentItem Copy(ContentItem source, ContentItem destination, bool includeChildren)
        {
            return(Utility.InvokeEvent(ItemCopying, this, source, destination, delegate(ContentItem copiedItem, ContentItem destinationItem)
            {
                if (copiedItem is IActiveContent)
                {
                    TraceInformation("ContentPersister.Copy " + source + " (is IActiveContent) to " + destination);
                    return (copiedItem as IActiveContent).CopyTo(destinationItem);
                }

                TraceInformation("ContentPersister.Copy " + source + " to " + destination);
                ContentItem cloned = copiedItem.Clone(includeChildren);
                if (cloned.Name == source.ID.ToString())
                {
                    cloned.Name = null;
                }
                cloned.AddTo(destination);

                Repository.SaveOrUpdateRecursive(cloned);
                EnsureName(cloned);

                Invoke(ItemCopied, new DestinationEventArgs(cloned, destinationItem));

                return cloned;
            }));
        }
Example #15
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();
            }
        }
        public void MoveTo(ContentItem item, ContentItem parent, int index)
        {
            if (item.Parent != parent || !parent.Children.Contains(item))
            {
                item.AddTo(parent);
            }
            else if (parent.Children.Contains(item) && parent.Children.Last() != item)
            {
                item.AddTo(null);
                item.AddTo(parent);
            }

            IList <ContentItem> siblings = parent.Children;

            Utility.MoveToIndex(siblings, item, index);
            UpdateSortOrderAndSave(parent);
        }
Example #17
0
 protected virtual void HandleParentRelation(ContentItem item, string parent, ReadingJournal journal)
 {
     if (!string.IsNullOrEmpty(parent))
     {
         int         parentID   = int.Parse(parent);
         ContentItem parentItem = journal.Find(parentID);
         item.AddTo(parentItem);
     }
 }
        private LinkButton CreateButton(Control container, TemplateDefinition template)
        {
            ((Page)HttpContext.Current.CurrentHandler).JavaScript("{ManagementUrl}/Resources/Js/LoadingModal.js?v=" + Register.ScriptVersion);

            var button = new LinkButton
            {
                ID   = "iel" + ID + "_" + template.Definition.GetDiscriminatorWithTemplateKey().Replace('/', '_'),
                Text = string.IsNullOrEmpty(template.Definition.IconUrl)
                    ? string.Format("<b class='{0}'></b> {1}", template.Definition.IconClass, template.Definition.Title)
                    : string.Format("<img src='{0}' alt='ico'/>{1}", template.Definition.IconUrl, template.Definition.Title),
                ToolTip          = template.Definition.ToolTip,
                CausesValidation = false,
                CssClass         = "addButton btnLoadingModal",
                OnClientClick    = "n2LoadingModal.openModal()"
            };

            button.Command += (s, a) =>
            {
                var parentEditor    = ItemUtility.FindInParents <ItemEditor>(Parent);
                var autoSaveVersion = parentEditor.GetAutosaveVersion();
                if (autoSaveVersion != null)
                {
                    //Posted back item has all the latest updates. Discard the auto-saved version if exists.
                    N2.Context.Current.Persister.Delete(autoSaveVersion);
                }

                var path = EnsureDraft(ParentItem);

                UpdateItemFromTopEditor(path);

                ContentItem item = CreateItem(template.Definition);
                item.AddTo(path.CurrentItem, ZoneName);
                Utility.UpdateSortOrder(path.CurrentItem.Children).ToList();

                //Fill the Title with Type Name if empty.
                if (string.IsNullOrEmpty(item.Title))
                {
                    item.Title = template.Definition.Discriminator;
                }

                if (path.CurrentPage.VersionOf.HasValue)
                {
                    var cvr = Engine.Resolve <ContentVersionRepository>();
                    cvr.Save(path.CurrentPage);
                }
                else
                {
                    Engine.Persister.SaveRecursive(path.CurrentPage);
                }

                RedirectToVersionOfSelf(path.CurrentPage);
            };
            container.Controls.Add(button);

            return(button);
        }
Example #19
0
		public void MoveTo(ContentItem item, ContentItem parent)
		{
			if (item.Parent == parent)
			{
				// move it last
				item.AddTo(null);
				item.AddTo(parent);
			}
			else if (item.Parent == null || !parent.Children.Contains(item))
				item.AddTo(parent);

			using (var tx = persister.Repository.BeginTransaction())
			{
				foreach (ContentItem updatedItem in Utility.UpdateSortOrder(parent.Children))
				{
					persister.Repository.SaveOrUpdate(updatedItem);
				}
				tx.Commit();
			}
		}
Example #20
0
		public void MoveTo(ContentItem item, ContentItem parent, int index)
		{
			if (item.Parent != parent || !parent.Children.Contains(item))
				item.AddTo(parent);
			else if (parent.Children.Contains(item) && parent.Children.Last() != item)
			{
				item.AddTo(null);
				item.AddTo(parent);
			}

			IList<ContentItem> siblings = parent.Children;
			Utility.MoveToIndex(siblings, item, index);
			using (var tx = persister.Repository.BeginTransaction())
			{
				foreach (ContentItem updatedItem in Utility.UpdateSortOrder(siblings))
				{
					persister.Repository.SaveOrUpdate(updatedItem);
				}
				tx.Commit();
			}
		}
Example #21
0
 private void OnReadingChildren(XPathNavigator navigator, ContentItem item)
 {
     if (navigator.MoveToFirstChild())
     {
         do
         {
             ContentItem child = OnReadingItem(navigator);
             child.AddTo(item);
         } while (navigator.MoveToNext());
         navigator.MoveToParent();
     }
 }
Example #22
0
        public void MoveTo(ContentItem item, NodePosition position, ContentItem relativeTo)
        {
            if (relativeTo == null)
            {
                throw new ArgumentNullException("item");
            }
            if (relativeTo == null)
            {
                throw new ArgumentNullException("relativeTo");
            }
            if (relativeTo.Parent == null)
            {
                throw new ArgumentException("The supplied item '" + relativeTo + "' has no parent to add to.", "relativeTo");
            }

            if (item.Parent == null ||
                item.Parent != relativeTo.Parent ||
                !item.Parent.Children.Contains(item))
            {
                item.AddTo(relativeTo.Parent);
            }

            IList <ContentItem> siblings = item.Parent.Children;

            int itemIndex       = siblings.IndexOf(item);
            int relativeToIndex = siblings.IndexOf(relativeTo);

            if (itemIndex < 0)
            {
                if (position == NodePosition.Before)
                {
                    siblings.Insert(relativeToIndex, item);
                }
                else
                {
                    siblings.Insert(relativeToIndex + 1, item);
                }
            }
            else if (itemIndex < relativeToIndex && position == NodePosition.Before)
            {
                MoveTo(item, relativeToIndex - 1);
            }
            else if (itemIndex > relativeToIndex && position == NodePosition.After)
            {
                MoveTo(item, relativeToIndex + 1);
            }
            else
            {
                MoveTo(item, relativeToIndex);
            }
        }
Example #23
0
        public virtual void Import(IImportRecord record, ContentItem destination, ImportOption options)
        {
            var security = N2.Context.Current.Resolve <ISecurityManager>();

            using (security.Disable())     // TODO restrict to Admin User
            {
                ResetIDs(record.ReadItems);
                if ((options & ImportOption.AllItems) == ImportOption.AllItems)
                {
                    record.RootItem.AddTo(destination);
                    if (_persister != null)
                    {
                        _persister.SaveRecursive(record.RootItem);
                    }
                }
                else if ((options & ImportOption.Children) == ImportOption.Children)
                {
                    RemoveReferences(record.ReadItems, record.RootItem);
                    while (record.RootItem.Children.Count > 0)
                    {
                        ContentItem child = record.RootItem.Children[0];
                        child.AddTo(destination);
                        if (_persister != null)
                        {
                            _persister.SaveRecursive(child);
                        }
                    }
                }
                else
                {
                    logger.ErrorFormat("Option {0} isn't supported", options);
                    throw new NotImplementedException("This option isn't implemented, sorry.");
                }
                if ((options & ImportOption.Attachments) == ImportOption.Attachments)
                {
                    foreach (Attachment a in record.Attachments)
                    {
                        try
                        {
                            a.Import(_fs);
                        }
                        catch (Exception ex)
                        {
                            logger.Warn(ex);
                            record.FailedAttachments.Add(a);
                        }
                    }
                }
            }
        }
Example #24
0
        public void AddTemplate(ContentItem templateItem)
        {
            TemplateContainer templates = container.GetOrCreateBelowRoot((c) =>
                {
                    c.Title = "Templates";
                    c.Name = "Templates";
                    c.Visible = false;
                    c.SortOrder = int.MaxValue - 1001000;
                });

            templateItem.Name = null;
            templateItem.AddTo(templates);
            persister.Save(templateItem);
        }
Example #25
0
        public void AddTemplate(ContentItem templateItem)
        {
            TemplateContainer templates = container.GetOrCreateBelowRoot((c) =>
            {
                c.Title     = "Templates";
                c.Name      = "Templates";
                c.Visible   = false;
                c.SortOrder = int.MaxValue - 1001000;
            });

            templateItem.Name = null;
            templateItem.AddTo(templates);
            persister.Save(templateItem);
        }
Example #26
0
        private ContentItem Create(ContentItem parent, Type type, string name, int depth, int i)
        {
            ContentItem item = activator.CreateInstance(type, parent);

            item.Name       = name + i;
            item.Title      = name + " " + i + " (" + depth + ")";
            item.ChildState = Collections.CollectionState.IsEmpty;
            if (item is IContentPage)
            {
                (item as IContentPage).Text = @"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec sagittis mi. Donec pharetra vestibulum facilisis. Sed sodales risus vel nulla vulputate volutpat. Mauris vel arcu in purus porta dapibus. Aliquam erat volutpat. Maecenas suscipit tincidunt purus porttitor auctor. Quisque eget elit at justo facilisis malesuada sit amet sit amet eros. Duis convallis porta congue. Nulla commodo faucibus diam in mollis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec ut nibh eu sapien ornare consectetur.</p>
<p>Aliquam id massa nec mi pellentesque rhoncus id vel neque. Pellentesque malesuada venenatis sollicitudin. Maecenas at nisl urna, vel feugiat ipsum. Integer imperdiet rhoncus libero sit amet ullamcorper. Vestibulum et purus et ipsum dignissim molestie id sed urna. Nulla vitae neque neque, tempor fermentum lectus. Proin pellentesque blandit diam, in vehicula ipsum suscipit vel. Pellentesque elementum feugiat egestas. Duis scelerisque metus suscipit massa mattis tempor. Vestibulum sed dolor sed felis pharetra semper eu sed quam. Nam vitae lectus nunc, in placerat dui. Vivamus massa lorem, faucibus in semper ac, tincidunt non massa.</p>";
            }
            item.AddTo(parent);
            return(item);
        }
Example #27
0
        private void DeleteRecursive(ContentItem itemToDelete)
        {
            using (logger.Indent())
            {
                foreach (ContentItem child in itemToDelete.Children.ToList())
                {
                    DeleteRecursive(child);
                }
            }

            itemToDelete.AddTo(null);

            logger.InfoFormat("Deleting {0}", itemToDelete);
            repository.Delete(itemToDelete);
        }
Example #28
0
 public override ContentItem Move(ContentItem source, ContentItem destination)
 {
     using (var tx = repository.BeginTransaction())
     {
         logger.Info("ContentPersister.MoveAction " + source + " to " + destination);
         source.AddTo(destination);
         foreach (var descendant in UpdateAncestralTrailRecursive(source, destination))
         {
             repository.SaveOrUpdate(descendant);
         }
         Save(source);
         tx.Commit();
     }
     return(source);
 }
Example #29
0
        private void CreateChildren(ContentItem parent, Type type, int depth)
        {
            if (depth == 0)
            {
                return;
            }

            int width = int.Parse(txtWidth.Text);

            for (int i = 1; i <= width; i++)
            {
                ContentItem item = Engine.Resolve <ContentActivator>().CreateInstance(type, parent);
                item.Name  = txtName.Text + i;
                item.Title = txtName.Text + " " + i;
                item.AddTo(parent);
                CreateChildren(item, type, depth - 1);
            }
        }
Example #30
0
        private void SaveAction(ContentItem item)
        {
            if (item is IActiveContent)
            {
                (item as IActiveContent).Save();
                Invoke(ItemSaved, new ItemEventArgs(item));
            }
            else
            {
                IEnumerable <ContentItem> reorderedChildren = null;
                using (ITransaction transaction = itemRepository.BeginTransaction())
                {
                    // delay saved event until a previously initiated transcation is completed
                    transaction.Committed += (s, a) => Invoke(ItemSaved, new ItemEventArgs(item));

                    if (!item.VersionOf.HasValue)
                    {
                        item.Updated = Utility.CurrentTime();
                    }
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        item.Name = null;
                    }

                    item.AddTo(item.Parent);
                    reorderedChildren = EnsureSortOrder(item);

                    itemRepository.SaveOrUpdate(item);
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        item.Name = item.ID.ToString();
                        itemRepository.SaveOrUpdate(item);
                    }

                    transaction.Commit();
                }

                if (reorderedChildren != null)
                {
                    itemRepository.BatchUpdate(reorderedChildren);
                }
            }
        }
        public void AddTemplate(ContentItem templateItem)
        {
            TemplateContainer templates = container.GetOrCreateBelowRoot((c) =>
            {
                c.Title     = "Templates";
                c.Name      = "Templates";
                c.Visible   = false;
                c.SortOrder = int.MaxValue - 1001000;
            });

            templateItem.Name = null;
            templateItem.AddTo(templates);

            using (var tx = repository.BeginTransaction())
            {
                repository.SaveOrUpdate(templateItem);
                tx.Commit();
            }
        }
Example #32
0
 private ContentItem MoveAction(ContentItem source, ContentItem destination)
 {
     if (source is IActiveContent)
     {
         TraceInformation("ContentPersister.MoveAction " + source + " (is IActiveContent) to " + destination);
         (source as IActiveContent).MoveTo(destination);
     }
     else
     {
         using (ITransaction transaction = itemRepository.BeginTransaction())
         {
             TraceInformation("ContentPersister.MoveAction " + source + " to " + destination);
             source.AddTo(destination);
             Save(source);
             transaction.Commit();
         }
     }
     Invoke(ItemMoved, new DestinationEventArgs(source, destination));
     return(null);
 }
Example #33
0
        public static PathData EnsureDraft(IVersionManager versions, ContentVersionRepository versionRepository, string versionIndex, string versionKey, ContentItem item)
        {
            item = versionRepository.ParseVersion(versionIndex, versionKey, item)
                   ?? item;

            var page = Find.ClosestPage(item);

            if (!page.VersionOf.HasValue)
            {
                page = versions.GetOrCreateDraft(page);
                item = page.FindPartVersion(item);
            }

            if (item.Parent != null && !item.Parent.Children.Contains(item))
            {
                item.AddTo(item.Parent);
            }

            return(new PathData(page, item));
        }
Example #34
0
        public static void InsertChildBefore(this ContentItem parent, ContentItem child, int beforeSortOrder)
        {
            bool wasAdded = false;

            for (int i = 0; i < parent.Children.Count; i++)
            {
                var sibling = parent.Children[i];
                if (sibling.SortOrder >= beforeSortOrder)
                {
                    parent.Children.Insert(i, child);
                    Utility.UpdateSortOrder(parent.Children);
                    wasAdded = true;
                    break;
                }
            }
            if (!wasAdded)
            {
                child.AddTo(parent);
                Utility.UpdateSortOrder(parent.Children);
            }
        }
Example #35
0
 public virtual void Import(IImportRecord record, ContentItem destination, ImportOption options)
 {
     ResetIDs(record.ReadItems);
     if ((options & ImportOption.AllItems) == ImportOption.AllItems)
     {
         record.RootItem.AddTo(destination);
         persister.SaveRecursive(record.RootItem);
     }
     else if ((options & ImportOption.Children) == ImportOption.Children)
     {
         RemoveReferences(record.ReadItems, record.RootItem);
         while (record.RootItem.Children.Count > 0)
         {
             ContentItem child = record.RootItem.Children[0];
             child.AddTo(destination);
             persister.SaveRecursive(child);
         }
     }
     else
     {
         logger.ErrorFormat("Option {0} isn't supported", options);
         throw new NotImplementedException("This option isn't implemented, sorry.");
     }
     if ((options & ImportOption.Attachments) == ImportOption.Attachments)
     {
         foreach (Attachment a in record.Attachments)
         {
             try
             {
                 a.Import(fs);
             }
             catch (Exception ex)
             {
                 logger.Warn(ex);
                 record.FailedAttachments.Add(a);
             }
         }
     }
 }
Example #36
0
        private static ContentItem Create(int parentID, Type type, string name, int depth, int i, string[] sentences, List <int> linkSource = null, bool images = false)
        {
            var         parent = Context.Current.Persister.Get(parentID);
            ContentItem item   = Context.Current.Resolve <ContentActivator>().CreateInstance(type, parent, null, asProxy: true);

            item.Name       = name + i;
            item.Title      = name + " " + i + " (" + depth + ")";
            item.ChildState = Collections.CollectionState.IsEmpty;
            item.State      = ContentState.Published;
            var fs         = Context.Current.Resolve <IFileSystem>();
            var persister  = Context.Current.Persister;
            var imageHtmls = images
                                ? fs.GetFilesRecursive("~/Upload/").Where(f => f.Name.EndsWith("jpg")).Select(f => "<img src='" + f.VirtualPath + "' alt='" + f.Name + "'/>").ToList()
                                : new List <string>();

            if (item is IContentPage)
            {
                (item as IContentPage).Text += string.Join("", Enumerable.Range(0, r.Next(1, 10)).Select(pi =>
                                                                                                         "<p>" + string.Join(" ", Enumerable.Range(0, r.Next(8) + 2).Select(si =>
                {
                    if (imageHtmls.Count > 0 && r.Next(100) < 5)
                    {
                        return(imageHtmls[r.Next(imageHtmls.Count)]);
                    }
                    if (r.Next(100) < 10 && linkSource != null && linkSource.Count > 1)
                    {
                        return("<a href='" + persister.Get(linkSource[r.Next(1, linkSource.Count)]).Url + "'>" + sentences[r.Next(sentences.Length)] + "</a>");
                    }
                    else
                    {
                        return(sentences[r.Next(sentences.Length)]);
                    }
                }).ToArray()) + "</p>").ToArray());
            }
            parent.ChildState |= Collections.CollectionState.ContainsVisiblePublicPages;
            item.AddTo(parent);
            return(item);
        }
Example #37
0
		public override ContentItem Move(ContentItem source, ContentItem destination)
		{
			using (var tx = repository.BeginTransaction())
			{
				Trace.TraceInformation("ContentPersister.MoveAction " + source + " to " + destination);
				source.AddTo(destination);
				foreach (var descendant in UpdateAncestralTrailRecursive(source, destination))
				{
					repository.SaveOrUpdate(descendant);
				}
				Save(source);
				tx.Commit();
			}
			return source;
		}
Example #38
0
		private void DeleteRecursive(ContentItem itemToDelete)
		{
			DeletePreviousVersions(itemToDelete);

			try
			{
				Trace.Indent();
				foreach (ContentItem child in itemToDelete.Children.ToList())
					DeleteRecursive(child);
			}
			finally
			{
				Trace.Unindent();
			}

			itemToDelete.AddTo(null);

			Trace.TraceInformation("DatabaseSource.DeleteRecursive " + itemToDelete);
			repository.Delete(itemToDelete);
		}
Example #39
0
 protected virtual void HandleParentRelation(ContentItem item, string parent, ReadingJournal journal)
 {
     if (!string.IsNullOrEmpty(parent))
     {
         int parentID = int.Parse(parent);
         ContentItem parentItem = journal.Find(parentID);
         item.AddTo(parentItem);
     }
 }
Example #40
0
 protected virtual void HandleParentRelation(ContentItem item, string parent, string parentVersionKey, ReadingJournal journal)
 {
     int parentID = 0;
     if (int.TryParse(parent, out parentID) && parentID != 0)
     {
         ContentItem parentItem = journal.Find(parentID);
         if (parentItem != null)
             item.AddTo(parentItem);
         else
             journal.Register(parentID, (laterParent) => item.AddTo(laterParent), isChild: true);
     }
     if (!string.IsNullOrEmpty(parentVersionKey))
     {
         ContentItem parentItem = journal.Find(parentVersionKey);
         if (parentItem != null)
             item.AddTo(parentItem);
         else
             journal.Register(parentVersionKey, (laterParent) => item.AddTo(laterParent), isChild: true);
     }
 }
Example #41
0
		private void DeleteRecursive(ContentItem itemToDelete)
		{
			using (logger.Indent())
			{
				foreach (ContentItem child in itemToDelete.Children.ToList())
					DeleteRecursive(child);
			}

			itemToDelete.AddTo(null);

			logger.InfoFormat("Deleting {0}", itemToDelete);
			repository.Delete(itemToDelete);
		}
Example #42
0
        public void MoveTo(ContentItem item, NodePosition position, ContentItem relativeTo)
        {
            if (relativeTo == null) throw new ArgumentNullException("item");
            if (relativeTo == null) throw new ArgumentNullException("relativeTo");
            if (relativeTo.Parent == null) throw new ArgumentException("The supplied item '" + relativeTo + "' has no parent to add to.", "relativeTo");

			using (var tx = persister.Repository.BeginTransaction())
			{
				if (item.Parent == null 
					|| item.Parent != relativeTo.Parent
					|| !item.Parent.Children.Contains(item))
				{
					item.AddTo(relativeTo.Parent);
					if (ItemMoved != null)
						ItemMoved.Invoke(this, new DestinationEventArgs(item, relativeTo.Parent));
					//foreach (ContentItem updatedItem in item.UpdateAncestralTrailRecursive(relativeTo.Parent))
					//{
					//	persister.Repository.SaveOrUpdate(updatedItem);
					//}
				}

				IList<ContentItem> siblings = item.Parent.Children;
            
				int itemIndex = siblings.IndexOf(item);
				int relativeToIndex = siblings.IndexOf(relativeTo);
            
				if(itemIndex < 0)
				{
					if(position == NodePosition.Before)
						siblings.Insert(relativeToIndex, item);
					else
						siblings.Insert(relativeToIndex + 1, item);
				}
				else if(itemIndex < relativeToIndex && position == NodePosition.Before)
					MoveTo(item, relativeToIndex - 1);
				else if (itemIndex > relativeToIndex && position == NodePosition.After)
					MoveTo(item, relativeToIndex + 1);
				else
					MoveTo(item, relativeToIndex);

				tx.Commit();
			}
        }
Example #43
0
        public void RegisterParentRelation(int parentID, ContentItem item)
		{
			Register(parentID, (laterParent) => item.AddTo(laterParent), isChild: true, relationType: "parent", referencingItem: item);
		}
Example #44
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 #45
0
		public static void InsertChildBefore(this ContentItem parent, ContentItem child, int beforeSortOrder)
		{
			bool wasAdded = false;
			for (int i = 0; i < parent.Children.Count; i++)
			{
				var sibling = parent.Children[i];
				if (sibling.SortOrder >= beforeSortOrder)
				{
					parent.Children.Insert(i, child);
					Utility.UpdateSortOrder(parent.Children);
					wasAdded = true;
					break;
				}
			}
			if (!wasAdded)
			{
				child.AddTo(parent);
				Utility.UpdateSortOrder(parent.Children);
			}
		}
Example #46
0
        public void AddTemplate(ContentItem templateItem)
        {
            TemplateContainer templates = container.GetOrCreateBelowRoot((c) =>
                {
                    c.Title = "Templates";
                    c.Name = "Templates";
                    c.Visible = false;
                    c.SortOrder = int.MaxValue - 1001000;
                });

            templateItem.Name = null;
            templateItem.AddTo(templates);

			using (var tx = repository.BeginTransaction())
			{
				repository.SaveOrUpdate(templateItem);
				tx.Commit();
			}
        }