Ejemplo n.º 1
0
        /// <summary>
        /// Returns a new instance of a page with the page name set, or a clone of an existing one, if a page with than name already exists
        /// </summary>
        /// <param name="page"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static T GetOrCreatePageWithName <T>(this PageReference parent, string pageName) where T : BasePageData
        {
            if (parent == null)
            {
                return(null);
            }
            var page = parent.GetChildWithName(pageName);

            if (page != null)
            {
                var clone = (page.CreateWritableClone() as T);
                var assetsFolderForPage = _contentAssetHelper.GetOrCreateAssetFolder(clone.ContentLink);
                var children            = _repo.GetChildren <IContent>(assetsFolderForPage.ContentLink);
                foreach (var child in children)
                {
                    _repo.Delete(child.ContentLink, true, AccessLevel.Read);
                }

                return(clone);
            }
            var newPage = _repo.GetDefault <T>(parent);

            newPage.PageName = pageName;
            return(newPage);
        }
Ejemplo n.º 2
0
        public static ContentReference CreateFolder(this IContentRepository contentRepository, string folderName, ContentReference parentContent)
        {
            var contentFile = contentRepository.GetDefault <ContentFolder>(parentContent);

            contentFile.Name = folderName;
            return(contentRepository.Save(contentFile, SaveAction.Publish, AccessLevel.NoAccess));
        }
Ejemplo n.º 3
0
        public static Guid CreateFileContent(FileInfo assetFile, string parentFolder)
        {
            var catalogRootFolder = GetRootFolderContent(parentFolder);
            var contentType       = _contenttypeRepository.Load(_contentMediaResolver.GetFirstMatching(assetFile.Extension));
            var file = _contentRepository.GetDefault <MediaData>(catalogRootFolder.ContentLink, contentType.ID);

            file.Name = assetFile.Name;
            var        blob = _blobFactory.CreateBlob(file.BinaryDataContainer, assetFile.Extension);
            FileStream fs   = assetFile.OpenRead();

            blob.Write(fs);
            file.BinaryData = blob;
            var content = _contentRepository.Save(file, DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);

            fs.Close();
            return(file.ContentGuid);
        }
