Example #1
0
        public static IEnumerable <T> GetDescendants <T>(this PageData page)
        {
            var repository  = ServiceLocator.Current.GetInstance <IContentTypeRepository>();
            var contentType = repository.Load(typeof(T));
            int?pageTypeID  = contentType.ID;

            if (pageTypeID.HasValue)
            {
                PropertyCriteria pageTypeCriteria = new PropertyCriteria
                {
                    Condition = CompareCondition.Equal,
                    Name      = "PageTypeID",
                    Type      = PropertyDataType.PageType,
                    Value     = pageTypeID.Value.ToString()
                };
                PropertyCriteriaCollection criterias = new PropertyCriteriaCollection
                {
                    pageTypeCriteria
                };

                var pageCriteriaQueryService = ServiceLocator.Current
                                               .GetInstance <IPageCriteriaQueryService>();
                var descendants = pageCriteriaQueryService
                                  .FindPagesWithCriteria(page.ContentLink.ToPageReference(), criterias).Cast <T>();

                return(descendants);
            }
            return(null);
        }
Example #2
0
        // Type specified through page type ID
        private IEnumerable <PageData> FindPagesByPageTypeRecursively(PageReference pageLink, int pageTypeId)
        {
            var criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name      = "PageTypeID",
                    Type      = PropertyDataType.PageType,
                    Condition = CompareCondition.Equal,
                    Value     = pageTypeId.ToString(CultureInfo.InvariantCulture)
                }
            };

            // Include content providers serving content beneath the page link specified for the search
            if (_providerManager.ProviderMap.CustomProvidersExist)
            {
                var contentProvider = _providerManager.ProviderMap.GetProvider(pageLink);

                if (contentProvider.HasCapability(ContentProviderCapabilities.Search))
                {
                    criteria.Add(new PropertyCriteria
                    {
                        Name  = "EPI:MultipleSearch",
                        Value = contentProvider.ProviderKey
                    });
                }
            }

            return(_pageCriteriaQueryService.FindPagesWithCriteria(pageLink, criteria));
        }
        public override string Execute()
        {
            CategoriesManager.DeleteAll();

            var searchService = ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>();

            foreach (var type in CategoriesManager.CategoryAssignmentProperties)
            {
                var typeName = type.Key.Name;
                var criteria = new PropertyCriteriaCollection
                    {
                        new PropertyCriteria
                        {
                            Name = "PageTypeName",
                            Type = PropertyDataType.PageType,
                            Condition = CompareCondition.Equal,
                            Value = typeName
                        }
                    };

                var pages = searchService.FindPagesWithCriteria(ContentReference.StartPage, criteria);

                foreach (var page in pages)
                {
                    contentReviewed++;
                    assignmentsIndexed = assignmentsIndexed + CategoriesManager.IndexContentPage(page);
                }
            }

            return String.Format("Content Reviewed: {0}, Assignments Indexed: {1}", contentReviewed, assignmentsIndexed);
        }
Example #4
0
        /// <summary>
        /// Gets the latest updated threads. Will search through all the forums beneath the supplied root.
        /// </summary>
        /// <param name="pageRef">The root page to look for threads under.</param>
        /// <param name="nrOfThreads">The number of threads to return.</param>
        /// <returns>A PageDataCollection containing threads.</returns>
        public static PageDataCollection GetLatestUpdatedThreads(PageReference pageRef, int nrOfThreads)
        {
            PropertyCriteriaCollection criterias = new PropertyCriteriaCollection();

            criterias.Add("PageTypeName", ThreadContainerPageTypeName, CompareCondition.Equal);
            PageDataCollection pages = DataFactory.Instance.FindPagesWithCriteria(pageRef, criterias);

            PageDataCollection threads         = new PageDataCollection();
            FilterPublished    publishedFilter = new FilterPublished();

            foreach (PageData threadContainer in pages)
            {
                foreach (PageData page in DataFactory.Instance.GetChildren(threadContainer.PageLink, LanguageSelector.AutoDetect(), 0, nrOfThreads))
                {
                    if (!publishedFilter.ShouldFilter(page))
                    {
                        threads.Add(page);
                    }
                }
            }

            new FilterPropertySort("PageChanged", FilterSortDirection.Descending).Filter(threads);
            new FilterCount(nrOfThreads).Filter(threads);

            return(threads);
        }
        /// <summary>
        /// The find pages with criteria.
        /// </summary>
        /// <param name="pageLink">
        /// The page link.
        /// </param>
        /// <param name="criterias">
        /// The criterias.
        /// </param>
        /// <param name="languageBranch">
        /// The language branch.
        /// </param>
        /// <param name="selector">
        /// The selector.
        /// </param>
        /// <returns>
        /// The <see cref="PageDataCollection"/>.
        /// </returns>
        public PageDataCollection FindPagesWithCriteria(
            PageReference pageLink,
            PropertyCriteriaCollection criterias,
            string languageBranch,
            ILanguageSelector selector)
        {
            if (PageReference.IsNullOrEmpty(pageLink))
            {
                return(new PageDataCollection());
            }

            // Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
            if (pageLink.CompareToIgnoreWorkID(this.EntryRoot))
            {
                pageLink = this.CloneRoot;
            }
            else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName))
            {
                // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
                pageLink = new PageReference(pageLink.ID);
            }

            PageDataCollection pages = DataFactory.Instance.FindPagesWithCriteria(
                pageLink, criterias, languageBranch, selector);

            // Return cloned search result set
            return(new PageDataCollection(pages.Select(this.ClonePage)));
        }
Example #6
0
        private static IEnumerable <PageData> FindPagesByPageTypeRecursively(ContentReference pageLink, int pageTypeId)
        {
            var criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name      = "PageTypeID",
                    Type      = PropertyDataType.PageType,
                    Condition = CompareCondition.Equal,
                    Value     = pageTypeId.ToString(CultureInfo.InvariantCulture)
                }
            };

            if (!ProviderManager.Value.ProviderMap.CustomProvidersExist)
            {
                return(PageCriteriaQueryService.Value.FindPagesWithCriteria(pageLink.ToPageReference(), criteria));
            }

            var contentProvider = ProviderManager.Value.ProviderMap.GetProvider(pageLink);

            if (contentProvider.HasCapability(ContentProviderCapabilities.Search))
            {
                criteria.Add(new PropertyCriteria
                {
                    Name  = "EPI:MultipleSearch",
                    Value = contentProvider.ProviderKey
                });
            }

            return(PageCriteriaQueryService.Value.FindPagesWithCriteria(pageLink.ToPageReference(), criteria));
        }
        public bool checkPageExisting(string name, string IDPageParent)
        {
            ContentReference tmp = ContentReference.Parse(IDPageParent);

            var criterias = new PropertyCriteriaCollection
            {
                new PropertyCriteria()
                {
                    Name      = "PageName",
                    Type      = PropertyDataType.String,
                    Condition = EPiServer.Filters.CompareCondition.Equal,
                    Value     = name
                }
            };

            var repository = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();

            var pages = repository.FindPagesWithCriteria(
                tmp.ToPageReference(),
                criterias);

            if (pages.Count.ToString() == "0")
            {
                return(false);
            }
            return(true);
        }
