protected override IList <GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageId, out bool languageSpecific)
        {
            var videoTypeId       = _contentTypeRepository.Load(typeof(Video));
            var videoFolderTypeId = _contentTypeRepository.Load(typeof(VideoFolder));

            languageSpecific = false;
            if (contentLink.CompareToIgnoreWorkID(EntryPoint))
            {
                var test =
                    _items.Where(x => x.ContentTypeID.Equals(videoFolderTypeId.ID))
                    .Select(p => new GetChildrenReferenceResult()
                {
                    ContentLink = p.ContentLink, ModelType = typeof(VideoFolder)
                }).ToList();
                return(test);
            }
            var content = LoadContent(contentLink, LanguageSelector.AutoDetect());

            return(_items
                   .Where(p => p.ContentTypeID.Equals(videoTypeId.ID) && p.ParentLink.ID.Equals(content.ContentLink.ID))
                   .Select(p => new GetChildrenReferenceResult()
            {
                ContentLink = p.ContentLink, ModelType = typeof(Video)
            }).ToList());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Populates a list of content items of the provided content type
        /// </summary>
        /// <param name="contentTypeAudit"></param>
        /// <param name="includeReferences"></param>
        /// <param name="includeParentDetail"></param>
        public ContentTypeAudit GenerateContentTypeAudit(int contentTypeId,
                                                         bool includeReferences, bool includeParentDetail)
        {
            var contentType = _contentTypeRepository.Load(contentTypeId);

            var contentTypeAudit = new ContentTypeAudit
            {
                ContentTypeId = contentTypeId,
                Name          = contentType.Name,
                Usages        = new List <ContentTypeAudit.ContentItem>()
            };

            var contentModelUsages = _contentModelUsage.ListContentOfContentType(contentType)
                                     .Where(cmu => cmu.ContentLink != ContentReference.WasteBasket &&
                                            !_contentRepository.GetAncestors(cmu.ContentLink).Select(ic => ic.ContentLink).Contains(ContentReference.WasteBasket))
                                     .Select(contentUsage => new
            {
                ContentLink = contentUsage.ContentLink.ToReferenceWithoutVersion(),
                Name        = contentUsage.Name
            })
                                     .Distinct()
                                     .Select(distinctContentUsage => new
            {
                ContentLink = distinctContentUsage.ContentLink,
                Name        = distinctContentUsage.Name,
                ContentItem = _contentRepository.Get <IContent>(distinctContentUsage.ContentLink)
            });

            foreach (var cmu in contentModelUsages)
            {
                var siteDefinition = _siteDefinitionResolver.GetByContent(cmu.ContentLink, true);

                contentTypeAudit.Usages.Add(new ContentTypeAudit.ContentItem
                {
                    Name        = cmu.Name,
                    ContentLink = cmu.ContentLink,
                    SiteId      = siteDefinition?.Id ?? Guid.Empty,
                    Parent      = includeParentDetail && cmu.ContentItem.ParentLink != ContentReference.EmptyReference
                        ? new ContentTypeAudit.ContentItem
                    {
                        Name        = _contentRepository.Get <IContent>(cmu.ContentItem.ParentLink).Name,
                        ContentLink = cmu.ContentItem.ParentLink
                    }
                        : null,
                    PageReferences = includeReferences
                        ? _contentRepository.GetReferencesToContent(cmu.ContentLink, true)
                                     .Select(rtc => new ContentTypeAudit.ContentItem.PageReference
                    {
                        Name        = rtc.OwnerName,
                        ContentLink = rtc.OwnerID,
                        SiteId      = _siteDefinitionResolver.GetByContent(rtc.OwnerID, true)?.Id ?? Guid.Empty
                    }).ToList()
                        : new List <ContentTypeAudit.ContentItem.PageReference>()
                });
            }

            return(contentTypeAudit);
        }
        private void DisallowAll <T>()
        {
            var page    = _contentTypeRepository.Load(typeof(T));
            var setting = new AvailableSetting
            {
                Availability = Availability.None
            };

            _availableSettingsRepository.RegisterSetting(page, setting);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creat media data in folder
        /// </summary>
        /// <param name="fileInfo">File input</param>
        /// <param name="folderRef">Content reference to parent folder</param>
        public ContentReference CreateFile(FileInfo fileInfo, ContentReference folderRef)
        {
            //try
            //{
            using (var fileStream = fileInfo.OpenRead())
            {
                var mediaDataResolver = ServiceLocator.Current.GetInstance <ContentMediaResolver>();
                var blobFactory       = ServiceLocator.Current.GetInstance <BlobFactory>();

                //Get extension filename
                var fileExtension = Path.GetExtension(fileInfo.Name); // ex. .jpg or .txt

                var media = (from d in _contentRepository.GetChildren <MediaData>(folderRef)
                             where string.Compare(d.Name, fileInfo.Name, StringComparison.OrdinalIgnoreCase) == 0
                             select d).FirstOrDefault();

                if (media == null)
                {
                    //Get a suitable MediaData type from extension
                    var mediaType   = mediaDataResolver.GetFirstMatching(fileExtension);
                    var contentType = _contentTypeRepository.Load(mediaType);
                    //Get a new empty file data
                    media      = _contentRepository.GetDefault <MediaData>(folderRef, contentType.ID);
                    media.Name = fileInfo.Name;
                }
                else
                {
                    media = media.CreateWritableClone() as MediaData;
                }

                //Create a blob in the binary container
                if (media != null)
                {
                    var blob = blobFactory.CreateBlob(media.BinaryDataContainer, fileExtension);
                    blob.Write(fileStream);

                    //Assign to file and publish changes
                    media.BinaryData = blob;
                }
                var fileRef = _contentRepository.Save(media, SaveAction.Publish, AccessLevel.NoAccess);

                return(fileRef);
            }
            //}
            //catch (Exception ex)
            //{
            //    Logger.Error("Method CreateFile(FileInfo fileInfo, ContentReference folderRef) Unhandle Exception: {0}", ex.Message);
            //    return null;
            //}
        }
Exemplo n.º 5
0
        protected void ImportNodes(CatalogRoot root, CatalogContent catalogContent)
        {
            NodeImporter nodeImporter = ServiceLocator.Current.GetInstance <NodeImporter>();

            var defaultContentType = _typeRepository.Load(root.defaults.defaultNodeType);

            nodeImporter.DefaultContentType = defaultContentType;
            _log.Debug("Default content type: {0}", defaultContentType != null ? defaultContentType.FullName : "None");

            nodeImporter.RootCatalog = catalogContent;
            nodeImporter.Defaults    = root.defaults;

            nodeImporter.Import(root.nodes);
        }
        public string Execute(params string[] parameters)
        {
            if (string.IsNullOrEmpty(ContentTypeName) && parameters.Length > 0)
            {
                ContentTypeName = parameters.First();
            }
            if (string.IsNullOrEmpty(ContentTypeName))
            {
                return(null);
            }
            var ct = _typeRepository.Load(ContentTypeName);

            HandleContentType(ct);
            return(null);
        }
        public IEnumerable <ISelectItem> GetSelections(ExtendedMetadata metadata)
        {
            var contentType = _contentTypeRepository.Load <T>();

            if (contentType == null)
            {
                return(Enumerable.Empty <SelectItem>());
            }

            var startPage = _contentLoader.Get <StartPage>(SiteDefinition.Current.StartPage);

            var selectItems = _contentModelUsage
                              .ListContentOfContentType(contentType)
                              .Select(x => x.ContentLink.ToReferenceWithoutVersion())
                              .Distinct()
                              .Select(x => _contentLoader.Get <T>(x, startPage.Language))
                              .OfType <IContent>()
                              .Select(x => new SelectItem
            {
                Text  = x.Name,
                Value = x.ContentLink
            })
                              .OrderBy(x => x.Text)
                              .ToList();

            selectItems.Insert(0, new SelectItem());

            return(selectItems);
        }
        public void Initialize(InitializationEngine context)
        {
            _contentTypeRepository       = ServiceLocator.Current.GetInstance <IContentTypeRepository>();
            _availableSettingsRepository = ServiceLocator.Current.GetInstance <IAvailableSettingsRepository>();
            var sysRoot = _contentTypeRepository.Load("SysRoot") as PageType;
            var setting = new AvailableSetting
            {
                Availability = Availability.None,
                //Availability = Availability.Specific,

                /*AllowedContentTypeNames =
                 * {
                 *  nameof(StartPageType), // can't use custom interfaces with IContentTypeRepository
                 * }*/
            };

            _availableSettingsRepository.RegisterSetting(sysRoot, setting);
            // Disallow insertion for all product and article related pages
            DisallowAll <AboutUsPageType>();
            DisallowAll <ContactPageType>();
            //DisallowAll<NewsPageContainerType>();
            DisallowAll <SearchPageType>();
            DisallowAll <NewsPageType>();
            DisallowAll <StartPageType>();
            // Home Page
            SetPageRestriction <NewsContainerPageType>(new List <Type>
            {
                typeof(NewsPageType)
            });
        }
Exemplo n.º 9
0
        private TypeCount ToTypeCount(JToken instance)
        {
            TypeCount typeCount = new TypeCount
            {
                Type  = instance.Value <JObject>().Property("key").Value.ToString(),
                Count = Convert.ToInt32(instance.Value <JObject>().Property("doc_count").Value.ToString())
            };

            typeCount.ShortTypeName = typeCount.Type.GetShortTypeName();
            ContentType contentType = _contentTypeRepository.Load(typeCount.ShortTypeName);

            if (contentType != null)
            {
                typeCount.Name  = contentType.LocalizedName;
                typeCount.Group = contentType.LocalizedGroupName;
            }

            if (String.IsNullOrWhiteSpace(typeCount.Name))
            {
                typeCount.Name = typeCount.ShortTypeName;
            }

            if (String.IsNullOrWhiteSpace(typeCount.Group))
            {
                typeCount.Group = " " + LocalizationExtensions.TranslateWithPath("nocategory", "/epinovaelasticsearch/indexinspector/");
            }

            return(typeCount);
        }
Exemplo n.º 10
0
        protected string DownloadAsset(string url)
        {
            try
            {
                WebClient wc    = new WebClient();
                byte[]    asset = wc.DownloadData(url);

                string      ext         = Path.GetExtension(url);
                var         ctype       = _mresolver.GetFirstMatching(ext);
                ContentType contentType = _trepo.Load(ctype);

                //TODO: Support destination that should be resolved.
                var assetFile = _repo.GetDefault <MediaData>(SiteDefinition.Current.GlobalAssetsRoot, contentType.ID);
                assetFile.Name = Path.GetFileName(url);

                var blob = _blobFactory.CreateBlob(assetFile.BinaryDataContainer, ext);
                using (var s = blob.OpenWrite())
                {
                    var w = new StreamWriter(s);
                    w.BaseStream.Write(asset, 0, asset.Length);
                    w.Flush();
                }
                assetFile.BinaryData = blob;
                var assetContentRef = _repo.Save(assetFile, SaveAction.Publish);

                OnCommandOutput?.Invoke(this, assetContentRef); //If piped, output the reference that was just created
            } catch (Exception exc)
            {
                return(exc.Message);
            }

            return(null);
        }
Exemplo n.º 11
0
        private void OnPublishedContent(object sender, ContentEventArgs e)
        {
            var content = e.Content;

            CleanupOldTags(content);

            var contentType = _contentTypeRepository.Load(content.ContentTypeID);

            var tagProperties = contentType.PropertyDefinitions.Where(p => p.TemplateHint == "Tags").ToArray();

            if (!tagProperties.Any())
            {
                return;
            }

            foreach (var tagProperty in tagProperties)
            {
                var tagPropertyInfo = contentType.ModelType.GetProperty(tagProperty.Name);
                var tags = GetPropertyTags(content as ContentData, tagProperty);

                if (tagPropertyInfo == null)
                {
                    return;
                }

                var groupKeyAttribute =
                    tagPropertyInfo.GetCustomAttribute(typeof(TagsGroupKeyAttribute)) as TagsGroupKeyAttribute;
                var cultureSpecificAttribute
                    = tagPropertyInfo.GetCustomAttribute(typeof(CultureSpecificAttribute)) as CultureSpecificAttribute;

                var groupKey = TagsHelper.GetGroupKeyFromAttributes(groupKeyAttribute, cultureSpecificAttribute, content);

                _tagService.Save(content.ContentGuid, tags, groupKey);
            }
        }
        public override ActionResult Index(ContentRecommendationsBlock currentBlock)
        {
            var request = new ContentRecommendationViewModel
            {
                ContentId  = CurrentPage.ContentGuid.ToString(),
                SiteId     = SiteDefinition.Current.Id.ToString(),
                LanguageId = CurrentPage.Language.Name,
                NumberOfRecommendations = currentBlock.NumberOfRecommendations
            };

            var model = new ContentRecommendationsBlockViewModel {
                ContentRecommendationItems = new List <ContentRecommendationItem>()
            };

            foreach (var item in Task.Run(async() => await _recommendationService.GetRecommendationContent(HttpContext, request)).Result)
            {
                var sitePageData = item.Content as FoundationPageData;
                if (sitePageData == null)
                {
                    continue;
                }
                model.ContentRecommendationItems.Add(new ContentRecommendationItem
                {
                    Content     = sitePageData,
                    ContentUrl  = _urlResolver.GetUrl(item.Content.ContentLink),
                    ContentType = _contentTypeRepository.Load(item.Content.ContentTypeID).Name
                }
                                                     );
            }

            return(PartialView("~/Features/Blocks/Views/ContentRecommendationsBlock.cshtml", model));
        }
Exemplo n.º 13
0
        private void CheckContentProperties(IContent content, IList <Tag> tags)
        {
            var contentType = _contentTypeRepository.Load(content.ContentTypeID);

            foreach (var propertyDefinition in contentType.PropertyDefinitions)
            {
                if (!TagsHelper.IsTagProperty(propertyDefinition))
                {
                    continue;
                }

                var tagNames = GetTagNames(content, propertyDefinition);

                var allTags = tags;

                if (tagNames == null)
                {
                    RemoveFromAllTags(content.ContentGuid, allTags);
                    continue;
                }

                var addedTags = ParseTags(tagNames);

                // make sure the tags it has added has the ContentReference
                ValidateTags(allTags, content.ContentGuid, addedTags);

                // make sure there's no ContentReference to this ContentReference in the rest of the tags
                RemoveFromAllTags(content.ContentGuid, allTags);
            }
        }
Exemplo n.º 14
0
        public virtual ContentType LocateContentType(string type)
        {
            //Try guid, try ID, try name
            Guid g = Guid.Empty;

            if (Guid.TryParse(type, out g))
            {
                return(_typerepo.Load(g));
            }
            int i = 0;

            if (Int32.TryParse(type, out i))
            {
                return(_typerepo.Load(i));
            }
            return(_typerepo.Load(type));
        }
 public CatalogContentTypeResolver(ReferenceConverter referenceConverter,
                                   IContentTypeRepository contentTypeRepository,
                                   ContentTypeModelRepository contentTypeModelRepository)
 {
     _referenceConverter           = referenceConverter;
     _contentTypeModelRepository   = contentTypeModelRepository;
     _metaClassContentTypeModelMap = PopulateMetadataMappings();
     _catalogContentType           = contentTypeRepository.Load(typeof(CatalogContent));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Populates a list of content items of the provided content type
        /// </summary>
        /// <param name="contentTypeAudit"></param>
        /// <param name="includeReferences"></param>
        /// <param name="includeParentDetail"></param>
        public void PopulateContentItemsOfType(ContentTypeAudit contentTypeAudit,
                                               bool includeReferences, bool includeParentDetail)
        {
            var contentType        = _contentTypeRepository.Load(contentTypeAudit.ContentTypeId);
            var contentModelUsages = _contentModelUsage.ListContentOfContentType(contentType)
                                     .Where(cmu => cmu.ContentLink != ContentReference.WasteBasket &&
                                            !_contentRepository.GetAncestors(cmu.ContentLink).Select(ic => ic.ContentLink).Contains(ContentReference.WasteBasket))
                                     .Select(contentUsage => new
            {
                ContentLink = contentUsage.ContentLink.ToReferenceWithoutVersion(),
                Name        = contentUsage.Name
            })
                                     .Distinct()
                                     .Select(distinctContentUsage => new
            {
                ContentLink = distinctContentUsage.ContentLink,
                Name        = distinctContentUsage.Name,
                ContentItem = _contentRepository.Get <IContent>(distinctContentUsage.ContentLink)
            });


            contentTypeAudit.Usages = contentModelUsages.Select(cmu => new ContentTypeAudit.ContentItem
            {
                Name        = cmu.Name,
                ContentLink = cmu.ContentLink,
                SiteId      = _siteDefinitionResolver.GetByContent(cmu.ContentLink, true).Id,
                Parent      = includeParentDetail && cmu.ContentItem.ParentLink != ContentReference.EmptyReference
                    ? new ContentTypeAudit.ContentItem
                {
                    Name        = _contentRepository.Get <IContent>(cmu.ContentItem.ParentLink).Name,
                    ContentLink = cmu.ContentItem.ParentLink
                }
                    : null,
                PageReferences = includeReferences
                    ? _contentRepository.GetReferencesToContent(cmu.ContentLink, true)
                                 .Select(rtc => new ContentTypeAudit.ContentItem.PageReference
                {
                    Name        = rtc.OwnerName,
                    ContentLink = rtc.OwnerID,
                    SiteId      = _siteDefinitionResolver.GetByContent(rtc.OwnerID, true).Id
                }).ToList()
                    : new List <ContentTypeAudit.ContentItem.PageReference>()
            }).ToList();
        }
Exemplo n.º 17
0
        private string GetTypeContent(IContent content)
        {
            var contentName = "";

            var contentType = _contentTypeRepository.Load(content.GetType().BaseType);

            if (contentType != null)
            {
                contentName = contentType.DisplayName;
            }
            else
            {
                contentType = _contentTypeRepository.Load(content.GetType());

                if (contentType != null)
                {
                    if (!string.IsNullOrEmpty(contentType.DisplayName))
                    {
                        contentName = contentType.DisplayName;
                    }
                    else if (!string.IsNullOrEmpty(contentType.Name))
                    {
                        contentName = contentType.Name;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(contentName))
            {
                var memberInfo = content.GetType().BaseType;
                if (memberInfo != null)
                {
                    contentName = _localizationService.GetString("/contenttypes/" + memberInfo.Name.ToLower() + "/name", FallbackBehaviors.FallbackCulture);
                }
            }

            if (!string.IsNullOrWhiteSpace(contentName) && contentName.Contains("[Missing text"))
            {
                contentName = "";
            }

            return(contentName);
        }
        private IHttpActionResult GetAllOfType(string type, bool recursive = true)
        {
            if (string.IsNullOrEmpty(type) || pageTypeRepository.Load(type) == null)
            {
                return(Content(HttpStatusCode.BadRequest, "Requires valid content type"));
            }

            var pageReference = SiteDefinition.Current.StartPage.ToPageReference();
            var pageTypeId    = pageTypeRepository.Load(type).ID;
            var results       = contentLocator.FindPagesByPageType(pageReference, recursive, pageTypeId).ToList();
            var jsonResult    = new JArray();

            foreach (var item in results)
            {
                jsonResult.Add(JObject.Parse(item.ToJson()));
            }

            return(Json(jsonResult));
        }
        public virtual IHttpActionResult CreateContent(string ParentRef, string ContentType, [FromBody] ExpandoObject content, EPiServer.DataAccess.SaveAction action = EPiServer.DataAccess.SaveAction.Save)
        {
            //Instantiate content of named type
            var p = LookupRef(ParentRef);

            if (p == ContentReference.EmptyReference)
            {
                return(NotFound());
            }
            int j = 0;

            var ctype = _typerepo.Load(ContentType);

            if (ctype == null && int.TryParse(ContentType, out j))
            {
                ctype = _typerepo.Load(j);
            }
            if (ctype == null)
            {
                return(NotFound());
            }


            var properties = content as IDictionary <string, object>;

            IContent con = _repo.GetDefault <IContent>(p, ctype.ID);

            UpdateContentWithProperties(properties, con);
            //TODO: Handle local blocks. Handle properties that are not strings (parse values).

            if (properties.ContainsKey("Name"))
            {
                con.Name = properties["Name"].ToString();
            }
            EPiServer.DataAccess.SaveAction saveaction = action;
            if (properties.ContainsKey("SaveAction") && properties["SaveAction"] == "Publish")
            {
                saveaction = EPiServer.DataAccess.SaveAction.Publish;
            }
            var rt = _repo.Save(con, saveaction);

            return(Created <object>(new Uri(Url.Link("GetContentRoute", new { Reference = rt.ToReferenceWithoutVersion().ToString() })), new { reference = rt.ToReferenceWithoutVersion().ToString() }));
        }
Exemplo n.º 20
0
 public EpiFormDataExport(Guid formTypeId, int homePageId)
 {
     _formTypeId            = formTypeId;
     _homePage              = new ContentReference(homePageId);
     _contentTypeRepository = ServiceLocator.Current.GetInstance <IContentTypeRepository>();
     _contentModelUsage     = ServiceLocator.Current.GetInstance <IContentModelUsage>();
     _permanentStorate      = ServiceLocator.Current.GetInstance <IPermanentStorage>();
     _contentLoader         = ServiceLocator.Current.GetInstance <IContentLoader>();
     _contentRepository     = ServiceLocator.Current.GetInstance <IContentRepository>();
     _formContentType       = _contentTypeRepository.Load(_formTypeId);
 }
Exemplo n.º 21
0
        public ActionResult Index()
        {
            var contentType = _contentTypeRepository.Load(CurrentPage.ContentTypeID);
            var model       = new SingleTranslationsViewModel
            {
                ContentTypeName = contentType.Name,
                Translations    = _translationService.TranslationsFor(contentType.Name)
            };

            return(View("~/LanguageTool/Interaction/Views/Plugin.cshtml", model));
        }
        public string Execute(params string[] parameters)
        {
            ContentType ct = null;

            if (!string.IsNullOrEmpty(ContentTypeName))
            {
                ct = _trepo.Load(ContentTypeName);
            }
            else if (ContentTypeID != 0)
            {
                ct = _trepo.Load(ContentTypeID);
            }
            else if (parameters.Length > 0)
            {
                ct = _trepo.Load(parameters.First());
            }
            else
            {
                return("No Content Type specified");
            }

            ContentReference pref = ContentReference.EmptyReference;

            if (!string.IsNullOrEmpty(Parent))
            {
                pref = ContentReference.Parse(Parent);
            }
            else if (parameters.Length == 2)
            {
                pref = ContentReference.Parse(parameters.Last());
            }
            else
            {
                return("No Parent specified");
            }

            var content = _repo.GetDefault <IContent>(pref, ct.ID);

            OnCommandOutput?.Invoke(this, content);
            return($"Content of type {ct.Name} created below {pref} and passed to the pipe.");
        }
        private TResult CreateChild <TResult>(PageReference parentLink, string pageName) where TResult : PageData
        {
            TResult child;

            var resultPageType = _contentTypeRepository.Load(typeof(TResult));

            child          = _contentRepository.GetDefault <PageData>(parentLink, resultPageType.ID) as TResult;
            child.PageName = pageName;

            _contentRepository.Save(child, SaveAction.Publish, AccessLevel.NoAccess);

            return(child);
        }
Exemplo n.º 24
0
        public ActionResult GetProperties(int id)
        {
            var contentType = _contentTypeRepository.Load(id);
            var properties  = contentType.PropertyDefinitions
                              .Where(o => o.Type.DataType == PropertyDataType.LongString && o.Type.DefinitionType.Name == typeof(PropertyLongString).Name ||
                                     o.Type.DataType == PropertyDataType.String && o.Type.DefinitionType.Name == typeof(PropertyString).Name ||
                                     o.Type.DataType == PropertyDataType.Number ||
                                     o.Type.DataType == PropertyDataType.FloatNumber ||
                                     o.Type.DataType == PropertyDataType.Boolean ||
                                     o.Type.DataType == PropertyDataType.Date)
                              .Select(o => new
            {
                o.ID,
                o.Name,
            });

            return(new ContentResult
            {
                Content = JsonConvert.SerializeObject(properties),
                ContentType = "application/json",
            });
        }
Exemplo n.º 25
0
        private void BlockTypeChanged(object sender, EventArgs e)
        {
            DropDownList dropDownList  = (DropDownList)sender;
            string       selectedValue = dropDownList.SelectedValue;

            if (!string.IsNullOrEmpty(selectedValue))
            {
                if (dropDownList.ID.Equals(FromBlockTypeId))
                {
                    FromBlockType = _contentTypeRepository.Load(int.Parse(selectedValue));
                }
                else
                {
                    ToBlockType = _contentTypeRepository.Load(int.Parse(selectedValue));
                }

                if (dropDownList.ID.Equals(ToBlockTypeId) || _ddlTo.SelectedValue == ToBlockType.ID.ToString())
                {
                    ClearChildViewState();
                    Controls.Clear();
                    CreateChildControls();
                }
            }
        }
        public ActionResult Details(int id)
        {
            ContentType contentType = _contentTypeRepository.Load(id);
            var         model       = new DetailsModel
            {
                ContentType = CreateContentTypeModel(contentType),
                Content     = _contentFinder.List(id).Select(x => new ContentSummaryModel
                {
                    Summary  = x,
                    EditUrls = CreateEditContentUrls(x)
                }).ToList()
            };

            return(View(string.Empty, model));
        }
        public ContentReference UploadPdf(byte[] fileContent, string fileName, ContentFolder parentFolder)
        {
            try
            {
                PdfFile pdfFile;

                var file = TryGetMedia <PdfFile>(fileName, parentFolder);

                if (file != null)
                {
                    pdfFile =
                        _contentRepository.Get <PdfFile>(file).CreateWritableClone() as
                        PdfFile;
                }
                else
                {
                    var fileExtension = Path.GetExtension(fileName);
                    var mediaType     = _contentMediaResolver.GetFirstMatching(fileExtension);
                    var contentType   = _contentTypeRepository.Load(mediaType);

                    var contentReference = GetFolderReference(parentFolder);

                    pdfFile = _contentRepository.GetDefault <PdfFile>(
                        contentReference,
                        contentType.ID);
                    pdfFile.Name = fileName;
                }

                if (pdfFile == null)
                {
                    throw new Exception();
                }

                pdfFile.BinaryData = _blobFactory.CreateBlob(pdfFile.BinaryDataContainer, Path.GetExtension(fileName));
                var stream = new MemoryStream(fileContent);
                pdfFile.BinaryData.Write(stream);

                return(_contentRepository.Save(pdfFile, SaveAction.Publish, AccessLevel.Read));
            }
            catch (Exception e)
            {
                Log.Warn(
                    $"Failed to upload file {fileName} to folder {parentFolder.RouteSegment} id {parentFolder.ContentLink.ID}",
                    e);
            }

            return(null);
        }
Exemplo n.º 28
0
        public CmsqlQueryExecutionResult ExecuteQueries(IEnumerable <CmsqlQuery> queries)
        {
            List <CmsqlQueryExecutionError> errors = new List <CmsqlQueryExecutionError>();
            List <PageData> result = new List <PageData>();

            CmsqlExpressionParser expressionParser = new CmsqlExpressionParser();

            foreach (CmsqlQuery query in queries)
            {
                ContentType contentType = _contentTypeRepository.Load(query.ContentType);
                if (contentType == null)
                {
                    errors.Add(new CmsqlQueryExecutionError($"Couldn't load content-type '{query.ContentType}'."));
                    continue;
                }

                CmsqlExpressionVisitorContext visitorContext = expressionParser.Parse(contentType, query.Criteria);
                if (visitorContext.Errors.Any())
                {
                    errors.AddRange(visitorContext.Errors);
                    continue;
                }

                PageReference searchStartNodeRef = GetStartSearchFromNode(query.StartNode);
                if (PageReference.IsNullOrEmpty(searchStartNodeRef))
                {
                    errors.Add(new CmsqlQueryExecutionError($"Couldn't process start node '{query.StartNode}'."));
                    continue;
                }

                foreach (PropertyCriteriaCollection propertyCriteriaCollection in visitorContext.GetCriteria())
                {
                    PageDataCollection foundPages = _pageCriteriaQueryService.FindPagesWithCriteria(
                        searchStartNodeRef,
                        propertyCriteriaCollection);
                    if (foundPages != null && foundPages.Any())
                    {
                        result.AddRange(foundPages);
                    }
                }
            }

            IEnumerable <ICmsqlQueryResult> pageDataCmsqlQueryResults =
                result.Select(p => new PageDataCmsqlQueryResult(p)).ToList();

            return(new CmsqlQueryExecutionResult(pageDataCmsqlQueryResults, errors));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Builds result search information for IContent
        /// </summary>
        /// <param name="searchHit"></param>
        /// <returns></returns>
        protected virtual SearchResult CreateSearchResult(IHit <IContent> searchHit)
        {
            Validator.ThrowIfNull(nameof(searchHit), searchHit);

            // load the content from the given link
            var referenceString        = (searchHit.Fields["contentLink"] as JArray)?.FirstOrDefault();
            ContentReference reference = null;

            if (referenceString != null)
            {
                ContentReference.TryParse(referenceString.ToString(), out reference);
            }

            if (ContentReference.IsNullOrEmpty(reference))
            {
                throw new Exception("Unable to convert search hit to IContent!");
            }

            var content        = ContentRepository.Get <IContent>(reference);
            var localizable    = content as ILocalizable;
            var changeTracking = content as IChangeTrackable;
            var editUrl        = GetEditUrl(content, out var isOnCurrentHost);
            var result         = new SearchResult
                                 (
                editUrl,
                HttpUtility.HtmlEncode(content.Name),
                CreatePreviewText(content)
                                 )
            {
                Language     = localizable?.Language?.NativeName ?? string.Empty,
                IconCssClass = IconCssClass(content),
                Metadata     =
                {
                    ["Id"]              = content.ContentLink.ToString(),
                    ["LanguageBranch"]  = localizable?.Language?.Name,
                    ["ParentId"]        = content.ParentLink.ToString(),
                    ["TypeIdentifier"]  = content.GetTypeIdentifier(UiDescriptorRegistry),
                    ["IsOnCurrentHost"] = isOnCurrentHost? "true" : "false"
                }
            };

            var contentType = ContentTypeRepository.Load(content.ContentTypeID);

            CreateToolTip(content, changeTracking, result, contentType);

            return(result);
        }
Exemplo n.º 30
0
        private static IContent CreateContent(ContentRequest contentRequest, DivvyTypeMapping mapping)
        {
            // Run the event. The target node might change in here
            var e = new DivvyEventArgs()
            {
                ContentRequest   = contentRequest,
                IntendedParent   = mapping.ParentNode,
                IntendedTypeName = mapping.EpiserverPageTypeName
            };

            OnBeforeContentCreation(null, e);

            if (e.CancelAction)
            {
                return(null);
            }

            var parent = repo.Get <PageData>(e.IntendedParent);

            DivvyLogManager.LogRequest($"Creating New Content", new { Type = e.IntendedTypeName, ParentId = parent.ContentGuid, ParentName = parent.Name });

            try
            {
                // Get the type ID. For whatever reason, we can't create content with a type name, we have to have the ID...
                var type = typeRepo.Load(e.IntendedTypeName);

                // Create the content
                var content = repo.GetDefault <IContent>(e.IntendedParent, type.ID);
                content.Name = contentRequest.Title;
                repo.Save(content, AccessLevel.NoAccess);

                // There's an edge case where we have a mappng already because the Episerver content got deleted
                if (!DivvyContentMapping.HasDivvyMapping(content.ContentLink.ID))
                {
                    DivvyContentMapping.Create(content.ContentLink.ID, contentRequest.Id);
                }

                DivvyLogManager.LogRequest("Created New Content", new { Id = content.ContentGuid });

                return(content);
            }
            catch (Exception ex)
            {
                DivvyLogManager.LogRequest($"Error Creating New Content", ex);
                return(null);
            }
        }