Ejemplo n.º 4
0
        private static PageReference CreateOrganisationalUnitFolderPage(IContentRepository contentRepository, ContentReference parent)
        {
            OrganisationalUnitFolderPage defaultPageData = contentRepository.GetDefault <OrganisationalUnitFolderPage>(parent, typeof(OrganisationalUnitFolderPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName   = ORGANISATIONAL_UNIT_FOLDER_NAME;
            defaultPageData.URLSegment = UrlSegment.CreateUrlSegment(defaultPageData);
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Ejemplo n.º 5
0
        public void Save(string typeName, Dictionary <string, int> boosting)
        {
            DeleteBoostingData(typeName);

            foreach (KeyValuePair <string, int> dataPair in boosting)
            {
                Logger.Debug($"Saving boosting for type '{typeName}'. Values: {dataPair.Key + ":" + dataPair.Value}");

                BoostingData dataContent = _contentRepository.GetDefault <BoostingData>(GetBoostingFolder());
                dataContent.Name      = typeName;
                dataContent.FieldName = dataPair.Key;
                dataContent.Weight    = dataPair.Value;
                _contentRepository.Save(dataContent, SaveAction.Publish, AccessLevel.NoAccess);
            }

            CacheManager.Remove(GetCacheKey(typeName));
        }
        private ContentReference CreateStart(ContentReference rootReference)
        {
            IContent startContent = _contentRepository.GetBySegment(rootReference, "test-content",
                                                                    CultureInfo.GetCultureInfo("en"));

            if (startContent == null)
            {
                var startPage = _contentRepository.GetDefault <StartPage>(rootReference);

                var faker = new StartPageFaker("QA Start Page", "test-content");
                faker.Populate(startPage);

                return(_contentRepository.Save(startPage, SaveAction.Publish, AccessLevel.NoAccess));
            }

            return(startContent.ContentLink);
        }
        private int CreateLetterContainer(string letter)
        {
            var newPage = _contentRepository.GetDefault <ContainerPage>(EmployeeContainerRootPage);

            newPage.Name = letter;
            _contentRepository.Save(newPage, EPiServer.DataAccess.SaveAction.Publish);

            return(newPage.ContentLink.ID);
        }
Ejemplo n.º 8
0
        private void CreateArticle(DataRow row, ContentReference parent)
        {
            var html = row["content_html"].ToString();

            var parser = new XmlParser(html);

            var myPage = _contentRepository.GetDefault <ArticlePage>(parent, _articleTypeId);

            myPage.Name       = row["content_title"].ToString();
            myPage.PageTitle  = row["content_title"].ToString();
            myPage.SubTitle   = parser.ParseString("/root/SubTitle");
            myPage.Intro      = parser.ParseXHtmlString("/root/Introduction");
            myPage.MainBody   = parser.ParseXHtmlString("/root/Article");
            myPage.URLSegment = EPiServer.Web.UrlSegment.CreateUrlSegment(myPage);
            myPage.Summary    = StripHtml(row["content_teaser"].ToString());

            _contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
        }
        public PageData createPage(IContentRepository contentRepository, string IDofPageParent, string PageName)
        {
            PageData myPage = contentRepository.GetDefault <ContainerPage>(ContentReference.Parse(IDofPageParent));

            myPage.Name = PageName;

            contentRepository.Save(myPage, SaveAction.Publish, AccessLevel.NoAccess);
            return(myPage);
        }
Ejemplo n.º 10
0
        private PageReference CreateDatePage(IContentRepository contentRepository, ContentReference parent, string name, DateTime startPublish)
        {
            BlogListPage defaultPageData = contentRepository.GetDefault <BlogListPage>(parent, typeof(BlogListPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName     = name;
            defaultPageData.Heading      = name;
            defaultPageData.StartPublish = startPublish;
            defaultPageData.URLSegment   = UrlSegment.CreateUrlSegment(defaultPageData);
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Ejemplo n.º 11
0
        private static PageReference CreateOrganisationalUnitFolderPage(IContentRepository contentRepository, ContentReference parent)
        {
            OrganisationalUnitFolderPage defaultPageData = contentRepository.GetDefault <OrganisationalUnitFolderPage>(parent, typeof(OrganisationalUnitFolderPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName        = ORGANISATIONAL_UNIT_FOLDER_NAME;
            defaultPageData.URLSegment      = UrlSegment.CreateUrlSegment(defaultPageData);
            defaultPageData.MenuDescription = "Containing all the organisational units for the compare service";
            defaultPageData.MenuTitle       = "Organisational units for the compare service";
            defaultPageData.VisibleInMenu   = false;
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Import button click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImportButton_Click(object sender, EventArgs e)
        {
            // Clear index
            _client.Delete <object>(x => x.GetType().Name.Exists() | !x.GetType().Name.Exists());

            //Remove pages first
            _contentRepository.DeleteChildren(ContentReference.StartPage, true, AccessLevel.Publish);

            var articlesPage = _contentRepository.GetDefault <ArticlesPage>(ContentReference.StartPage);

            articlesPage.PageName = "Articles";
            _contentRepository.Save(articlesPage, SaveAction.Publish);

            // Import article pages
            var numberOfArticles = ImportArticles(articlesPage.ContentLink.ID);

            var numberOfCompanies = ImportCompanies();

            ImportResult.Text = string.Format("{0} article imported, {1} companies imported", numberOfArticles, numberOfCompanies);
        }
        public void AddSkill(ContentReference skillFolderReference, string skill)
        {
            AddedSkill newSkillBlock = _contentRepository.GetDefault <AddedSkill>(skillFolderReference);

            newSkillBlock.Skill = skill;

            IContent newSkillBlockInstance = newSkillBlock as IContent;

            newSkillBlockInstance.Name = skill;

            _contentRepository.Save(newSkillBlockInstance, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.FullAccess);
        }
Ejemplo n.º 14
0
        private PageReference CreateDatePage(IContentRepository contentRepository, ContentReference parent, string name, DateTime startPublish)
        {
            BlogListPage defaultPageData = contentRepository.GetDefault <BlogListPage>(parent, typeof(BlogListPage).GetPageType().ID);

            defaultPageData.PageName     = name;
            defaultPageData.Heading      = name;
            defaultPageData.StartPublish = startPublish;
            IUrlSegmentCreator urlSegment = ServiceLocator.Current.GetInstance <IUrlSegmentCreator>();

            defaultPageData.URLSegment = urlSegment.Create(defaultPageData);
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Ejemplo n.º 15
0
        private PageReference CreatePageFromJson(PageObject pageObject, PageReference parent, IContentRepository contentRepo)
        {
            BasePage newPage;
            switch (pageObject.Type)
            {
                case 0:
                    ArticlePage aPage = contentRepo.GetDefault<ArticlePage>(parent);
                    aPage.MainBody = pageObject.MainBodyText;
                    newPage = aPage;
                    break;
                case 1:
                    newPage = contentRepo.GetDefault<FolderPage>(parent);
                    break;
                case 2:
                    ListPage lPage = contentRepo.GetDefault<ListPage>(parent);
                    lPage.MainBody = pageObject.MainBodyText;
                    newPage = lPage;
                    break;
                case 3:
                    newPage = contentRepo.GetDefault<PersonPage>(parent);
                    break;
                case 4:
                    newPage = contentRepo.GetDefault<PortalPage>(parent);
                    break;
                default:
                    newPage = contentRepo.GetDefault<ArticlePage>(parent);
                    break;
            }

            newPage.PageName = pageObject.PageName;
            newPage.IntroText = pageObject.IntroText;
            contentRepo.Save(newPage, SaveAction.Publish);
            return newPage.PageLink;
        }
Ejemplo n.º 16
0
        private ImageFile GetOrCreateFile(string fileName, ContentReference parentReference)
        {
            var fileContent = _contentRepository.GetChildren <IContent>(parentReference)?.Where(x => x.Name == fileName).FirstOrDefault();

            if (fileContent != null)
            {
                return(_contentRepository.Get <ImageFile>(fileContent.ContentLink).CreateWritableClone() as ImageFile);
            }

            var file = _contentRepository.GetDefault <ImageFile>(parentReference);

            return(file);
        }
Ejemplo n.º 17
0
        private static StaticAssetsRootFolder EnsureAssetsFolder(IContentRepository contentRepository)
        {
            var assetsFolder = contentRepository.GetChildren <StaticAssetsRootFolder>(ContentReference.RootPage).FirstOrDefault();

            if (assetsFolder == null)
            {
                assetsFolder      = contentRepository.GetDefault <StaticAssetsRootFolder>(ContentReference.RootPage);
                assetsFolder.Name = "Static Assets";
                contentRepository.Save(assetsFolder, AccessLevel.NoAccess);
            }

            return(assetsFolder);
        }
Ejemplo n.º 18
0
        public Task <string> SaveAsync(Stream fileStream, string extension, string fileGroups, string owner)
        {
            if (string.IsNullOrWhiteSpace(fileGroups))
            {
                throw new ArgumentNullException(nameof(fileGroups));
            }
            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new ArgumentNullException(nameof(extension));
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            var fileGroupArray = fileGroups.Split('/').Where(n => !string.IsNullOrWhiteSpace(n));
            var groupArray     = fileGroupArray as string[] ?? fileGroupArray.ToArray();
            var groupFolder    = GetGroupFolder(groupArray);

            //Get a suitable MediaData type from extension
            var mediaType   = _mediaResolver.GetFirstMatching(extension);
            var contentType = _contentTypeRepo.Load(mediaType);
            var mediaData   = _contentRepo.GetDefault <MediaData>(groupFolder.ContentLink, contentType.ID);

            var fileName = $"{DateTime.Now.Ticks}_{Guid.NewGuid().ToString()}{extension}";

            mediaData.Name      = fileName;
            mediaData.CreatedBy = owner;

            //Create a blob in the binary container
            var blob = _blobFactory.CreateBlob(mediaData.BinaryDataContainer, extension);

            blob.Write(fileStream);

            //Assign to file and publish changes
            mediaData.BinaryData = blob;
            _contentRepo.Save(mediaData, SaveAction.Publish, AccessLevel.NoAccess);
            return(Task.FromResult($"/globalassets/{string.Join("/", groupArray)}/{fileName}"));
        }
        /// <summary>
        /// Creates a new block of type T, and saves it to the ContentReference's assets folder
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parentPageReference"></param>
        /// <param name="newBlockName"></param>
        /// <returns></returns>
        public static T CreateGenericBlockForPage <T>(this ContentReference parentPageReference, string newBlockName) where T : BaseBlockData
        {
            if (parentPageReference.IsNullOrEmpty())
            {
                return(null);
            }
            var assetsFolderForPage = _contentAssetHelper.GetOrCreateAssetFolder(parentPageReference);
            var blockInstance       = _repo.GetDefault <T>(assetsFolderForPage.ContentLink);
            var blockForPage        = blockInstance as IContent;

            blockForPage.Name = newBlockName;
            return(blockInstance);
        }
        public static ContentReference Ensure(IContentRepository repository)
        {
            var entryPoint = repository.GetChildren <StyleguideContentEntryPoint>(ContentReference.RootPage).SingleOrDefault();

            if (entryPoint == null)
            {
                entryPoint      = repository.GetDefault <StyleguideContentEntryPoint>(ContentReference.RootPage);
                entryPoint.Name = "Styleguide Content";
                repository.Save(entryPoint, global::EPiServer.DataAccess.SaveAction.Publish, global::EPiServer.Security.AccessLevel.NoAccess);
            }

            return(entryPoint.ContentLink);
        }
        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);
        }
        public void AddComment(ContentReference commentFolderReference, string name, string text, DateTime date)
        {
            PostedComment newCommentBlock = _contentRepository.GetDefault <PostedComment>(commentFolderReference);

            newCommentBlock.Text            = text;
            newCommentBlock.Date            = date;
            newCommentBlock.CommentatorName = name;
            IContent newCommentBlockInstance = newCommentBlock as IContent;

            newCommentBlockInstance.Name = name;

            _contentRepository.Save(newCommentBlockInstance, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.Publish);
        }
Ejemplo n.º 23
0
        public ContentReference CreateOrGetFolder(ContentReference parent, string folderName)
        {
            ContentFolder existingFolder = _contentRepo.GetChildren <ContentFolder>(parent).FirstOrDefault(x => x.Name == folderName);

            if (existingFolder != null)
            {
                return(existingFolder.ContentLink);
            }

            var newFolder = _contentRepo.GetDefault <ContentFolder>(parent);

            newFolder.Name = folderName;
            return(_contentRepo.Save(newFolder, SaveAction.Save, AccessLevel.NoAccess));
        }
        public override string Execute()
        {
            int shippersImported = 0;

            OnStatusChanged(
                "Starting execution of 'Import Shippers' job.");

            var startPage = repo.Get <StartPage>(ContentReference.StartPage);

            var existingShippers = repo.GetChildren <ShipperPage>(startPage.Shippers);

            var existingIDs = existingShippers.Select(s => s.ShipperID).ToArray();

            var db = new Northwind();

            var shippers = db.Shippers
                           .Where(s => !existingIDs.Contains(s.ShipperID));

            foreach (Shipper item in shippers)
            {
                var newshipper = repo.GetDefault <ShipperPage>(startPage.Shippers);

                newshipper.Name        = item.CompanyName;
                newshipper.ShipperID   = item.ShipperID;
                newshipper.CompanyName = item.CompanyName;
                newshipper.Phone       = item.Phone;

                repo.Save(newshipper,
                          EPiServer.DataAccess.SaveAction.Publish,
                          EPiServer.Security.AccessLevel.NoAccess);

                shippersImported++;

                if (_stopSignaled)
                {
                    return("'Import Shippers' job was stopped.");
                }
            }

            if (shippersImported == 0)
            {
                return("No new shippers to import.");
            }
            else
            {
                return(string.Format(
                           "Successfully imported {0} shippers.",
                           shippersImported));
            }
        }
Ejemplo n.º 25
0
        public ContentReference GetOrCreateCatelog(string catalogName)
        {
            var root = _referenceConverter.GetRootLink();

            var catalogs = _contentRepository.GetChildren <CatalogContent>(root);
            var catalog  = catalogs?.Where(x => x.Name == catalogName).FirstOrDefault();

            if (catalog != null)
            {
                return(catalog.ContentLink);
            }

            var newCatalog = _contentRepository.GetDefault <CatalogContent>(root);

            newCatalog.Name            = catalogName;
            newCatalog.DefaultCurrency = "USD";
            newCatalog.DefaultLanguage = "en";
            newCatalog.WeightBase      = "kgs";
            newCatalog.LengthBase      = "cm";
            var contentReference = _contentRepository.Save(newCatalog, SaveAction.Publish, AccessLevel.NoAccess);

            return(contentReference);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// This method is used to seed the content for the Reseller Community Pages.
        /// </summary>
        /// <param name="contentRepository"></param>
        /// <param name="urlSegmentCreator"></param>
        private void ResellerCommunitySeeding(IContentRepository contentRepository, IUrlSegmentCreator urlSegmentCreator)
        {
            //Checking to see if the reseller title page already exists. If no reseller title page can be found a new one will be created on application start.
            var resellerTitlePage = contentRepository.GetBySegment(PageReference.StartPage, "reseller-community", CultureInfo.CurrentCulture);

            if (resellerTitlePage == null)
            {
                StandardPage communityPage = contentRepository.GetDefault <StandardPage>(PageReference.StartPage);
                communityPage.PageName      = "Reseller Community";
                communityPage.URLSegment    = urlSegmentCreator.Create(communityPage);
                communityPage.MainBody      = new XhtmlString("<p>This is the homepage for all reseller community pages.</p>");
                communityPage.VisibleInMenu = true;
                contentRepository.Save(communityPage, EPiServer.DataAccess.SaveAction.Publish, AccessLevel.NoAccess);
            }

            resellerTitlePage = contentRepository.GetBySegment(PageReference.StartPage, "reseller-community", CultureInfo.CurrentCulture);
            //If the title reseller page exists there is a check if there are any child pages. If no child pages exist then create example reseller pages.
            if (resellerTitlePage != null)
            {
                var parentReference           = resellerTitlePage.ContentLink;
                var resellerTitlePageChildren = contentRepository.GetChildren <CommunityPage>(parentReference);
                if (resellerTitlePageChildren != null && resellerTitlePageChildren.Any() != true)
                {
                    var listOfGroups = new List <string> {
                        "Platinum Reseller Group", "Gold Reseller Group", "Silver Reseller Group"
                    };
                    foreach (var group in listOfGroups)
                    {
                        CommunityPage resellerGroupPage = contentRepository.GetDefault <CommunityPage>(parentReference);
                        resellerGroupPage.PageName      = group;
                        resellerGroupPage.URLSegment    = urlSegmentCreator.Create(resellerGroupPage);
                        resellerGroupPage.VisibleInMenu = true;
                        contentRepository.Save(resellerGroupPage, EPiServer.DataAccess.SaveAction.Publish, AccessLevel.NoAccess);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public override string Execute()
        {
            string toImportFolder = WebConfigurationManager.AppSettings["episerver:edu.ToImportFolder"];
            string importedFolder = WebConfigurationManager.AppSettings["episerver:edu.ImportedFolder"];

            var assetsFolder = new ContentReference(
                WebConfigurationManager.AppSettings["episerver:edu.ImportAssetsFolder"]);

            IEnumerable <string> images = GetImageFilenames(toImportFolder);
            int toImportCount           = images.Count();
            int importedCount           = 0;
            int remainingCount          = toImportCount;

            OnStatusChanged($"Starting {ScheduledJobName}. {toImportCount} images to import. Please wait...");

            while (remainingCount > 0)
            {
                if (_stopSignaled)
                {
                    return("Stop of job was called");
                }

                string nextImage = images.First();

                var asset = contentRepository.GetDefault <ImageFile>(parentLink: assetsFolder);
                asset.Name      = Path.GetFileName(nextImage);
                asset.Copyright = $"Copyright © 2018 Episerver Education";

                Blob blob = blobFactory.CreateBlob(id: asset.BinaryDataContainer,
                                                   extension: Path.GetExtension(nextImage));
                blob.WriteAllBytes(File.ReadAllBytes(nextImage));
                asset.BinaryData = blob;

                contentRepository.Save(asset, SaveAction.Publish, AccessLevel.NoAccess);

                File.Move(nextImage, Path.Combine(
                              importedFolder, Path.GetFileName(nextImage)));

                Thread.Sleep(2500); // slow it down
                importedCount++;

                OnStatusChanged($"Imported {importedCount} of {toImportCount} images. Please wait...");

                images         = GetImageFilenames(toImportFolder);
                remainingCount = images.Count();
            }

            return($"Successfully imported {importedCount} images.");
        }
Ejemplo n.º 28
0
        public void AddHeader(ContentReference headerFolderReference, string pic, string fullname, string address, string headline, string business, string summary)
        {
            AddedHeader newHeaderBlock = _contentRepository.GetDefault <AddedHeader>(headerFolderReference);

            newHeaderBlock.PersonImage    = pic;
            newHeaderBlock.FullName       = fullname;
            newHeaderBlock.Headline       = headline;
            newHeaderBlock.Address        = address;
            newHeaderBlock.LineOfBusiness = business;
            newHeaderBlock.Summary        = summary;
            IContent newHeaderBlockInstance = newHeaderBlock as IContent;

            newHeaderBlockInstance.Name = fullname;
            _contentRepository.Save(newHeaderBlockInstance, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.Publish);
        }
Ejemplo n.º 29
0
        public Comment CreateAComment()
        {
            var comment = _contentRepository.GetDefault <Comment>(PageReference.RootPage, LanguageSelector.AutoDetect().Language);

            comment.Name       = "acomment";
            comment.User.Email = "*****@*****.**";
            comment.Body       = "This is a comment";

            var contentLink   = _contentRepository.Save(comment, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
            var loadedComment = _contentRepository.Get <Comment>(contentLink);

            System.Diagnostics.Debug.Assert(comment.User.Email == loadedComment.User.Email);
            System.Diagnostics.Debug.Assert(comment.Body == loadedComment.Body);

            return(comment);
        }
        /// <summary>
        /// Downloads an image from the url and saves to parents assets folder
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="url"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public static ImageFile DownloadImage(ContentReference parent, string url, string title)
        {
            var imageFile = Repo.GetDefault <ImageFile>(ContentAssetHelper.GetOrCreateAssetFolder(parent).ContentLink);

            imageFile.Name = $"image-{title}";
            var blob = ImageDownloaderHelper.DownloadImageBlob(url);

            if (blob != null)
            {
                imageFile.BinaryData = blob;
                Repo.Save(imageFile, SaveAction.Publish);
                return(imageFile);
            }

            return(null);
        }
Ejemplo n.º 31
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);
            }
        }
Ejemplo n.º 32
0
        private void ImportLocations(IFileDataImporter fileImporter, IContentRepository contentRepo, EmployeeContainerLookup lookup)
        {
            string[] allLocations = fileImporter.RetrieveAllData(_locationDataFile);
            ContentReference locationRoot = lookup.EmployeeLocationRootPage;
            foreach (string location in allLocations)
            {
                EmployeeLocationPage locationPage = lookup.GetExistingPage<EmployeeLocationPage>(locationRoot, location);
                if (locationPage == null)
                {
                    locationPage = contentRepo.GetDefault<EmployeeLocationPage>(locationRoot);
                    locationPage.Name = location;

                    contentRepo.Save(locationPage, EPiServer.DataAccess.SaveAction.Publish);

                    //For long running jobs periodically check if stop is signaled and if so stop execution
                    if (_stopSignaled)
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 33
0
 private PageReference CreateDatePage(IContentRepository contentRepository, ContentReference parent, string name, DateTime startPublish)
 {
     BlogListPage defaultPageData = contentRepository.GetDefault<BlogListPage>(parent, typeof(BlogListPage).GetPageType().ID);
     defaultPageData.PageName = name;
     defaultPageData.Heading = name;
     defaultPageData.StartPublish = startPublish;
     defaultPageData.URLSegment = UrlSegment.CreateUrlSegment(defaultPageData);
     return contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference();
 }
Ejemplo n.º 34
0
        private void ImportExpertise(IFileDataImporter fileImporter, IContentRepository contentRepo, EmployeeContainerLookup lookup)
        {
            string[] allExpertise = fileImporter.RetrieveAllData(_expertiseDataFile);
            ContentReference expertiseRoot = lookup.EmployeeSpecialityRootPage;
            foreach (string expertise in allExpertise)
            {
                EmployeeExpertise expertisePage = lookup.GetExistingPage<EmployeeExpertise>(expertiseRoot, expertise);
                if (expertisePage == null)
                {
                    expertisePage = contentRepo.GetDefault<EmployeeExpertise>(expertiseRoot);
                    expertisePage.Name = expertise;

                    contentRepo.Save(expertisePage, EPiServer.DataAccess.SaveAction.Publish);

                    //For long running jobs periodically check if stop is signaled and if so stop execution
                    if (_stopSignaled)
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 35
0
        private void ImportEmployees(IFileDataImporter fileImporter, IContentRepository contentRepo, EmployeeContainerLookup lookup)
        {
            string[] allEmployees = fileImporter.RetrieveAllData(_employeeDataFile);

            foreach (string employeeRow in allEmployees)
            {

                string[] fields = fileImporter.SplitByDelimiter(employeeRow, TabDelimiter);
                if (!string.IsNullOrWhiteSpace(fields[2]))
                {
                    string firstLetter = fields[2].Substring(0, 1).ToUpper();
                    string pageName = string.Format("{0}, {1}", fields[2], fields[1]);

                    int pageReference = lookup.GetIndex(firstLetter);

                    ContentReference startingFolder = new ContentReference(pageReference);

                    EmployeePage page = lookup.GetExistingPage<EmployeePage>(startingFolder, pageName);

                    if (page != null)
                    {
                        page = page.CreateWritableClone() as EmployeePage;
                    }
                    else
                    {
                        page = contentRepo.GetDefault<EmployeePage>(startingFolder);
                    }

                    MapFields(fields, page);
                    page.Name = pageName;
                    

                    contentRepo.Save(page, EPiServer.DataAccess.SaveAction.Publish);
                }
                //For long running jobs periodically check if stop is signaled and if so stop execution
                if (_stopSignaled)
                {
                    break;
                }
            }
        }