Example #8
0
        public void Test_can_map_query_condition_to_property_criteria()
        {
            // Arrange
            CmsqlQueryCondition condition = new CmsqlQueryCondition
            {
                Identifier = "PageName",
                Operator   = EqualityOperator.GreaterThan,
                Value      = "5"
            };

            CmsqlExpressionVisitorContext context = new CmsqlExpressionVisitorContext(new ContentType());

            CmsqlExpressionVisitor cmsqlExpressionVisitor =
                new CmsqlExpressionVisitor(
                    new QueryConditionToPropertyCriteriaMapper(
                        new PropertyDataTypeResolver(new ContentType())), context);

            // Act
            cmsqlExpressionVisitor.VisitQueryCondition(condition);

            PropertyCriteriaCollection propertyCriteriaCollection = context.GetCriteria().Single();

            PropertyCriteria propertyCriteria = propertyCriteriaCollection.Last();

            // Assert
            propertyCriteria.Value.ShouldBeEquivalentTo(condition.Value);
            propertyCriteria.Condition.ShouldBeEquivalentTo(CompareCondition.GreaterThan);
            propertyCriteria.Name.ShouldBeEquivalentTo(condition.Identifier);
        }
        public NotificationSettings GetNotificationSettings(string language = null)
        {
            var contentTypeRepository = ServiceLocator.Current.GetInstance<EPiServer.DataAbstraction.IContentTypeRepository>();
            var pageCriteriaQueryService = ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>();
            var criterias = new PropertyCriteriaCollection();
            var criteria = new PropertyCriteria();
            criteria.Condition = EPiServer.Filters.CompareCondition.Equal;
            criteria.Name = "PageTypeID";
            criteria.Type = PropertyDataType.PageType;
            criteria.Value = contentTypeRepository.Load("NotificationSettings").ID.ToString();
            criteria.Required = true;
            criterias.Add(criteria);
            // TODO: We should not search for settings, point to it from the start page instead.
            PageData page;
            if (language == null)
            {
                page = pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criterias).FirstOrDefault();

            }
            else
            {
                page = pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criterias, language).FirstOrDefault();

            }
            if (page is NotificationSettings)
            {
                return (NotificationSettings)page;
            }
            return null;
        }
Example #10
0
        /// <summary>
        /// Gets pages by a specific PageTypeId under a certain starting point.
        /// </summary>
        /// <param name="startPageReference">The page reference used as a starting point for the search.</param>
        /// <param name="pageTypeId">The page type id to search for.</param>
        /// <returns>A PageDataCollection containing all pages below the startPageReference of the page type pageTypeId.</returns>
        private static PageDataCollection GetPages(PageReference startPageReference, int pageTypeId)
        {
            PropertyCriteriaCollection pcc = new PropertyCriteriaCollection();

            pcc.Add(BlogUtility.CreateCriteria(CompareCondition.Equal, "PageTypeID", PropertyDataType.PageType, pageTypeId.ToString(CultureInfo.InvariantCulture), true));
            return(DataFactory.Instance.FindPagesWithCriteria(startPageReference, pcc));
        }
Example #11
0
        public NotificationSettings GetNotificationSettings(string language = null)
        {
            var contentTypeRepository    = ServiceLocator.Current.GetInstance <EPiServer.DataAbstraction.IContentTypeRepository>();
            var pageCriteriaQueryService = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();
            var criterias = new PropertyCriteriaCollection();
            var criteria  = new PropertyCriteria();

            criteria.Condition = EPiServer.Filters.CompareCondition.Equal;
            criteria.Name      = "PageTypeID";
            criteria.Type      = PropertyDataType.PageType;
            criteria.Value     = contentTypeRepository.Load("NotificationSettings").ID.ToString();
            criteria.Required  = true;
            criterias.Add(criteria);
            // TODO: We should not search for settings, point to it from the start page instead.
            PageData page;

            if (language == null)
            {
                page = pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criterias).FirstOrDefault();
            }
            else
            {
                page = pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criterias, language).FirstOrDefault();
            }
            if (page is NotificationSettings)
            {
                return((NotificationSettings)page);
            }
            return(null);
        }
        private static IEnumerable <PageData> GetLatestPublishedContent(DateTime daysBack)
        {
            var criterias = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Condition = EPiServer.Filters.CompareCondition.GreaterThan,
                    Name      = "PageChanged",
                    Type      = PropertyDataType.Date,
                    Value     = daysBack.ToString(CultureInfo.InvariantCulture),
                    Required  = true
                }
            };

            var newsPageItems = DataFactory.Instance
                                .FindPagesWithCriteria(PageReference.StartPage, criterias)
                                // Only keep those with a user set otherwise the demo won't show anything. (also: PropertyCriteria can only search for null but we don't want empty strings either)
                                .Where(x => !string.IsNullOrEmpty(x.ChangedBy))
                                .ToList();

            // LAST MINUTE HACK
            var pageLink = new PageReference(6);
            var hackPage = DataFactory.Instance.GetPage(pageLink);

            if (!newsPageItems.Contains(hackPage))
            {
                newsPageItems.Add(hackPage);
            }

            return(newsPageItems);
        }
        public virtual PageDataCollection List(PageReference pageLink)
        {
            // Using functionality from
            // http://world.episerver.com/documentation/Items/Developers-Guide/EPiServer-CMS/9/Search/Searching-for-pages-based-on-page-type/
            string pageTypeId = _pageTypeRepository.Load<StandardPage>()?.ID.ToString();
            if (pageTypeId == null)
            {
                return new PageDataCollection();
            }

            PropertyCriteria productPageTypeCriterion = new PropertyCriteria
            {
                Name = "PageTypeID",
                Type = PropertyDataType.PageType,
                Value = pageTypeId,
                Condition = CompareCondition.Equal,
                Required = true
            };

            var criteria = new PropertyCriteriaCollection
            {
                productPageTypeCriterion
            };

            PageDataCollection pageDataCollection = _searchPages.FindPagesWithCriteria(pageLink, criteria);

            return pageDataCollection;
        }
        public override PageDataCollection SearchRelations(Rule rule, int pageID, string searchKeyWord, PageReference hierarchyStart, bool isLeftRule)
        {
            string             pageTypes = HttpUtility.UrlDecode(isLeftRule ? rule.PageTypeRight : rule.PageTypeLeft);
            PageDataCollection result    = new PageDataCollection();

            if (!string.IsNullOrEmpty(pageTypes))
            {
                string[] pageTypeCollection = pageTypes.Split(';');
                PropertyCriteriaCollection pageTypeCriterias = new PropertyCriteriaCollection();

                if (hierarchyStart == null || hierarchyStart == PageReference.EmptyReference)
                {
                    hierarchyStart = PageReference.RootPage;
                }

                foreach (string s in pageTypeCollection)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        PropertyCriteria criteria = new PropertyCriteria();
                        criteria.Condition = EPiServer.Filters.CompareCondition.Equal;
                        criteria.Name      = "PageTypeName";
                        criteria.Type      = PropertyDataType.String;
                        criteria.Value     = s;
                        pageTypeCriterias.Add(criteria);
                    }
                }

                PageDataCollection pages = DataFactory.Instance.FindPagesWithCriteria(hierarchyStart, pageTypeCriterias);

                PageData rootPage = DataFactory.Instance.GetPage(hierarchyStart);
                if (pageTypeCollection.Contains <string>(rootPage.PageTypeName) && !pages.Contains(rootPage))
                {
                    pages.Add(rootPage);
                }


                new EPiServer.Filters.FilterSort(EPiServer.Filters.FilterSortOrder.Alphabetical).Sort(pages);


                if (!string.IsNullOrEmpty(searchKeyWord))
                {
                    for (int i = 0; i < pages.Count; i++)
                    {
                        if (pages[i].PageName.ToLower().Contains(searchKeyWord.ToLower()))
                        {
                            result.Add(pages[i]);
                        }
                    }
                }
                else
                {
                    result = pages;
                }
            }

            return(result);
        }
