public IEnumerable <IEventDetailsPage> SearchEvents(
            IEventPipeline pipeline,
            EventSearchSettings searchSettings)
        {
            Throw.IfNull(searchSettings, nameof(searchSettings));
            Throw.IfNull(pipeline, nameof(pipeline));

            using (var ctx = ContentSearchManager.GetIndex(IndexName).CreateSearchContext())
            {
                var queryable     = ctx.GetQueryable <EventDetailsSearchItem>();
                var searchResults = pipeline.Process(searchSettings, queryable).GetResults();

                if (searchResults != null && searchResults.TotalSearchResults > 0)
                {
                    var data = searchResults.Hits
                               .Where(i => i.Document != null)
                               .Select(i => i.Document);

                    var listResult = new List <IEventDetailsPage>();

                    foreach (var searchItem in data)
                    {
                        listResult.Add(_sitecoreService.GetItem <IEventDetailsPage>(searchItem.GetItem()));
                    }

                    return(listResult);
                }
            }

            return(Enumerable.Empty <IEventDetailsPage>());
        }
Exemplo n.º 2
0
        public ArticleStruct Post([FromBody] CreateArticleRequest content)
        {
            try
            {
                var publicationDate = DateTime.Parse(content.PublicationDate);
                var parent          = _articleUtil.GenerateDailyFolder(content.PublicationID, publicationDate);
                var rinsedName      = ItemUtil.ProposeValidItemName(content.Name);
                var articleCreate   = _sitecoreMasterService.Create <IArticle, IArticle_Date_Folder>(parent, rinsedName);

                //Hack to start the workflow
                var articleItem  = _sitecoreMasterService.GetItem <Item>(articleCreate._Id);
                var savedArticle = _sitecoreMasterService.GetItem <ArticleItem>(articleCreate._Id);
                //var intialWorkflow = _sitecoreMasterService.Database.WorkflowProvider.GetWorkflow("{926E6200-EB76-4AD4-8614-691D002573AC}");
                var intialWorkflow = _sitecoreMasterService.Database.WorkflowProvider.GetWorkflow(savedArticle.Crawl <ISite_Root>().Workflow.ToString());
                intialWorkflow.Start(articleItem);

                var article = _sitecoreMasterService.GetItem <IArticle__Raw>(articleCreate._Id);
                article.Title = content.Name;
                article.Planned_Publish_Date = publicationDate;
                article.Created_Date         = DateTime.Now;
                article.Article_Number       = SitecoreUtil.GetNextArticleNumber(_articleSearch.GetNextArticleNumber(content.PublicationID), content.PublicationID);
                _sitecoreMasterService.Save(article);
                savedArticle = _sitecoreMasterService.GetItem <ArticleItem>(articleCreate._Id);
                var articleStruct = _articleUtil.GetArticleStruct(savedArticle);
                return(articleStruct);
            }
            catch (Exception ex)
            {
                return(new ArticleStruct {
                    RemoteErrorMessage = ex.ToString()
                });
            }
        }
