Ejemplo n.º 1
0
        public static T CurrentItem <T>(this RouteValueDictionary data, string key, IPersister persister)
            where T : ContentItem
        {
            if (data.ContainsKey(key))
            {
                object value = data[key];
                if (value == null)
                {
                    return(null);
                }

                var item = value as T;
                if (item != null)
                {
                    return(item as T);
                }

                if (value is int)
                {
                    return(persister.Get((int)value) as T);
                }

                int itemId;
                if (value is string && int.TryParse(value as string, out itemId))
                {
                    return(persister.Get((int)value) as T);
                }
            }

            return(null);
        }
        public virtual ContentItem Navigate(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            if (!path.StartsWith("/"))
            {
                if (path.StartsWith("~"))
                {
                    return(Navigate(persister.Get(host.CurrentSite.StartPageID), path.Substring(1))
                           ?? sources.ResolvePath(path).CurrentItem
                           ?? virtualNodes.Get(path));
                }

                if (path.Equals("undefined")) // typical for JavaScript
                {
                    return(null);
                }

                // TODO consider returning null here instead of error
                throw new ArgumentException("The path must start with a slash '/', was '" + path + "'", "path");
            }

            return(Navigate(persister.Get(host.CurrentSite.RootItemID), path));
        }
Ejemplo n.º 3
0
        public IEnumerable <ILanguage> GetAvailableLanguages()
        {
            var languages = languagesCache.GetValue(host.CurrentSite.RootItemID, FindLanguagesRecursive);

            foreach (var language in languages)
            {
                yield return(persister.Get(language.ID) as ILanguage);
            }
        }
Ejemplo n.º 4
0
        /// <summary>Gets available languages.</summary>
        /// <returns>An enumeration of available languages.</returns>
        public IEnumerable <ILanguage> GetAvailableLanguages()
        {
            var languages = languagesCache.GetValue(site.StartPageID, FindLanguagesRecursive);

            foreach (var language in languages)
            {
                yield return(persister.Get(language.ID) as ILanguage);
            }
        }
Ejemplo n.º 5
0
 public override string CheckRootItem()
 {
     try
     {
         var root = persister.Get(host.DefaultSite.RootItemID);
         return(string.Format("Root: {0}", root));
     }
     catch (Exception ex)
     {
         return(ex.ToString());
     }
 }
Ejemplo n.º 6
0
        private void UpdateSortOrder(ContentItem item)
        {
            int languageKey;

            if (int.TryParse(GetLanguageKey(), out languageKey))
            {
                ContentItem translation = persister.Get(languageKey);
                if (translation != null)
                {
                    item.SortOrder = translation.SortOrder;
                }
            }
        }