Example #15
0
        public override ActionResult Index(PageListBlock currentBlock)
        {
            PropertyCriteriaCollection criterias = SetupCriterias(currentBlock.PageType);

            var foundPages = _queryService.FindPagesWithCriteria(currentBlock.Root.ToPageReference(), criterias);
            var rootPage   = _contentRepository.Get <PageData>(currentBlock.Root);

            return(PartialView("Blocks/PageListBlock", new PageListBlockViewModel(currentBlock, foundPages, rootPage)));
        }
        protected override IEnumerable <PageReference> GetContentReferences(string languageBranch)
        {
            var criterias = new PropertyCriteriaCollection()
            {
                PageIsInCategoryCriteria
            };
            PageDataCollection pages = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, criterias, languageBranch);

            return(pages.Select(p => p.PageLink));
        }
Example #17
0
        public static IEnumerable<PageData> FindPages(string pageTypeId)
        {
            var criteria = new PropertyCriteriaCollection();

            if (FilterStrategy.ShouldFilterOnPageType(pageTypeId))
            {
                criteria.Add(PropertyCriteriaGenerator.ForPageType(pageTypeId));
            }

            return DataFactory.Instance.FindPagesWithCriteria(PageReference.RootPage, criteria);
        }
Example #18
0
        public static IEnumerable <PageData> FindPages(string pageTypeId)
        {
            var criteria = new PropertyCriteriaCollection();

            if (FilterStrategy.ShouldFilterOnPageType(pageTypeId))
            {
                criteria.Add(PropertyCriteriaGenerator.ForPageType(pageTypeId));
            }

            return(DataFactory.Instance.FindPagesWithCriteria(PageReference.RootPage, criteria));
        }
        public PageDataCollection List(PageReference pageLink)
        {
            string key = CachedFindPagesWithCriterion.GetCacheKey(pageLink.ToReferenceWithoutVersion());

            var standardPages = _synchronizedObjectInstanceCache.Get(key) as PageDataCollection;
            if (standardPages == null)
            {
                object miniLock = MiniLocks.GetOrAdd(key, k => new object());
                lock (miniLock)
                {
                    standardPages = _synchronizedObjectInstanceCache.Get(key) as PageDataCollection;
                    if (standardPages == null)
                    {
                        string pageTypeId = _pageTypeRepository.Load<StandardPage>()?.ID.ToString();
                        if (pageTypeId == null)
                        {
                            return new PageDataCollection();
                        }

                        PropertyCriteria productPageTypeCriterion = new PropertyCriteria
                        {
                            Name = "PageTypeID",
                            Type = PropertyDataType.PageType,
                            Value = pageTypeId,
                            Condition = CompareCondition.Equal,
                            Required = true
                        };

                        var criteria = new PropertyCriteriaCollection
                        {
                            productPageTypeCriterion
                        };

                        standardPages = _searchPages.FindPagesWithCriteria(pageLink, criteria);

                        Thread.Sleep(5000);

                        _synchronizedObjectInstanceCache.Insert(key, standardPages, CacheEvictionPolicy.Empty);

                        // Saving some space we will release the lock
                        object temp1;
                        if (MiniLocks.TryGetValue(key, out temp1) && (temp1 == miniLock))
                        {
                            object temp2;
                            MiniLocks.TryRemove(key, out temp2);
                        }
                    }
                }
            }

            return standardPages;
        }
Example #20
0
    public override void ProcessRequest(HttpContext context)
    {
        PropertyCriteriaCollection criterias = new PropertyCriteriaCollection();
        PropertyCriteria           criteria  = new PropertyCriteria();

        criteria.Condition = CompareCondition.Equal;
        criteria.Name      = "PageTypeID";
        criteria.Type      = PropertyDataType.PageType;
        criteria.Value     = Locate.ContentTypeRepository().Load("HotelDetailPage").ID.ToString();
        criteria.Required  = true;

        criterias.Add(criteria);

        PageDataCollection _newsPageItems = Locate.PageCriteriaQueryService().FindPagesWithCriteria(PageReference.StartPage, criterias);
    }
Example #21
0
        private void RetrieveSiteProductPages()
        {
            PropertyCriteriaCollection criteria = new PropertyCriteriaCollection();

            PropertyCriteria prodpagecriterion = new PropertyCriteria();

            prodpagecriterion.Condition = EPiServer.Filters.CompareCondition.Equal;
            prodpagecriterion.Name      = "PageTypeID";
            prodpagecriterion.Type      = PropertyDataType.PageType;
            prodpagecriterion.Value     = ServiceLocator.Current.GetInstance <IContentTypeRepository>().Load("ProductPage").ID.ToString();

            prodpagecriterion.Required = true;
            criteria.Add(prodpagecriterion);

            productPages = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>().FindPagesWithCriteria(PageReference.StartPage, criteria);
        }
Example #22
0
        private void IphoneChecker(object sender, ContentEventArgs e)
        {
            var repo   = ServiceLocator.Current.GetInstance <IContentRepository>();
            var finder = ServiceLocator.Current
                         .GetInstance <IPageCriteriaQueryService>();
            int pageCount = 0;

            var criteria = new PropertyCriteriaCollection();

            criteria.Add(new PropertyCriteria
            {
                Type      = PropertyDataType.LongString,
                Name      = "PageName",
                Condition = EPiServer.Filters.CompareCondition.Contained,
                Value     = "iphone"
            });
            criteria.Add(new PropertyCriteria
            {
                Type      = PropertyDataType.LongString,
                Name      = "MetaTitle",
                Condition = EPiServer.Filters.CompareCondition.Contained,
                Value     = "iphone"
            });
            criteria.Add(new PropertyCriteria
            {
                Type      = PropertyDataType.LongString,
                Name      = "MetaDescription",
                Condition = EPiServer.Filters.CompareCondition.Contained,
                Value     = "iphone"
            });
            PageDataCollection results = finder.FindPagesWithCriteria(
                ContentReference.RootPage as PageReference, criteria);

            foreach (SitePageData page in results)
            {
                var clone = page.CreateWritableClone() as SitePageData;
                clone.Name            = page.Name.Replace("iphone", "[censored]");
                clone.MetaTitle       = page.MetaTitle?.Replace("iphone", "[censored]");
                clone.MetaDescription =
                    page.MetaDescription?.Replace("iphone", "[censored]");
                repo.Save(clone,
                          EPiServer.DataAccess.SaveAction.CheckIn,
                          EPiServer.Security.AccessLevel.NoAccess);
                pageCount++;
            }
        }