Exemplo n.º 3
0
        public JsonResult <string[]> Get()
        {
            List <string> result         = new List <string>();
            var           siteConfigItem = _sitecoreService.GetItem <ISite_Config>(Constants.ScripRootNode);

            if (siteConfigItem == null)
            {
                return(Json(result.ToArray()));
            }
            var supportingDocumentFieldValue = siteConfigItem.Supporting_Documents_Folder;

            if (supportingDocumentFieldValue == new Guid())
            {
                return(Json(result.ToArray()));
            }
            var supportingDocumentFolder = _sitecoreService.GetItem <IGlassBase>(supportingDocumentFieldValue);

            if (supportingDocumentFolder == null)
            {
                return(Json(result.ToArray()));
            }
            result.Add(supportingDocumentFolder._Name);
            result.Add(supportingDocumentFolder._Path);
            return(Json(result.ToArray()));
        }
        public void Process(HttpRequestArgs args)
        {
            var item = Context.Item;

            if (item != null &&
                item.TemplateID == EventDetailsPage.TemplateId &&
                Tracker.Current != null)
            {
                var eventItem = _sitecoreService.GetItem <IEventDetailsPage>(item);

                var profileItem    = Context.Database.GetItem(new ID(ItemIds.PreferableEventProfileItemId));
                var datasourceItem = Context.Database.GetItem(new ID(ItemIds.DatasourceItemId));

                var preferableEventTypeProfile   = Tracker.Current.Interaction.Profiles[profileItem.Name];
                var eventPersonalizationSettings = _sitecoreService.GetItem <IEventPersonalizationSettings>(datasourceItem);

                var scores = new Dictionary <string, double>();
                foreach (var tag in eventItem.Tags)
                {
                    scores.Add(tag.TagName, eventPersonalizationSettings.PointPerVisit);
                }

                preferableEventTypeProfile.Score(scores);
                preferableEventTypeProfile.UpdatePattern();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Maps the Sitecore.Context.Item to a model
        /// </summary>
        /// <typeparam name="T">The type to return</typeparam>
        /// <param name="options">Options for how the model will be retrieved</param>
        /// <returns></returns>
        public virtual object GetContextItem(GetKnownOptions options)
        {
            Assert.IsNotNull(options, "options must no be  null");

            options.Item = ContextItem;

            return(SitecoreService.GetItem(options));
        }
Exemplo n.º 6
0
 public MovieManager(ISitecoreService masterService, ISitecoreContext context)
 {
     _masterService           = masterService;
     _context                 = context;
     _moviesRootFolder        = masterService.GetItem <Movies>(RebootConstants.MovieRootID.Guid);
     _trailersRootFolder      = masterService.GetItem <TrailersModel>(RebootConstants.TrailerRootID.Guid);
     _prodCompaniesRootFolder = masterService.GetItem <ProductionCompanies>(RebootConstants.ProductionCompaniesRootID.Guid);
 }
Exemplo n.º 7
0
        public IEnumerable <IGlassBase> GetReferrers(IGlassBase glassItem)
        {
            var item = _service.GetItem <Item>(glassItem._Id, glassItem._Language);

            var links          = Globals.LinkDatabase.GetReferrers(item);
            var linkReferences = links.Select(i => _service.GetItem <IGlassBase>(i.SourceItemID.Guid, i.SourceItemLanguage, inferType: true)).Where(i => i != null);

            return(linkReferences);
        }
Exemplo n.º 8
0
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // get the model type
            var modelType = bindingContext.ModelType;

            var resolver = DependencyResolver.CreateStandardResolver();

            // get the sitecore service
            ISitecoreService sitecoreService = resolver.Resolve <ISitecoreService>();

            if (sitecoreService == null)
            {
                throw new Exception("Unable to resolve dependency for Glass.Sitecore.Mapper.ISitecoreService. Register the interface once in the global application, or in the AreaRegistration.");
            }

            Guid   dataSourceId   = Guid.Empty;
            string dataSourcePath = string.Empty;

            // check if its an ID or path
            if (!Guid.TryParse(DataSource, out dataSourceId))
            {
                dataSourcePath = DataSource;
            }

            // do some workflow
            if (Behavior == GlassDataSourceBehavior.Failover)
            {
                // get the current rendering context id
                // uses monads http://nuget.org/packages/Monads
                var currentId = RenderingContext.CurrentOrNull
                                .With(x => x.Rendering)
                                .With(x => x.Item)
                                .With(x => x.ID)
                                .Return(x => x.Guid, Guid.Empty);

                // if the current id is not null, use it for the datasource
                if (currentId != Guid.Empty)
                {
                    dataSourceId = currentId;
                }
            }

            // do we have an id?
            if (dataSourceId != Guid.Empty)
            {
                return(sitecoreService.GetItem(modelType, dataSourceId));
            }

            // do we have a path?
            if (!string.IsNullOrWhiteSpace(dataSourcePath))
            {
                return(sitecoreService.GetItem(modelType, dataSourcePath));
            }

            // no item found to bind
            return(null);
        }
Exemplo n.º 9
0
        // GET api/<controller>
        public JsonResult <DirectoryStruct[]> Get()
        {
            var item     = _sitecoreService.GetItem <Item>("{11111111-1111-1111-1111-111111111111}");
            var children = new List <DirectoryStruct>();

            foreach (var child in item.Children.ToArray())
            {
                var dir = new DirectoryStruct
                {
                    Name         = child.Name,
                    ChildrenList = new List <string>()
                };
                var nestedChildren = child.Children.ToArray();
                foreach (var name in nestedChildren)
                {
                    dir.ChildrenList.Add(name.Name);
                }

                if (nestedChildren.Length == 0)
                {
                    var    media = MediaManager.GetMedia(child);
                    string ext   = media.Extension.ToLower();

                    if (!(ext.Contains("gif") ||
                          ext.Contains("jpg") ||
                          ext.Contains("png")))
                    {
                        continue;
                    }
                }

                if (nestedChildren.Length == 0)
                {
                    var    media = MediaManager.GetMedia(child);
                    string ext   = media.Extension.ToLower();

                    if (!(ext.Contains("mp3") ||
                          ext.Contains("doc") ||
                          ext.Contains("docx") ||
                          ext.Contains("xls") ||
                          ext.Contains("xlsx") ||
                          ext.Contains("ppt") ||
                          ext.Contains("pptx") ||
                          ext.Contains("pdf")))
                    {
                        continue;
                    }
                }
                dir.Children = dir.ChildrenList.ToArray();
                children.Add(dir);
            }

            return(Json(children.ToArray()));
        }
Exemplo n.º 10
0
        public JsonResult <List <TaxonomyStruct> > Get()
        {
            List <TaxonomyStruct> result = new List <TaxonomyStruct>();
            var baseFolder = _sitecoreService.GetItem <IFolder>(new Guid("{E8A37C2D-FFE3-42D4-B38E-164584743832}"));

            result = baseFolder?._ChildrenWithInferType.OfType <ITaxonomy_Item>()
                     .Select(eachChild => new TaxonomyStruct()
            {
                Name = eachChild.Item_Name, ID = eachChild._Id
            }).ToList();
            return(Json(result));
        }
Exemplo n.º 11
0
        private string GetDictionaryFieldValue(string relativePath, string defaultValue)
        {
            //Get Dicitionary Path from Site Root path
            IDictionarySettings dictionarySettings = _sitecoreService.GetItem <IDictionarySettings>(Context.Site?.RootPath);
            var fullPath       = dictionarySettings?.DictionaryPath + relativePath;
            var dictionaryItem = _sitecoreService.GetItem <IDictionaryEntry>(fullPath);

            if (dictionaryItem != null)
            {
                return(dictionaryItem.Phrase ?? defaultValue);
            }
            return(defaultValue);
        }
Exemplo n.º 12
0
        public JsonResult <HDirectoryStruct> Get(string guid)
        {
            var item     = _sitecoreService.GetItem <Item>(guid);
            var children = item.Children.Select(child => GetHierarchy(child.Paths.Path)).ToList();

            var childNode = new HDirectoryStruct()
            {
                ChildrenList = children, Name = item.DisplayName, ID = item.ID.ToGuid()
            };

            childNode.Children = childNode.ChildrenList.ToArray();
            return(Json(childNode));
        }
Exemplo n.º 13
0
        /// <summary>
        /// This is a search implementatation where you want to pass the database name along with the filter.
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="database"></param>
        /// <returns></returns>
        public IArticleSearchResults SearchCustomDatabase(IArticleSearchFilter filter, string database)
        {
            using (var context = SearchContextFactory.Create(database))
            {
                var query = context.GetQueryable <ArticleSearchResultItem>()
                            .Filter(i => i.TemplateId == IArticleConstants.TemplateId)
                            .FilterTaxonomies(filter, ItemReferences, GlobalService)
                            .ExcludeManuallyCurated(filter)
                            .FilteryByArticleNumbers(filter)
                            .FilteryByEScenicID(filter)
                            .ApplyDefaultFilters();

                if (filter.PageSize > 0)
                {
                    query = query.Page(filter.Page > 0 ? filter.Page - 1 : 0, filter.PageSize);
                }

                query = query.OrderByDescending(i => i.ActualPublishDate);
                ISitecoreService localSearchContext = SitecoreFactory(database);
                var results = query.GetResults();
                return(new ArticleSearchResults
                {
                    Articles = results.Hits.Select(h => localSearchContext.GetItem <IArticle>(h.Document.ItemId.Guid))
                });
            }
        }
        public IEnumerable <IEventListPage> GetEventLists()
        {
            var settings = _searchSettingsReader.Settings;

            Throw.IfNull(settings, nameof(settings));

            using (var ctx = ContentSearchManager.GetIndex(settings.IndexName).CreateSearchContext())
            {
                var queryable     = ctx.GetQueryable <EventListSearchResultItem>();
                var searchResults = queryable
                                    .Where(x => x.TemplateId == _templateId &&
                                           x.ItemId != _standardValuesId &&
                                           !x.ExcludeFromNavigation)
                                    .OrderBy(x => x.Name)
                                    .GetResults();

                if (searchResults != null && searchResults.TotalSearchResults > 0)
                {
                    var data = searchResults.Hits
                               .Where(i => i.Document != null)
                               .Select(i => i.Document);

                    var items      = data.Select(x => x.GetItem());
                    var eventLists = items.Select(x => _sitecoreService.GetItem <IEventListPage>(x));

                    return(eventLists);
                }
            }

            return(Enumerable.Empty <IEventListPage>());
        }
Exemplo n.º 15
0
        private IList <ISite_Root> BuildSiteRootsContext()
        {
            var contentItem = SitecoreService.GetItem <IGlassBase>("/sitecore/content");
            var siteRoots   = contentItem._ChildrenWithInferType.OfType <ISite_Root>();

            return(siteRoots.ToList());
        }
        public IEnumerable <TResult> GetAll(
            ID templateId,
            Expression <Func <TSearchItem, bool> > filter    = null,
            Expression <Func <TSearchItem, object> > orderBy = null,
            string indexName       = "sitecore_web_index",
            bool showStandardValue = false)
        {
            using (var ctx = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
            {
                var searchResults = GetAll(
                    ctx.GetQueryable <TSearchItem>()
                    .Where(i => i.TemplateId == templateId && (showStandardValue || i.Name != StandardValues)),
                    filter,
                    orderBy)
                                    .GetResults();

                if (searchResults != null && searchResults.TotalSearchResults > 0)
                {
                    var data = searchResults.Hits
                               .Where(i => i.Document != null)
                               .Select(i => i.Document);

                    var listResult = new List <TResult>();

                    foreach (var searchItem in data)
                    {
                        listResult.Add(_sitecoreService.GetItem <TResult>(searchItem.GetItem()));
                    }

                    return(listResult);
                }
            }

            return(Enumerable.Empty <TResult>());
        }
Exemplo n.º 17
0
        public async Task <ResultModel> Create(object datasource, PagingModel paging)
        {
            var ds = datasource as SelectedSitecoreItemsDataSource;

            if (ds?.Items == null)
            {
                return(new ResultModel
                {
                    ErrorMessage = "No SelectedSitecoreItemsDataSource received"
                });
            }

            var ids = (IEnumerable <Guid>)ds.Items;

            if (paging.From.HasValue && paging.From.Value > 0)
            {
                ids = ids.Skip(paging.From.Value);
            }

            var rows = paging.Rows ?? 100;

            ids = ids.Take(rows);

            var items       = ids.Select(id => _sitecore.GetItem <object>(id, inferType: true)).ToList();
            var resultitems = items.OfType <IResultItem>().ToList();

            return(new ResultModel
            {
                Items = resultitems,
                TotalCount = ds.Items.Count
            });
        }
Exemplo n.º 18
0
        public static T Save <T>(this T obj, IGlassBase parent, ISitecoreService service) where T : class, IHasExternalId
        {
            if (obj.HasIDTableEntry())
            {
                if (obj.IsUpdateRequired())
                {
                    //      Any data manipulation can go hear before
                    //      updating the database once again
                    //      This case will never be hit in this sample
                    using (new SecurityDisabler())
                    {
                        service.Save(obj);
                    }
                }
                obj = service.GetItem <T>(obj.GetItemIdFromIDTableEntry().Guid);
            }
            else
            {
                obj.Name = ItemUtil.ProposeValidItemName(obj.Name).ToLower().Replace(" ", "-");
                using (new SecurityDisabler())
                {
                    service.Create(parent, obj);
                }
            }

            return(obj);
        }
Exemplo n.º 19
0
        private void ResetFieldValue <T>() where T : class, IPageBase, ISearchableContent
        {
            SearchResults <T> results = _siteSearchService.GetSearchResultsAs <T>(w => w, f => f, s => s);

            foreach (SearchHit <T> hit in results.Hits)
            {
                Item m = _sitecoreContext.GetItem <Item>(hit.Document.Id);
                if (m == null)
                {
                    Log.Warn(string.Format("Could not find item with id {0}", hit.Document.Id), results);
                    continue;
                }
                ImageField imf = m.Fields[IHasImageConstants.ImageFieldId];
                if (imf.MediaItem != null)
                {
                    continue;
                }
                m.Editing.BeginEdit();
                try
                {
                    imf.InnerField.Reset();
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("Error occured while processing item with id {0}", hit.Document.Id), ex,
                              results);
                    m.Editing.CancelEdit();
                }
                finally
                {
                    m.Editing.EndEdit();
                }
            }
        }
Exemplo n.º 20
0
        public JsonResult <List <TaxonomyStruct> > Get(string searchTerm)
        {
            var taxoGuid     = new Guid("{E8A37C2D-FFE3-42D4-B38E-164584743832}");
            var taxonomyItem = _sitecoreService.GetItem <Item>(taxoGuid);

            if (taxonomyItem == null)
            {
                return(null);
            }
            List <Item> children;

            if (!string.IsNullOrEmpty(searchTerm))
            {
                children = taxonomyItem.Axes.GetDescendants().Where(i => TaxonomyMatch(i.Name, searchTerm)).ToList();
            }
            else
            {
                children = taxonomyItem.Axes.GetDescendants().ToList();
            }
            var matches = children.Select(child => new TaxonomyStruct {
                ID = child.ID.Guid, Name = child.DisplayName, Section = child.ParentID.Guid.Equals(taxoGuid) ? null : child.ParentID.Guid.ToString()
            }).ToList();

            return(Json(matches));
        }
Exemplo n.º 21
0
        public async Task <ActionResult> Execute(string id, PagingModel paging)
        {
            var dataSourceItem = _sitecoreService.GetItem <object>(id, inferType: true);

            if (dataSourceItem == null)
            {
                return(HttpNotFound($"No datasource '{id}' available"));
            }

            var factory = _map[dataSourceItem.GetType()];

            if (factory == null)
            {
                return(new NewtonsoftJsonResult
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    StatusDescription = $"No IDataService available for {dataSourceItem.GetType().FullName}"
                });
            }

            var dataservice = factory();
            var result      = await dataservice.Create(dataSourceItem, paging);

            return(new NewtonsoftJsonResult(result));
        }