Ejemplo n.º 7
0
        public virtual void ReindexDescendants(ContentItem root, bool clearBeforeReindex)
        {
            DoWork(() =>
            {
                if (clearBeforeReindex)
                {
                    indexer.Delete(root.ID);
                }

                root = persister.Get(root.ID);
                indexer.Update(root);
                ReindexChildren(root.ID);
            });
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Rebases all items.
        /// </summary>
        /// <param name="fromUrl"></param>
        /// <param name="toUrl"></param>
        /// <returns></returns>
        /// <remarks>The return enumeration must be enumerated in order for the changes to take effect.</remarks>
        public IEnumerable <RebaseInfo> Rebase(string fromUrl, string toUrl)
        {
            using (var tx = persister.Repository.BeginTransaction())
            {
                foreach (var item in finder.All.Select())
                {
                    bool changed = false;
                    foreach (var info in Rebase(item, fromUrl, toUrl))
                    {
                        changed = true;
                        yield return(info);
                    }
                    if (changed)
                    {
                        persister.Repository.SaveOrUpdate(item);
                    }
                }

                ContentItem root = persister.Get(host.DefaultSite.RootItemID);
                root[InstallationManager.InstallationAppPath] = toUrl;
                persister.Repository.SaveOrUpdate(root);

                persister.Repository.Flush();
                tx.Commit();
            }
        }
Ejemplo n.º 9
0
        public virtual void AddAnswer(IPersister persister, int selectedItem)
        {
            Option o = persister.Get <Option>(selectedItem);

            o.Answers++;
            persister.Save(o);
        }
Ejemplo n.º 10
0
        public void ThrashHandler_Throw_WillInvokeEvents()
        {
            var activator = new ContentActivator(null, null, null);

            IPersister persister = mocks.StrictMock <IPersister>();

            Expect.Call(persister.Get(1)).Return(root).Repeat.Any();
            Expect.Call(delegate { persister.Save(item); }).Repeat.Any();

            mocks.ReplayAll();

            var          host = new Host(webContext, 1, 1);
            TrashHandler th   = new TrashHandler(persister, null, null, new ContainerRepository <TrashContainerItem>(persister, null, host, activator), new StateChanger())
            {
                UseNavigationMode = true
            };

            bool throwingWasInvoked = false;
            bool throwedWasInvoked  = false;

            th.ItemThrowing += delegate { throwingWasInvoked = true; };
            th.ItemThrowed  += delegate { throwedWasInvoked = true; };
            th.Throw(item);

            Assert.That(throwingWasInvoked);
            Assert.That(throwedWasInvoked);

            mocks.VerifyAll();
        }
        public override void Execute()
        {
            // get app root
            var root = _persister.Get(_host.DefaultSite.RootItemID);

            _base = root[InstallationManager.InstallationAppPath] as string ?? "";
            //logger.Info("LinkFixupScheduledAction BASE:" + _base + " actual " + Url.ToAbsolute("~/"));

            // identify types that need inspection

            /*var types = (from def in _definitions.GetDefinitions()
             *           from attr in def.Attributes
             *           where attr is EditableImageAttribute || attr is EditableImageExAttribute || attr is EditableLinkAttribute || attr is EditableUrlAttribute
             *           select def.ItemType).ToList();
             */

            /* TODO foreach (var def in _definitions.GetDefinitions())
             * {
             *  foreach (var attr in def.Attributes)
             *  {
             *      logger.Debug(attr.ToString());
             *  }
             * }*/

            //var types = new Type[]()  PromotionOffer, NavLink];
            //types.ForEach(FixType);
            //FixType(typeof(PromotionOffer));
            //FixType(typeof(NavLink));

            //logger.Info("LinkFixupScheduledAction DONE:");
            //foreach (var s in _fixedItems) { logger.Debug(s); }
        }
Ejemplo n.º 12
0
 private void UpdateItems(DatabaseStatus status)
 {
     try
     {
         status.StartPageID = host.DefaultSite.StartPageID;
         status.RootItemID  = host.DefaultSite.RootItemID;
         status.StartPage   = persister.Get(status.StartPageID);
         status.RootItem    = persister.Get(status.RootItemID);
         status.IsInstalled = status.RootItem != null && status.StartPage != null;
     }
     catch (Exception ex)
     {
         status.IsInstalled = false;
         status.ItemsError  = ex.Message;
     }
 }
Ejemplo n.º 13
0
        public void NonThrowableItem_IsNotMovedToTrashcan_LegacyAttribute()
        {
            IDefinitionManager definitions = mocks.Stub <IDefinitionManager>();

            IPersister persister = mocks.Stub <IPersister>();

            Expect.Call(persister.Get(1)).Return(root).Repeat.Any();
            persister.ItemDeleting += null;
            IEventRaiser invokeDelete = LastCall.IgnoreArguments().GetEventRaiser();

            mocks.ReplayAll();

            var          host = new Host(webContext, 1, 1);
            TrashHandler th   = new TrashHandler(persister, null, null, new ContainerRepository <TrashContainerItem>(persister, null, host, null))
            {
                UseNavigationMode = true
            };
            DeleteInterceptor interceptor = new DeleteInterceptor(persister, th);

            interceptor.Start();

            CancellableItemEventArgs deleteArgs = new CancellableItemEventArgs(nonThrowable2);

            invokeDelete.Raise(persister, deleteArgs);

            Assert.That(deleteArgs.Cancel, Is.False);
            Assert.That(trash.Children.Count, Is.EqualTo(0));
        }
Ejemplo n.º 14
0
        public override void SetUp()
        {
            base.SetUp();

            persister = mocks.StrictMock <IPersister>();
            Expect.Call(persister.Get(1)).Return(root).Repeat.Any();
        }
Ejemplo n.º 15
0
        public virtual void Reindex(int itemID, bool affectsChildren)
        {
            var itemX = persister.Get(itemID);

            if (itemX == null)
            {
                return;
            }

            string title    = itemX.Title;
            var    document = indexer.CreateDocument(itemX);

            Execute(new Work
            {
                Name   = "Reindex #" + itemID + " (affectsChildren = " + affectsChildren + ")",
                Action = () =>
                {
                    // update the index
                    currentWork = "Indexing " + title + " #" + itemID;
                    indexer.Update(document);

                    if (affectsChildren)
                    {
                        var reindexIds = persister.Repository
                                         .Select(Parameter.Equal("Parent.ID", itemID), "ID")
                                         .Select(d => d["ID"]).Cast <int>().ToList();

                        foreach (var childId in reindexIds)
                        {
                            Reindex(childId, affectsChildren);
                        }
                    }
                }
            });
        }
Ejemplo n.º 16
0
        public virtual void BeginPurge(int rootId)
        {
            workQueue.Enqueue(new Work
            {
                Task = () =>
                {
                    var item = persister.Get(rootId);
                    if (item == null)
                    {
                        return;
                    }

                    string title = item.Title;
                    Status       = new AsyncPurgeStatus {
                        IsRunning = true, Progress = new PurgingStatus {
                            Deleted = 0, Remaining = 1
                        }, Title = title
                    };

                    using (this.security.Disable())
                    {
                        trash.Purge(item, s => { Status = new AsyncPurgeStatus {
                                                     IsRunning = true, Progress = s, Title = title
                                                 }; });
                    }
                    Status = null;
                }
            });
            BeginWorking();
        }
Ejemplo n.º 17
0
        protected virtual IEnumerable <FolderReference> GetUploadFolderPaths()
        {
            var paths = new List <FolderReference>();

            if (folderSource == null)
            {
                throw new NullReferenceException("folderSource is null");
            }
            //return new FolderPair[0];

            var gpp = new List <FileSystemRoot>(folderSource.GetUploadFoldersForAllSites());            // non-lazy easier to debug :-)

            if (gpp == null)
            {
                throw new NullReferenceException("folderSource.GetUploadFoldersForAllSites() returned null");
            }

            // configured folders to the root node
            foreach (var folder in gpp)
            {
                var parent = persister.Get(folder.GetParentID());
                if (parent == null)
                {
                    break;
                }

                var pair = new FolderReference(parent.ID, parent.Path, parent.Path + folder.GetName() + "/", folder);
                paths.Add(pair);
            }

            return(paths);
        }
Ejemplo n.º 18
0
        public Result Search(N2.Persistence.Search.Query query)
        {
            if (!query.IsValid())
            {
                return(Result.Empty);
            }

            var s = accessor.GetSearcher();

            try
            {
                var q    = CreateQuery(query);
                var hits = s.Search(q, query.SkipHits + query.TakeHits);

                var result = new Result();
                result.Total = hits.totalHits;
                var resultHits = hits.scoreDocs.Skip(query.SkipHits).Take(query.TakeHits).Select(hit =>
                {
                    var doc          = s.Doc(hit.doc);
                    int id           = int.Parse(doc.Get("ID"));
                    ContentItem item = persister.Get(id);
                    return(new Hit {
                        Content = item, Score = hit.score
                    });
                }).Where(h => h.Content != null).ToList();
                result.Hits  = resultHits;
                result.Count = resultHits.Count;
                return(result);
            }
            finally
            {
                //s.Close();
            }
        }
Ejemplo n.º 19
0
        private DateTime?GetLastExecuted()
        {
            if (lastExecuted.HasValue)
            {
                return(lastExecuted);
            }

            var root  = persister.Get(host.DefaultSite.RootItemID);
            var value = root["ScheduledPopularityLastExecuted"] as DateTime?;

            if (value.HasValue)
            {
                return(value);
            }

            return(DateTime.MinValue);
        }
Ejemplo n.º 20
0
        private IPersister MockPersister(ContentItem root, ContentItem trash, ContentItem item)
        {
            IPersister persister = mocks.StrictMock <IPersister>();

            Expect.Call(persister.Get(1)).Return(root).Repeat.Any();
            Expect.Call(delegate { persister.Save(item); }).Repeat.Any();
            return(persister);
        }
Ejemplo n.º 21
0
        public void RemoveLocation(int id)
        {
            var location = persister.Get <MagicLocation>(id);

            if (location != null)
            {
                persister.Delete(location);
            }
        }
Ejemplo n.º 22
0
        protected virtual ContentItem TryLoadingFromQueryString(string url, params string[] parameters)
        {
            int?itemID = FindQueryStringReference(url, parameters);

            if (itemID.HasValue)
            {
                return(persister.Get(itemID.Value));
            }
            return(null);
        }
Ejemplo n.º 23
0
        public ContentItem Navigate(string path)
        {
            if (path == null)
            {
                return(null);
            }

            if (!path.StartsWith("/"))
            {
                if (path.StartsWith("~"))
                {
                    return(Navigate(persister.Get(host.CurrentSite.StartPageID), path.Substring(1))
                           ?? virtualNodes.Get(path));
                }
                throw new ArgumentException("The path must start with a slash '/', was '" + path + "'", "path");
            }

            return(Navigate(persister.Get(host.CurrentSite.RootItemID), path));
        }
Ejemplo n.º 24
0
        private FolderPair[] GetUploadFolderPaths()
        {
            var paths = new List <FolderPair>();

            // configured folders to the root node
            foreach (FolderElement folder in folders)
            {
                var root = persister.Get(host.DefaultSite.RootItemID);
                var pair = new FolderPair(root.ID, root.Path, folder.Path.TrimStart('~'), folder.Path);
                paths.Add(pair);
            }
            // site-upload folders to their respective nodes
            paths.AddRange(UploadFoldersForSite(host.DefaultSite));
            foreach (var site in host.Sites)
            {
                paths.AddRange(UploadFoldersForSite(site));
            }

            return(paths.ToArray());
        }
Ejemplo n.º 25
0
        public void UpgradeVersion_RemovesPreviousVersion()
        {
            using (persister)
            {
                worker.UpgradeVersion(version);
            }

            var previousVersion = persister.Get(version.ID);

            previousVersion.ShouldBe(null);
        }
Ejemplo n.º 26
0
        private bool UpdateItems(DatabaseStatus status)
        {
            try
            {
                status.StartPageID = host.DefaultSite.StartPageID;
                status.RootItemID  = host.DefaultSite.RootItemID;
                status.StartPage   = persister.Get(status.StartPageID);
                status.RootItem    = persister.Get(status.RootItemID);
                status.IsInstalled = status.RootItem != null && status.StartPage != null &&
                                     !IsTrashed(status.RootItem) && !IsTrashed(status.StartPage) /* fix #583 -- ~/N2 should detect if the RootNode is Trash */;

                return(true);
            }
            catch (Exception ex)
            {
                status.IsInstalled = false;
                status.ItemsError  = ex.Message;
                return(false);
            }
        }
Ejemplo n.º 27
0
 private ContentItem Get(ref ContentItem item, int id)
 {
     if (item != null)
     {
         return(item);
     }
     if (persister != null && id != 0)
     {
         return(item = persister.Get(id));
     }
     return(null);
 }
Ejemplo n.º 28
0
        private Directory CreateDirectory(FolderPair pair)
        {
            var dd     = fs.GetDirectoryOrVirtual(pair.FolderPath);
            var parent = persister.Get(pair.ParentID);

            var dir = Directory.New(dd, parent, dependencyInjector);

            dir.Title = pair.Path.Substring(pair.ParentPath.Length).Trim('/');
            dir.Name  = dir.Title;

            return(dir);
        }
Ejemplo n.º 29
0
        private IEnumerable <ItemDefinition> RegisterDynamicParts()
        {
            // Define registered parts
            var parts = new List <ContentRegistration>();
            var root  = Persister.Get(_host.CurrentSite.RootItemID);

            partNameToID.Clear();
            AddRegistrationsBelow(root, parts);

            // Refine
            _builder.ExecuteRefiners(parts.Select(r => r.Definition).ToList());
            return(parts.Select(registration => registration.Finalize()));
        }
Ejemplo n.º 30
0
            private Directory CreateDirectory(FolderPair pair)
            {
                var dd     = fs.GetDirectory(pair.FolderPath);
                var parent = persister.Get(pair.ParentID);

                var dir = new Directory(dd, parent);

                dir.Set(fs);
                dir.Title = pair.Path.Substring(pair.ParentPath.Length).Trim('/');
                dir.Name  = dir.Title;

                return(dir);
            }
Ejemplo n.º 31
0
        public override void SetUp()
        {
            base.SetUp();

            persister = mocks.StrictMock<IPersister>();
            Expect.Call(persister.Get(1)).Return(root).Repeat.Any();
        }
Ejemplo n.º 32
0
		internal static Directory CreateDirectory(FileSystemRoot folder, IFileSystem fs, IPersister persister, IDependencyInjector dependencyInjector)
		{
			var dd = fs.GetDirectoryOrVirtual(folder.Path);
			var parent = persister.Get(folder.GetParentID());

			var dir = Directory.New(dd, parent, dependencyInjector);
			dir.Name = folder.GetName();
			dir.Title = folder.Title ?? dir.Name;

			Apply(folder.Readers, dir);
			Apply(folder.Writers, dir);

			return dir;
		}
Ejemplo n.º 33
0
 public virtual void AddAnswer(IPersister persister, int selectedItem)
 {
     Option o = persister.Get<Option>(selectedItem);
     o.Answers++;
     persister.Save(o);
 }