Example #23
0
        public static void SetPagesForPageTypeName(ExistingPagesReportViewModel model)
        {
            var criterias = new PropertyCriteriaCollection();

            var criteria = new PropertyCriteria();

            criteria.Condition = CompareCondition.Equal;
            criteria.Name      = "PageTypeID";
            criteria.Type      = PropertyDataType.PageType;
            criteria.Value     = model.SelectedPageType;
            criteria.Required  = true;

            criterias.Add(criteria);

            var pages = DataFactory.Instance.FindPagesWithCriteria(ContentReference.RootPage, criterias);

            model.Pages = pages;
        }
        protected IEnumerable <T> GetAllPagesOfType <T>(PageReference startPage = null)
        {
            startPage = startPage == null ? ContentReference.StartPage : startPage;
            var contentTypeRepository            = ServiceLocator.Current.GetInstance <IContentTypeRepository>();
            PropertyCriteriaCollection criterias = new PropertyCriteriaCollection {
                new PropertyCriteria()
                {
                    Name      = "PageTypeID",
                    Type      = PropertyDataType.PageType,
                    Condition = EPiServer.Filters.CompareCondition.Equal,
                    Value     = contentTypeRepository.Load <T>().ID.ToString()
                }
            };

            var pageCriteriaQueryService = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();

            return(pageCriteriaQueryService.FindPagesWithCriteria(startPage, criterias).Cast <T>());
        }
        public override List <EventPageBase> GetEventPages()
        {
            PropertyCriteriaCollection criteria = new PropertyCriteriaCollection();

            var pageTypes = ServiceLocator.Current.GetInstance <IContentTypeRepository>().List();

            foreach (var pageType in pageTypes)
            {
                if (pageType.ModelType != null && typeof(EventPageBase).IsAssignableFrom(pageType.ModelType))
                {
                    PropertyCriteria pageTypeCriteria = new PropertyCriteria();
                    pageTypeCriteria.Condition = CompareCondition.Equal;
                    pageTypeCriteria.Value     = pageType.ID.ToString();
                    pageTypeCriteria.Type      = PropertyDataType.PageType;
                    pageTypeCriteria.Name      = "PageTypeID";
                    pageTypeCriteria.Required  = false;
                    criteria.Add(pageTypeCriteria);
                }
            }

            List <EventPageBase> eventList = new List <EventPageBase>();
            var sites = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance <EPiServer.Web.SiteDefinitionRepository>().List();

            foreach (SiteDefinition siteDefinition in sites)
            {
                PageDataCollection allEvents = new PageDataCollection();

                var allLanguages = ServiceLocator.Current.GetInstance <ILanguageBranchRepository>().ListEnabled();

                foreach (LanguageBranch languageBranch in allLanguages)
                {
                    allEvents.Add(DataFactory.Instance.FindAllPagesWithCriteria(siteDefinition.StartPage.ToPageReference(), criteria, languageBranch.LanguageID, new LanguageSelector(languageBranch.LanguageID)));
                }

                foreach (PageData currentEvent in allEvents)
                {
                    if (currentEvent as EventPageBase != null)
                    {
                        eventList.Add(currentEvent as EventPageBase);
                    }
                }
            }
            return(eventList);
        }
        public PageDataCollection List(PageReference pageLink)
        {
            string cacheKey = CachedFindPagesWithCriterion.GetCacheKey(pageLink.ToReferenceWithoutVersion());

            var standardPages = _synchronizedObjectInstanceCache.Get(cacheKey) as PageDataCollection;
            if (standardPages == null)
            {
                lock (Lock)
                {
                    // Check cache again since standardPages might have been cached while waiting for the lock to open
                    standardPages = _synchronizedObjectInstanceCache.Get(cacheKey) as PageDataCollection;
                    if (standardPages == null)
                    {
                        string pageTypeId = _pageTypeRepository.Load<StandardPage>()?.ID.ToString();
                        if (pageTypeId == null)
                        {
                            return new PageDataCollection();
                        }

                        PropertyCriteria productPageTypeCriterion = new PropertyCriteria
                        {
                            Name = "PageTypeID",
                            Type = PropertyDataType.PageType,
                            Value = pageTypeId,
                            Condition = CompareCondition.Equal,
                            Required = true
                        };

                        var criteria = new PropertyCriteriaCollection
                        {
                            productPageTypeCriterion
                        };

                        standardPages = _searchPages.FindPagesWithCriteria(pageLink, criteria);

                        Thread.Sleep(5000);

                        _synchronizedObjectInstanceCache.Insert(cacheKey, standardPages, CacheEvictionPolicy.Empty);
                    }
                }
            }

            return standardPages;
        }
Example #27
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            PropertyCriteriaCollection pcc = new PropertyCriteriaCollection();
            PropertyCriteria           pc  = new PropertyCriteria
            {
                Name      = "PageChanged",
                Value     = DateTime.Now.Subtract(TimeSpan.FromHours(CorrectHoursPropertyValue())).ToString(),
                Condition = CompareCondition.GreaterThan,
                Type      = PropertyDataType.Date
            };

            pcc.Add(pc);
            var pdc = DataFactory.Instance.FindPagesWithCriteria(CurrentPage["RecentContainer"] as PageReference ?? PageReference.StartPage, pcc);

            pagelist.DataSource = FilterForVisitor.Filter(pdc);
            pagelist.DataBind();
        }
Example #28
0
        public PageDataCollection GetPagesByPageType(string pageType)
        {
            var criterias = new PropertyCriteriaCollection();

            var criteria = new PropertyCriteria
            {
                Condition = CompareCondition.Equal,
                Name      = "PageTypeID",
                Type      = PropertyDataType.PageType,
                Value     = pageType,
                Required  = true,
            };

            criterias.Add(criteria);

            var pages = _queryService.FindPagesWithCriteria(ContentReference.RootPage, criterias);

            return(pages);
        }
        /// <summary>
        /// Called when a scheduled job executes
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {


            //Call OnStatusChanged to periodically notify progress of job for manually started jobs
            OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
            PropertyCriteriaCollection criteria = new PropertyCriteriaCollection();
            PropertyCriteria pageTypeCriteria = new PropertyCriteria();
            pageTypeCriteria.Condition = CompareCondition.Equal;
            pageTypeCriteria.Value = ServiceLocator.Current.GetInstance<IContentTypeRepository>().Load<EventPage>().ID.ToString();
            pageTypeCriteria.Type = PropertyDataType.PageType;
            pageTypeCriteria.Name = "PageTypeID";
            pageTypeCriteria.Required = true;
            criteria.Add(pageTypeCriteria);
            PageDataCollection allEvents = new PageDataCollection(); 
            
            PageDataCollection allLanguages = DataFactory.Instance.GetLanguageBranches(PageReference.StartPage);


            foreach (PageData pageData in allLanguages)
            {
                allEvents.Add(DataFactory.Instance.FindPagesWithCriteria(PageReference.RootPage, criteria, pageData.LanguageBranch));
                
            }
            int cnt = 0;
            foreach (var eventPage in allEvents)
            {
                cnt += UpdateEvent(eventPage as EventPage);
            }

            return "Found " + allEvents.Count + " pages, converted "+cnt+"e-mail templates!";

            //Add implementation

            //For long running jobs periodically check if stop is signaled and if so stop execution
            if (_stopSignaled)
            {
                return "Stop of job was called";
            }

            return "Change to message that describes outcome of execution";
        }
Example #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            PropertyCriteriaCollection propertyCriteriaCollection = new PropertyCriteriaCollection() {
                new PropertyCriteria() {
                    Name = "PageName",
                    Condition = CompareCondition.Contained,
                    Required = true,
                    Type = PropertyDataType.String,
                    Value = Request.Params["searchword"]
                }
            };

            PageDataCollection pageDataCollection = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, propertyCriteriaCollection);
            foreach (PageData pageData in pageDataCollection)
            {
                sb.Append("<option value='" + pageData.StaticLinkURL + "'>" + pageData.PageName + "</option>");
            }
            Output = sb.ToString();
        }