Exemplo n.º 22
0
        private List <SubNavItem> GetSubNavItems()
        {
            List <SubNavItem> subNavItems = new List <SubNavItem>();

            if (PageContext.Current.DescendsFrom(Templates.SubNav.ID))
            {
                Item parent = PageContext.Current.Parent;
                foreach (Item item in parent.GetChildren())
                {
                    if (item.DescendsFrom(Templates.SubNav.ID))
                    {
                        ISubNav subNav = sitecoreService.GetItem <ISubNav>(new GetItemByItemOptions {
                            Item = item
                        });
                        if (subNav != null)
                        {
                            subNavItems.Add(new SubNavItem
                            {
                                Title      = new HtmlString(mvcContext.GlassHtml.Editable(subNav, x => x.Title)),
                                Icon       = new HtmlString(mvcContext.GlassHtml.Editable(subNav, x => x.Icon)),
                                ActiveIcon = new HtmlString(mvcContext.GlassHtml.Editable(subNav, x => x.ActiveIcon)),
                                Url        = subNav.Url
                            });
                        }
                    }
                }
            }
            return(subNavItems);
        }
Exemplo n.º 23
0
        public static T GetItem <T>(this ISitecoreService service, string path, Action <GetItemByPathBuilder> config) where T : class
        {
            var builder = new GetItemByPathBuilder().Path(path);

            config(builder);
            return(service.GetItem <T>(builder));
        }