Example #31
0
        private List <PageData> FindPagesContainSearchQuery(string searchQuery)
        {
            PropertyCriteriaCollection propertyCriteriaCollection = new PropertyCriteriaCollection();

            PropertyCriteria propertyCriteria = new PropertyCriteria()
            {
                Name      = "PageName",
                Type      = PropertyDataType.String,
                Condition = Filters.CompareCondition.Contained,
                Required  = true,
                Value     = searchQuery
            };

            propertyCriteriaCollection.Add(propertyCriteria);

            List <PageData> results =
                DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, propertyCriteriaCollection).ToList <PageData>();

            return(results);
        }
        public string Execute(ref bool stopSignal, Func <string, bool> onStatusChanged)
        {
            if (stopSignal)
            {
                return($"Execution of {this.GetType().Name} was aborted by stop signal");
            }

            onStatusChanged("Running PagesNotVisibleInMenus...");

            var repository = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();

            PropertyCriteriaCollection criterias = new PropertyCriteriaCollection()
            {
                new PropertyCriteria()
                {
                    Name      = MetaDataProperties.PageVisibleInMenu,
                    Type      = PropertyDataType.Boolean,
                    Condition = EPiServer.Filters.CompareCondition.Equal,
                    Value     = "false"
                }
            };

            PageDataCollection         pages        = repository.FindPagesWithCriteria(ContentReference.StartPage, criterias);
            PagesNotVisibleInMenusData pageNameList = new PagesNotVisibleInMenusData();

            foreach (PageData page in pages)
            {
                //if (page.PageTypeName.Equals(nameof(SlideShowPicturePage)) || page.PageTypeName.Equals(nameof(ContactPage)) || page.PageTypeName.Equals(nameof(SortingItemPage)))
                //    continue;
                pageNameList.Pages.Add(new ContentReportItemWithType()
                {
                    PageContentLinkId = page.ContentLink.ID,
                    PageName          = page.Name,
                    PageTypeName      = page.PageTypeName
                });
            }

            DataStorage.WriteObjectToFile <PagesNotVisibleInMenusData>(pageNameList);
            return("I am done, doobie damm damm");
        }
        /// <summary>
        /// Called when a scheduled job executes
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {
            //Call OnStatusChanged to periodically notify progress of job for manually started jobs
            OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
            PropertyCriteriaCollection criteria         = new PropertyCriteriaCollection();
            PropertyCriteria           pageTypeCriteria = new PropertyCriteria();

            pageTypeCriteria.Condition = CompareCondition.Equal;
            pageTypeCriteria.Value     = ServiceLocator.Current.GetInstance <IContentTypeRepository>().Load <EventPageBase>().ID.ToString();
            pageTypeCriteria.Type      = PropertyDataType.PageType;
            pageTypeCriteria.Name      = "PageTypeID";
            pageTypeCriteria.Required  = true;
            criteria.Add(pageTypeCriteria);
            PageDataCollection allEvents = new PageDataCollection();

            PageDataCollection allLanguages = DataFactory.Instance.GetLanguageBranches(ContentReference.StartPage);

            foreach (PageData pageData in allLanguages)
            {
                allEvents.Add(DataFactory.Instance.FindPagesWithCriteria(ContentReference.StartPage, criteria, pageData.LanguageBranch));
            }
            int cnt = 0;

            foreach (var EventPageBase in allEvents)
            {
                cnt += UpdateEvent(EventPageBase as EventPageBase);
            }

            return("Found " + allEvents.Count + " pages, converted " + cnt + "e-mail templates!");

            //Add implementation

            //For long running jobs periodically check if stop is signaled and if so stop execution
            if (_stopSignaled)
            {
                return("Stop of job was called");
            }

            return("Change to message that describes outcome of execution");
        }
        public void find_x_pages_with_hit_percentage_y(
            [Values(100, 1000, 5000)] int pageCount,
            [Values(0.1, 1, 10)] double hitPercentage)
        {
            const int rootCount = 50;
            int childCount = pageCount/rootCount;
            int targetCount = Convert.ToInt32(pageCount*hitPercentage/100);

            Console.WriteLine("Find {2} ({1}%) of {0} pages", pageCount, hitPercentage, targetCount);
            TestHelpExtensions.MeasureTime(() => add_pages(rootCount, childCount), "Creation");

            var criterias = new PropertyCriteriaCollection
                                {
                                    {"PageName", "child", CompareCondition.StartsWith},
                                    new PropertyCriteria
                                        {
                                            Condition = CompareCondition.LessThan,
                                            Name = "Number",
                                            Required = true,
                                            Type = PropertyDataType.Number,
                                            Value = hitPercentage.ToString()
                                        }
                                };
            measure_query_time("FindPagesWithCriteria",
                               targetCount,
                               () => DataFactory.Instance.FindPagesWithCriteria(PageReference.RootPage, criterias));

            measure_query_time("Linq2EPiServer",
                               targetCount,
                               () => _repository.FindDescendantsOf(PageReference.RootPage)
                                         .Where(p => p.PageName.StartsWith("child") && (int) p["Number"] < (int)hitPercentage)
                                         .ToPageDataCollection());

            measure_query_time("Linq2Objects",
                               targetCount,
                               () => PageReference.RootPage
                                         .Descendants()
                                         .Where(p => p.PageName.StartsWith("child") && (int) p["Number"] < (int)hitPercentage)
                                         .ToPageDataCollection());
        }
Example #35
0
        /// <summary>
        /// Called when a scheduled job executes
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {
            OnStatusChanged(string.Format("Starting execution of {0}", this.GetType()));

            var repo = ServiceLocator.Current.GetInstance <IContentRepository>();

            var finder = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();

            var criteria = new PropertyCriteriaCollection();

            criteria.Add(new PropertyCriteria
            {
                Type      = PropertyDataType.LongString,
                Name      = "MetaDescription",
                Condition = EPiServer.Filters.CompareCondition.Contained,
                Value     = "iWatch"
            });

            criteria.Add(new PropertyCriteria
            {
                Type      = PropertyDataType.LongString,
                Name      = "MainIntro",
                Condition = EPiServer.Filters.CompareCondition.Contained,
                Value     = "iWatch"
            });

            PageDataCollection results =
                finder.FindPagesWithCriteria(ContentReference.RootPage as PageReference, criteria);

            foreach (PageData page in results)
            {
                //For long running jobs periodically check if stop is signaled and if so stop execution
                if (_stopSignaled)
                {
                    return("Stop of job was called");
                }
            }

            return("All content containing iWatch has been changed to Apple Watch.");
        }
        public PageDataCollection List(PageReference pageLink)
        {
            string cacheKey = GetCacheKey(pageLink.ToReferenceWithoutVersion());

            var standardPages = _synchronizedObjectInstanceCache.Get(cacheKey) as PageDataCollection;
            if (standardPages == null)
            {
                string pageTypeId = _pageTypeRepository.Load<StandardPage>()?.ID.ToString();
                if (pageTypeId == null)
                {
                    return new PageDataCollection();
                }

                PropertyCriteria productPageTypeCriterion = new PropertyCriteria
                {
                    Name = "PageTypeID",
                    Type = PropertyDataType.PageType,
                    Value = pageTypeId,
                    Condition = CompareCondition.Equal,
                    Required = true
                };

                var criteria = new PropertyCriteriaCollection
                {
                    productPageTypeCriterion
                };

                standardPages = _searchPages.FindPagesWithCriteria(pageLink, criteria);

                // Lots of things can happen while fetching the cache
                Thread.Sleep(1000);

                // Actually caching the ContentData is not a good practice. Caching the ContentReference is  better
                _synchronizedObjectInstanceCache.Insert(cacheKey, standardPages, CacheEvictionPolicy.Empty);
            }

            return standardPages;
        }
        /// <summary>
        /// Method for retrieving all pages passed by a page type id
        /// </summary>
        /// <returns>Returns pages for each page type given by pagetypeid</returns>
        private static IEnumerable <PageData> GetAllPagesOfPageType(int id)
        {
            var pageTypeId = id;
            var repository = ServiceLocator.Current.GetInstance <IPageCriteriaQueryService>();

            var pageTypeCriteria = new PropertyCriteria
            {
                Name      = "PageTypeID",
                Type      = PropertyDataType.PageType,
                Value     = pageTypeId.ToString(),
                Condition = CompareCondition.Equal,
                Required  = true
            };

            var criteria = new PropertyCriteriaCollection
            {
                pageTypeCriteria
            };

            var currentCulture = ContentLanguage.PreferredCulture;
            var languageBranch = currentCulture.Name;

            var pageDataCollection = repository.
                                     FindAllPagesWithCriteria(ContentReference.RootPage,
                                                              criteria,
                                                              languageBranch,
                                                              LanguageSelector.AutoDetect(true));

            if (pageDataCollection != null)
            {
                var sortedPageDataCollection = pageDataCollection.OrderByDescending(c => c.StartPublish);

                return(sortedPageDataCollection);
            }

            return(pageDataCollection);
        }