Exemplo n.º 24
0
        public static T GetItem <T>(this ISitecoreService service, Query query, Action <GetItemByQueryBuilder> config) where T : class
        {
            var builder = new GetItemByQueryBuilder().Query(query.Value);

            config(builder);
            return(service.GetItem <T>(builder));
        }
Exemplo n.º 25
0
        public static T GetItem <T>(this ISitecoreService service, Item item, Action <GetItemByItemBuilder> config) where T : class
        {
            var builder = new GetItemByItemBuilder().Item(item);

            config(builder);
            return(service.GetItem <T>(builder));
        }
Exemplo n.º 26
0
        public static T GetItem <T>(this ISitecoreService service, Guid id, Action <GetItemByIdBuilder> config) where T : class
        {
            var builder = new GetItemByIdBuilder().Id(id);

            config(builder);
            return(service.GetItem <T>(builder));
        }
Exemplo n.º 27
0
        public TaxonomyFolders(ISitecoreService sitecoreService)
        {
            _sitecoreService = sitecoreService;

            var mainTaxonomyFolder = _sitecoreService.GetItem <Item>(ItemReferences.Instance.GlobalTaxonomyFolder);

            _taxonomyFolders = mainTaxonomyFolder.Children;
        }
Exemplo n.º 28
0
        // GET api/<controller>
        public JsonResult <int[]> Get(string path)
        {
            ImageMedia mediaImage = _sitecoreService.GetItem <ImageMedia>(path);
            var        image      = mediaImage.GetImage();

            if (image == null)
            {
                return(null);
            }
            var dimens = new int[2];

            if (!Int32.TryParse(image.Width.ToString(), out dimens[0]) || !Int32.TryParse(image.Height.ToString(), out dimens[1]))
            {
                return(null);
            }
            return(Json(dimens));
        }
Exemplo n.º 29
0
 // GET api/<controller>
 public JsonResult <Guid> Get(string path)
 {
     if (!string.IsNullOrEmpty(path))
     {
         var item = _sitecoreService.GetItem <Item>(path);
         return(Json(item?.ID.Guid ?? new Guid()));
     }
     return(Json(new Guid()));
 }
Exemplo n.º 30
0
        protected override NlmPublisherModel Resolve(ArticleItem source, ResolutionContext context)
        {
            var publisher = _service.GetItem <INLM_Config>(_itemReferences.NlmConfiguration)?.Publisher_Name;

            return(new NlmPublisherModel
            {
                Name = publisher
            });
        }