Example #38
0
        protected string GetPagesUnfiltered(DateTime since)
        {
            PropertyCriteriaCollection col = new PropertyCriteriaCollection();
            PageData pageroot;

            //Restrict Pagetypes
            var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<EPiServer.DataAbstraction.PageTypeRepository>();


            //Start : for News Page page

            //For Fetching the News Page
            PropertyCriteria criteria = new PropertyCriteria();
            //criteria = new PropertyCriteria();
            criteria.Condition = CompareCondition.Equal;
            criteria.Name = "PageTypeID";
            criteria.Type = PropertyDataType.PageType;
            // set pagetype to be deleted
            criteria.Value = repository.Load(typeof(PropertiesSeperator)).ID.ToString();
            //criteria.Required = true;
            col.Add(criteria);

            //Fetching News Page with Date Criteria
            PropertyCriteria criteria1 = new PropertyCriteria();
            //criteria = new PropertyCriteria();
            criteria1.Condition = CompareCondition.LessThan;
            criteria1.Name = "PageCreated";
            criteria1.Type = PropertyDataType.Date;
            criteria1.Value = since.ToString();
            criteria.Required = true;
            col.Add(criteria1);
            //End : for News page
            // find key in config file
            PageDataCollection pageList = DataFactory.Instance.FindPagesWithCriteria(new PageReference(ConfigurationManager.AppSettings["ArchiveStartPage"]), col);



            // return pageList;
            //Check if there is any pages that matches the criteria
            if (pageList.Count >= 1)
            {

                //Creating the folder with reference to the start page
                //PageReference parent = new PageReference(ConfigurationManager.AppSettings["DestinationRootFolder"]);
                PageReference parent = new PageReference(1);
                PropertiesSeperator containerPage = DataFactory.Instance.GetDefault<PropertiesSeperator>(parent);
                //containerPage.PageName = ConfigurationManager.AppSettings["DestinationfolderName"];
                containerPage.PageName = ConfigurationManager.AppSettings["DestinationfolderName"];
                var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();

                //var startPage = contentRepository.Get<StartPage>(ContentReference.StartPage);
                var repository1 = ServiceLocator.Current.GetInstance<IContentRepository>();
                PageDataCollection children = DataFactory.Instance.GetChildren(parent);


                //Check if the Destinationfolder exist 
                var RootFolder = children.Where(p => p.Name == ConfigurationManager.AppSettings["DestinationfolderName"] && p.PageTypeName == typeof(PropertiesSeperator).Name);


                //If destination folder does not exist than create the folder
                if (RootFolder.Count() < 1)
                {
                    var PublishRootFolder = DataFactory.Instance.Save(containerPage, SaveAction.Publish, AccessLevel.NoAccess);
                    pageroot = new PageData(PublishRootFolder);
                }
                else
                {
                    pageroot = RootFolder.FirstOrDefault();
                }

                PageDataCollection children1 = DataFactory.Instance.GetChildren(pageroot.ContentLink as PageReference);

                //looping through each page which are 6 months older 
                foreach (var page in pageList)
                {

                    var year = page.Created.Year;
                    var Yearcheck = DataFactory.Instance.GetChildren(pageroot.ContentLink as PageReference);
                    var existyr = Yearcheck.Where(p => p.Name == year.ToString() && p.PageTypeName == typeof(PropertiesSeperator).Name);
                    //if year does not exist than create the year
                    if (existyr.Count() < 1)
                    {
                        PropertiesSeperator containerPage1 = DataFactory.Instance.GetDefault<PropertiesSeperator>(pageroot.ContentLink as PageReference);
                        containerPage1.PageName = year.ToString();
                        var savedyr = DataFactory.Instance.Save(containerPage1, SaveAction.Publish, AccessLevel.NoAccess);
                        var month = page.Created.Month;

                        int iMonthNo = month;
                        DateTime dtDate = new DateTime(2000, iMonthNo, 1);
                        string sMonthFullName = dtDate.ToString("MMMM");

                        PropertiesSeperator containerPage2 = DataFactory.Instance.GetDefault<PropertiesSeperator>(savedyr);
                        containerPage2.PageName = sMonthFullName.ToString();
                        var savedmonth = DataFactory.Instance.Save(containerPage2, SaveAction.Publish, AccessLevel.NoAccess);

                        DataFactory.Instance.Move(page.ContentLink as PageReference, savedmonth);
                    }
                    else {
                        var pagemonth = page.Created.Month;

                        int iMonthNo = pagemonth;
                        DateTime dtDate = new DateTime(2000, iMonthNo, 1);
                        string sMonthFullName = dtDate.ToString("MMMM");

                        var Monthcheck = DataFactory.Instance.GetChildren(existyr.FirstOrDefault().ContentLink as PageReference);
                        var existMONTH = Monthcheck.Where(p => p.Name == sMonthFullName.ToString() && p.PageTypeName == typeof(PropertiesSeperator).Name);
                        //check if month exist
                        if (existMONTH.Count() < 1)
                        {
                            PropertiesSeperator containerPage3 = DataFactory.Instance.GetDefault<PropertiesSeperator>(existyr.FirstOrDefault().ContentLink as PageReference);
                            containerPage3.PageName = sMonthFullName.ToString();
                            var curretnsaveddmonth = DataFactory.Instance.Save(containerPage3, SaveAction.Publish, AccessLevel.NoAccess);
                            DataFactory.Instance.Move(page.ContentLink as PageReference, curretnsaveddmonth);
                        }
                        else {
                            DataFactory.Instance.Move(page.ContentLink as PageReference, existMONTH.FirstOrDefault().ContentLink as PageReference);


                        }

                    }

                }

                //Delete 15 months older pages
                //DateTime delete = DateTime.Now.AddMonths(-15);

                //PropertyCriteriaCollection listpagepropdelete = new PropertyCriteriaCollection();
                //PropertyCriteria Listcriteriadelete = new PropertyCriteria();
                //Listcriteriadelete.Condition = CompareCondition.LessThan;
                //Listcriteriadelete.Name = "PageCreated";
                //Listcriteriadelete.Type = PropertyDataType.Date;
                //Listcriteriadelete.Value = delete.ToString();
                //Listcriteriadelete.Required = true;
                //listpagepropdelete.Add(Listcriteriadelete);

                //PageDataCollection pageListForNewsPageDelete = DataFactory.Instance.FindPagesWithCriteria(pageroot.ContentLink as PageReference, listpagepropdelete);
                //foreach (var pageDelete in pageListForNewsPageDelete)
                //{
                //    DataFactory.Instance.Delete(pageDelete.ContentLink, true);
                //}


                return "Job Executed successfully";

            }
            return "There are no pages to move";
        }
        public ActionResult Index(string submit)
        {
            int countOfRolesCreated = 0;
            int countOfUsersCreated = 0;

            #region Use EPiServer classes to create roles and users

            UIUserCreateStatus   status;
            IEnumerable <string> errors = new List <string>();

            foreach (string role in rolesToCreate)
            {
                if (!roles.RoleExists(role))
                {
                    roles.CreateRole(role);
                    countOfRolesCreated++;
                }
            }

            foreach (var item in Users)
            {
                if (users.GetUser(item.UserName) == null)
                {
                    var newUser = users.CreateUser(item.UserName, password,
                                                   email: $"{item.UserName.ToLower()}{email}",
                                                   passwordQuestion: null, passwordAnswer: null,
                                                   isApproved: true,
                                                   status: out status, errors: out errors);

                    if (status == UIUserCreateStatus.Success)
                    {
                        countOfUsersCreated++;
                        roles.AddUserToRoles(item.UserName, item.Roles);
                    }
                }
            }

            #endregion

            #region Use EPiServer classes to give access rights to Root, Recycle Bin, and News & Events

            SetSecurity(ContentReference.RootPage, adminsRole, AccessLevel.FullAccess);
            SetSecurity(ContentReference.RootPage, "WebAdmins", AccessLevel.NoAccess);
            SetSecurity(ContentReference.RootPage, "Administrators", AccessLevel.NoAccess);
            SetSecurity(ContentReference.RootPage, contentCreatorsRole, AccessLevel.Read | AccessLevel.Create | AccessLevel.Edit | AccessLevel.Delete);
            SetSecurity(ContentReference.RootPage, marketersRole, AccessLevel.Create | AccessLevel.Publish);

            SetSecurity(ContentReference.WasteBasket, adminsRole, AccessLevel.FullAccess);
            SetSecurity(ContentReference.WasteBasket, "Administrators", AccessLevel.NoAccess);

            // find the News & Events page
            var criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name      = "PageName",
                    Type      = PropertyDataType.LongString,
                    Condition = CompareCondition.Equal,
                    Value     = "News & Events"
                }
            };

            var pages = pageFinder.FindPagesWithCriteria(ContentReference.StartPage, criteria);

            if (pages.Count == 1)
            {
                // give News Editors full access and remove all access for others
                var news = pages[0].ContentLink;
                SetSecurity(news, newsEditorsRole, AccessLevel.FullAccess, overrideInherited: true);
                SetSecurity(news, contentCreatorsRole, AccessLevel.NoAccess, overrideInherited: true);
                SetSecurity(news, marketersRole, AccessLevel.NoAccess, overrideInherited: true);
            }

            // find the Press Releases page
            criteria = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Name      = "PageName",
                    Type      = PropertyDataType.LongString,
                    Condition = CompareCondition.Equal,
                    Value     = "Press Releases"
                }
            };

            pages = pageFinder.FindPagesWithCriteria(ContentReference.StartPage, criteria);

            if (pages.Count == 1)
            {
                // allow Lawyers and C-Level Execs to edit Press Releases
                // so they can approve/decline changes
                var pressReleases = pages[0].ContentLink;
                SetSecurity(pressReleases, lawyersRole, AccessLevel.Edit, overrideInherited: true);
                SetSecurity(pressReleases, cLevelExecsRole, AccessLevel.Edit, overrideInherited: true);
            }

            #endregion

            RegisterPersonas.IsEnabled = false;

            ViewData["message"] = $"Register personas completed successfully. {countOfRolesCreated} roles created. {countOfUsersCreated} users created and added to roles.";

            return(View("~/Features/RegisterPersonas/RegisterPersonas.cshtml"));
        }
 public virtual PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias,
                                                         String languageBranch)
 {
     return DataFactory.Instance.FindPagesWithCriteria(pageLink, criterias, languageBranch);
 }
        public override string Execute()
        {
            OnStatusChanged(string.Format(
                                "Starting execution of {0}", this.GetType()));

            var finder = ServiceLocator.Current
                         .GetInstance <IPageCriteriaQueryService>();

            var language = Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2);

            var criteria = new PropertyCriteriaCollection();

            if (language == "en")
            {
                criteria.Add(new PropertyCriteria
                {
                    Type      = PropertyDataType.LongString,
                    Name      = "PageName",
                    Condition = EPiServer.Filters.CompareCondition.Equal,
                    Value     = "Services"
                });
            }
            else if (language == "sv")
            {
                criteria.Add(new PropertyCriteria
                {
                    Type      = PropertyDataType.LongString,
                    Name      = "PageName",
                    Condition = EPiServer.Filters.CompareCondition.Equal,
                    Value     = "Tjänster"
                });
            }
            else
            {
                throw new InvalidOperationException($"No suppor for language branch: {language}");
            }

            var servicesPage = finder.FindPagesWithCriteria(
                ContentReference.RootPage as PageReference, criteria, language)[0] as ServicesPage;

            var loader = ServiceLocator.Current.GetInstance <IContentLoader>();

            if (servicesPage != null && servicesPage.MainContentArea != null && servicesPage.MainContentArea.Items.Any())
            {
                int count = 0;
                FormContainerBlock formContainerBlock = null;

                foreach (var item in servicesPage.MainContentArea.Items)
                {
                    try
                    {
                        formContainerBlock = loader.Get <FormContainerBlock>(item.ContentLink);
                    }
                    catch (TypeMismatchException)
                    {
                        if (count >= servicesPage.MainContentArea.Items.Count)
                        {
                            throw;
                        }
                    }
                    if (_stopSignaled)
                    {
                        return("Stop of job was called");
                    }
                    count++;
                }

                if (formContainerBlock != null)
                {
                    var formDataRepository = ServiceLocator.Current.GetInstance <IFormDataRepository>();

                    List <Submission> submittedData = formDataRepository.GetSubmissionData(
                        new FormIdentity(formContainerBlock.Form.FormGuid, servicesPage.Language.Name),
                        DateTime.Now.AddDays(-100), DateTime.Now)
                                                      .ToList();

                    if (submittedData.Count > 0)
                    {
                        var repo       = ServiceLocator.Current.GetInstance <IContentRepository>();
                        var clone      = servicesPage.CreateWritableClone() as ServicesPage;
                        var editString = servicesPage.MainBody.ToHtmlString();
                        int length     = editString.IndexOf("<div id=\"newsletter-receivers\">");

                        editString  = editString.Substring(0, length == -1 ? editString.Length : length);
                        editString += "<div id=\"newsletter-receivers\"><ul style='color:black;'>";
                        count       = 0;

                        foreach (var submission in submittedData)
                        {
                            string email;
                            if (language == "en")
                            {
                                email = submission.Data["__field_40"] as string;
                            }
                            else
                            {
                                email = submission.Data["__field_36"] as string;
                            }

                            editString += $"<li>{email}</li>";
                            if (_stopSignaled)
                            {
                                return("Stop of job was called");
                            }
                            count++;
                        }
                        editString    += "</ul></div>";
                        clone.MainBody = new XhtmlString(editString);
                        repo.Save(clone, EPiServer.DataAccess.SaveAction.CheckIn,
                                  EPiServer.Security.AccessLevel.NoAccess);

                        return($"The newsletter receivers list on the services-page has been updated and now contains {count} customer(s) in total.");
                    }
                    return("No submitted data was found");
                }
                return("No form container block was found");
            }
            return("No services page with the page name: 'Services' was found or services page was found but MainContentArea was empty.");
        }
        public override List<EventPageBase> GetEventPages()
        {
            PropertyCriteriaCollection criteria = new PropertyCriteriaCollection();

            var pageTypes = ServiceLocator.Current.GetInstance<IContentTypeRepository>().List();
            foreach (var pageType in pageTypes)
            {
                if (pageType.ModelType != null && typeof(EventPageBase).IsAssignableFrom(pageType.ModelType))
                {
                    PropertyCriteria pageTypeCriteria = new PropertyCriteria();
                    pageTypeCriteria.Condition = CompareCondition.Equal;
                    pageTypeCriteria.Value = pageType.ID.ToString();
                    pageTypeCriteria.Type = PropertyDataType.PageType;
                    pageTypeCriteria.Name = "PageTypeID";
                    pageTypeCriteria.Required = false;
                    criteria.Add(pageTypeCriteria);
                }
            }

            List<EventPageBase> eventList = new List<EventPageBase>();
            var sites = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<EPiServer.Web.SiteDefinitionRepository>().List();
            foreach (SiteDefinition siteDefinition in sites)
            {

                PageDataCollection allEvents = new PageDataCollection();

                var allLanguages = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>().ListEnabled();

                foreach (LanguageBranch languageBranch in allLanguages)
                {
                    allEvents.Add(DataFactory.Instance.FindPagesWithCriteria(siteDefinition.StartPage.ToPageReference(), criteria, languageBranch.LanguageID));
                }

                foreach (PageData currentEvent in allEvents)
                {
                    if (currentEvent as EventPageBase != null)
                        eventList.Add(currentEvent as EventPageBase);
                }
            }
            return eventList;

        }
        public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
        {
            // Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
            if (pageLink.CompareToIgnoreWorkID(EntryRoot))
            {
                pageLink = CloneRoot;
            }
            else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
            {
                pageLink = new PageReference(pageLink.ID);
            }

            var pages = DataFactory.Instance.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);

            // Return cloned search result set
            return new PageDataCollection(pages.Select(ClonePage));
        }
        private static PageDataCollection GetPages()
        {
            PropertyCriteriaCollection criterias = new PropertyCriteriaCollection();

            PropertyCriteria category = new PropertyCriteria();
            category.Condition = CompareCondition.NotEqual;
            category.Value = "-1";
            category.Type = PropertyDataType.PageType;
            category.Required = true;
            category.Name = "PageTypeID";

            criterias.Add(category);

            PageDataCollection objCollection = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, criterias);

            FilterForVisitor.Filter(objCollection);

            var pageTypeLimitter = new SitemapFilter(NOT_ALLOWED_PAGETYPES);
            pageTypeLimitter.Filter(objCollection);

            return objCollection;
        }
 public PropertyCriteriaExtractor(IEnumerable<IPropertyReferenceExtractor> extractors)
 {
     if (extractors == null) throw new ArgumentNullException("extractors");
     _extractors = extractors.ToList();
     _criteria = new PropertyCriteriaCollection();
 }
        public override PageDataCollection SearchRelations(Rule rule, int pageID, string searchKeyWord, PageReference hierarchyStart, bool isLeftRule)
        {
            string pageTypes = HttpUtility.UrlDecode(isLeftRule ? rule.PageTypeRight : rule.PageTypeLeft);
            PageDataCollection result = new PageDataCollection();

            if (!string.IsNullOrEmpty(pageTypes))
            {
                string[] pageTypeCollection = pageTypes.Split(';');
                PropertyCriteriaCollection pageTypeCriterias = new PropertyCriteriaCollection();

                if (hierarchyStart == null || hierarchyStart == PageReference.EmptyReference)
                    hierarchyStart = PageReference.RootPage;

                foreach (string s in pageTypeCollection)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        PropertyCriteria criteria = new PropertyCriteria();
                        criteria.Condition = EPiServer.Filters.CompareCondition.Equal;
                        criteria.Name = "PageTypeName";
                        criteria.Type = PropertyDataType.String;
                        criteria.Value = s;
                        pageTypeCriterias.Add(criteria);
                    }
                }

                PageDataCollection pages = DataFactory.Instance.FindPagesWithCriteria(hierarchyStart, pageTypeCriterias);

                PageData rootPage = DataFactory.Instance.GetPage(hierarchyStart);
                if (pageTypeCollection.Contains<string>(rootPage.PageTypeName) && !pages.Contains(rootPage))
                    pages.Add(rootPage);

                new EPiServer.Filters.FilterSort(EPiServer.Filters.FilterSortOrder.Alphabetical).Sort(pages);

                if (!string.IsNullOrEmpty(searchKeyWord))
                    for (int i = 0; i < pages.Count; i++)
                    {
                        if (pages[i].PageName.ToLower().Contains(searchKeyWord.ToLower()))
                            result.Add(pages[i]);
                    }
                else
                    result = pages;
            }

            return result;
        }
        private List<PageData> FindPagesContainSearchQuery(string searchQuery)
        {
            PropertyCriteriaCollection propertyCriteriaCollection = new PropertyCriteriaCollection();

            PropertyCriteria propertyCriteria = new PropertyCriteria()
            {
                Name = "PageName",
                Type = PropertyDataType.String,
                Condition = Filters.CompareCondition.Contained,
                Required = true,
                Value = searchQuery
            };

            propertyCriteriaCollection.Add(propertyCriteria);

            List<PageData> results =
                DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, propertyCriteriaCollection).ToList<PageData>();

            return results;
        }
        public ActionResult Index(DemoPage currentPage)
        {
            // Andrahandsalternativ till Constructor Injection
            // var loader1 = ServiceLocator.Current.GetInstance<IContentLoader>();

            var currentPageId = currentPage.ContentLink; // ID of a page is always in ContentLink property

            var startPageId = ContentReference.StartPage;
            IEnumerable <IContent> pages = loader.GetChildren <IContent>(startPageId);

            //Tvättar bort sidor som man inte får eller kan länka till
            IEnumerable <PageData> filteredListOfPages = FilterForVisitor.Filter(pages).Cast <PageData>();

            //Tvätta bort sidor som inte ska synas i navigeringen.
            IEnumerable <PageData> listWithPagesVisibleInNavigation = filteredListOfPages.Where(p => p.VisibleInMenu == true);

            // Ladda in alla föräldrar
            var allAncestors = loader.GetAncestors(currentPageId);

            // Bygg en lista med MenuItem som view model för menyn.
            var list = new List <MenuItem>();

            foreach (var page in listWithPagesVisibleInNavigation)
            {
                var item = new MenuItem();
                item.Page   = page;
                item.Active = allAncestors.Contains(page);

                list.Add(item);
            }

            // Laddar nyheter med GetChildren
            IEnumerable <PageData> myListOfPages = new List <PageData>();

            // Hämta sidor under sidan som egenskapen IdOfParentPageToList pekar ut
            if (!ContentReference.IsNullOrEmpty(currentPage.IdOfParentPageToList))
            {
                myListOfPages = loader.GetChildren <PageData>(currentPage.IdOfParentPageToList);
            }

            // Ladda nyheter med databas sök
            PageReference startPageForSearch = new PageReference(startPageId);
            var           criterias          = new PropertyCriteriaCollection
            {
                new PropertyCriteria
                {
                    Type      = PropertyDataType.String,
                    Name      = "PageName",
                    Condition = CompareCondition.Contained,
                    Value     = "alloy"
                }
            };
            var result = query.FindPagesWithCriteria(startPageForSearch, criterias);

            var model = new DemoPageViewModel();

            model.CurrentPage             = currentPage;
            model.MainMenuList            = listWithPagesVisibleInNavigation;
            model.MainMenuListWithItems   = list;
            model.MyListOfPages           = myListOfPages;
            model.RootPageOfMyListOfPages = loader.Get <PageData>(currentPage.IdOfParentPageToList);
            model.SearchResult            = result;

            return(View(model));
        }