private void SaveBackup(string languageId, string index, string[] synonymPairs)
        {
            var name = GetFilename(languageId, index);
            SynonymBackupFile contentFile = GetBackup(name);

            //TODO: Don't create new version for identical files.

            contentFile = contentFile == null
                ? _contentRepository.GetDefault <SynonymBackupFile>(GetBackupFolder().ContentLink)
                : contentFile.CreateWritableClone() as SynonymBackupFile;

            var content = String.Join("|", synonymPairs);

            var blob = _blobFactory.CreateBlob(contentFile.BinaryDataContainer, ".synonyms");

            using (var stream = blob.OpenWrite())
            {
                var writer = new StreamWriter(stream);
                writer.Write(content);
                writer.Flush();
            }
            contentFile.Name       = name;
            contentFile.BinaryData = blob;

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

            if (_logger.IsDebugEnabled())
            {
                _logger.Debug("SaveBackup -> Name: " + contentFile.Name);
                _logger.Debug("SaveBackup -> RouteSegment: " + contentFile.RouteSegment);
                _logger.Debug("SaveBackup -> MimeType: " + contentFile.MimeType);
                _logger.Debug("SaveBackup -> ContentLink: " + contentFile.ContentLink);
                _logger.Debug("SaveBackup -> Status: " + contentFile.Status);
            }
        }
        private void SetWords(string languageId, IEnumerable <string> wordsToAdd)
        {
            var             name        = GetFilename(languageId);
            AutoSuggestFile contentFile = GetAutoSuggest(name);

            contentFile = contentFile == null
                ? _contentRepository.GetDefault <AutoSuggestFile>(GetAutoSuggestFolder().ContentLink)
                : contentFile.CreateWritableClone() as AutoSuggestFile;

            if (contentFile == null)
            {
                return;
            }

            string content = String.Join("|", wordsToAdd);

            var blob = _blobFactory.CreateBlob(contentFile.BinaryDataContainer, ".autosuggest");

            using (var stream = blob.OpenWrite())
            {
                var writer = new StreamWriter(stream);
                writer.Write(content);
                writer.Flush();
            }
            contentFile.Name       = name;
            contentFile.BinaryData = blob;
            contentFile.LanguageId = languageId;

            var suggestRef = _contentRepository.Save(contentFile, SaveAction.Publish, AccessLevel.NoAccess);

            DeleteabAndonedDocuments(suggestRef, name, languageId);
        }
Ejemplo n.º 3
0
        public async Task <Content> Create([FromBody] Content content)
        {
            content.Id = Guid.NewGuid();
            await _contentRepository.Save(content);

            return(content);
        }
        public ContentReference InsertMediaByUrl <T>(ContentReference pageToStore, string fileName, string url, string imageExtension) where T : MediaData
        {
            if (
                ContentReference.IsNullOrEmpty(pageToStore) ||
                string.IsNullOrEmpty(url) ||
                string.IsNullOrEmpty(imageExtension))
            {
                return(null);
            }

            var newImage = _contentRepository.GetDefault <T>(pageToStore);
            var blob     = _blobFactory.CreateBlob(newImage.BinaryDataContainer, imageExtension);

            byte[] data;

            using (var webClient = new WebClient())
            {
                data = webClient.DownloadData(url);
            }

            using (var s = blob.OpenWrite())
            {
                var w = new StreamWriter(s);
                w.BaseStream.Write(data, 0, data.Length);
                w.Flush();
            }

            newImage.Name       = fileName;
            newImage.BinaryData = blob;
            return(_contentRepository.Save(newImage, SaveAction.Publish, AccessLevel.NoAccess));
        }
        public void Dump()
        {
            var languageBranch = _languageBranchRepository.ListAll().First();

            var currentMarket = _currentMarket.GetCurrentMarket();
            var market        = (MarketImpl)_marketService.GetMarket(currentMarket.MarketId);

            market.DefaultCurrency = Currency.EUR;
            market.DefaultLanguage = languageBranch.Culture;
            _marketService.UpdateMarket(market);

            var rootLink = _referenceConverter.GetRootLink();
            var catalog  = _contentRepository.GetDefault <CatalogContent>(rootLink, languageBranch.Culture);

            catalog.Name             = "Catalog";
            catalog.DefaultCurrency  = market.DefaultCurrency;
            catalog.CatalogLanguages = new ItemCollection <string> {
                languageBranch.LanguageID
            };
            catalog.DefaultLanguage = "en";
            catalog.WeightBase      = "kg";
            catalog.LengthBase      = "cm";
            var catalogRef = _contentRepository.Save(catalog, SaveAction.Publish, AccessLevel.NoAccess);

            var category = _contentRepository.GetDefault <NodeContent>(catalogRef);

            category.Name        = "Category";
            category.DisplayName = "Category";
            category.Code        = "category";
            var categoryRef = _contentRepository.Save(category, SaveAction.Publish, AccessLevel.NoAccess);

            var product = _contentRepository.GetDefault <ProductContent>(categoryRef);

            product.Name        = "Product";
            product.DisplayName = "Product";
            product.Code        = "product";
            var productRef = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var variant = _contentRepository.GetDefault <VariationContent>(productRef);

            variant.Name        = "Variant";
            variant.DisplayName = "Variant";
            variant.Code        = "test";
            variant.MinQuantity = 1;
            variant.MaxQuantity = 100;
            _contentRepository.Save(variant, SaveAction.Publish, AccessLevel.NoAccess);

            var price = new PriceValue
            {
                UnitPrice       = new Money(100, market.DefaultCurrency),
                CatalogKey      = new CatalogKey(variant.Code),
                MarketId        = market.MarketId,
                ValidFrom       = DateTime.Today.AddYears(-1),
                ValidUntil      = DateTime.Today.AddYears(1),
                CustomerPricing = CustomerPricing.AllCustomers,
                MinQuantity     = 0
            };

            _priceService.SetCatalogEntryPrices(price.CatalogKey, new[] { price });
        }
Ejemplo n.º 6
0
        // This method saves the content in accordance with the save action selected by the user for the item.
        private SaveAction SaveContent(IContent content, IGcItem item, GcDynamicTemplateMappings currentMapping)
        {
            /*
             *  <summary>
             *      Select the status/SaveAction from the mapping where first part of the 'MappedEpiServerStatus'
             *      matches the current Gc status ID. If the 'MappedEpiServerStatus' is set to 'Use Default Status',
             *      then fetch the SaveAction that matches the 'DefaultStatus' string from the mapping and select it.
             *      Else, fetch the SaveAction that matches the 'statusFromMapping' string and select it.
             *  </summary>
             */
            var        gcStatusIdForThisItem = item.CurrentStatus.Data.Id;
            SaveAction saveAction;

            var statusFromMapping = currentMapping.StatusMaps
                                    .Find(i => i.MappedEpiserverStatus.Split('~')[1] == gcStatusIdForThisItem)
                                    .MappedEpiserverStatus.Split('~')[0];

            if (statusFromMapping == "Use Default Status")
            {
                saveAction = _saveActions.Find(i => i.ToString() == currentMapping.DefaultStatus);
                _contentRepository.Save(content, saveAction, AccessLevel.Administer);
            }

            else
            {
                saveAction = _saveActions.Find(i => i.ToString() == statusFromMapping);
                _contentRepository.Save(content, saveAction, AccessLevel.Administer);
            }

            return(saveAction);
        }
Ejemplo n.º 7
0
        public ActionResult CreateDefaultEntry(FashionNode currentContent, NewBlouseObject model)
        {
            var parentReference = _referenceConverter.GetContentLink(model.Code);

            var product = _contentRepository.GetDefault <BlouseProduct>(parentReference);

            product.Name = model.NewName;
            product.Code = model.NewCode;

            var productContentReference = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var sizes = model.Sizes.Split(';');

            foreach (var size in sizes)
            {
                var sku = _contentRepository.GetDefault <ShirtVariation>(productContentReference);
                sku.Name  = $"{model.NewName} {model.Color} {size}";
                sku.Code  = $"{model.NewCode}{model.Color}{size}";
                sku.Color = model.Color;
                sku.Size  = size;
                _contentRepository.Save(sku, SaveAction.Publish, AccessLevel.NoAccess);
            }


            return(new RedirectResult(GetUrl(currentContent.ContentLink)));
        }
        public ActionResult InputData([FromBody] ClickerModel model)
        {
            if (model != null && model is ClickerModel)
            {
                var clickerPage = contentRepository.GetChildren <ClickerPage>(ContentReference.StartPage).FirstOrDefault();
                if (clickerPage == null)
                {
                    clickerPage         = contentRepository.GetDefault <ClickerPage>(ContentReference.StartPage);
                    clickerPage.DataSet = new List <ContentReference>();
                    clickerPage.Name    = "clicker num" + (new Random().Next());
                    contentRepository.Save(clickerPage, SaveAction.Publish, AccessLevel.NoAccess);
                }

                var modelPage = contentRepository.GetDefault <StupidClickerModel>(clickerPage.ContentLink);
                modelPage.UpdateStupid(model);

                modelPage.Name = "model num" + (new Random().Next());
                contentRepository.Save(modelPage, SaveAction.Publish, AccessLevel.NoAccess);


                return(new JsonDataResult()
                {
                    ContentType = "application/json",
                    Data = true,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
            return(new JsonDataResult()
            {
                ContentType = "application/json",
                Data = false,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Ejemplo n.º 9
0
        private async Task ApproveContent(string values, string approvalComment)
        {
            if (!string.IsNullOrEmpty(values))
            {
                var ids = values.Split(',');
                foreach (var id in ids)
                {
                    int.TryParse(id, out var approvalId);
                    if (approvalId != 0)
                    {
                        var approval = await _approvalRepository.GetAsync(approvalId);

                        await _approvalEngine.ForceApproveAsync(approvalId, PrincipalInfo.CurrentPrincipal.Identity.Name, approvalComment);

                        if (approval is ContentApproval contentApproval)
                        {
                            _contentRepository.TryGet(contentApproval.ContentLink, out IContent content);

                            var canUserPublish = await _helper.CanUserPublish(content);

                            if (content != null && canUserPublish)
                            {
                                switch (content)
                                {
                                case PageData page:
                                {
                                    var clone = page.CreateWritableClone();
                                    _contentRepository.Save(clone, SaveAction.Publish, AccessLevel.Publish);
                                    break;
                                }

                                case BlockData block:
                                {
                                    var clone = block.CreateWritableClone() as IContent;
                                    _contentRepository.Save(clone, SaveAction.Publish, AccessLevel.Publish);
                                    break;
                                }

                                case ImageData image:
                                {
                                    var clone = image.CreateWritableClone() as IContent;
                                    _contentRepository.Save(clone, SaveAction.Publish, AccessLevel.Publish);
                                    break;
                                }

                                case MediaData media:
                                {
                                    var clone = media.CreateWritableClone() as IContent;
                                    _contentRepository.Save(clone, SaveAction.Publish, AccessLevel.Publish);
                                    break;
                                }
                                }
                            }
                        }
                    }
                }
            }
        }
        public virtual IHttpActionResult PublishContent(string Reference)
        {
            var r = LookupRef(Reference);

            if (r == ContentReference.EmptyReference)
            {
                return(NotFound());
            }
            _repo.Save(_repo.Get <IContent>(r), EPiServer.DataAccess.SaveAction.Publish);
            return(Ok());
        }
Ejemplo n.º 11
0
        private void CreateVariations(ContentReference parentLink, int numberOfVariation)
        {
            for (int i = 0; i < numberOfVariation; i++)
            {
                var content = _contentRepository.GetDefault <FashionVariant>(parentLink);
                content.Code = parentLink + rnd.Next(1, 1000).ToString() + "ItemContentCode" + i;
                content.Name = "FashionItemContent new- index" + i;
                var contentRef = _contentRepository.Save(content, SaveAction.Publish, AccessLevel.NoAccess);

                AddInventory(content.Code, 10);
                AddPrice(content.Code, rnd.Next(30, 99));
            }
        }
Ejemplo n.º 12
0
        public ActionResult CreateContent(Treeview.Models.Content content)
        {
            using (var ctx = new CosmicVerseEntities1())
            {
                Content cont = new Content();
                cont.Title = content.ContentTitle;
                cont.Body  = content.ContentBody;

                contentRepository.InsertContent(cont);
                contentRepository.Save();
            }
            return(RedirectToAction("Index"));
        }
        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.º 14
0
 public ActionResult Create(Content content)
 {
     if (ModelState.IsValid)
     {
         contentRepository.InsertOrUpdate(content);
         contentRepository.Save();
         return(RedirectToAction("Index"));
     }
     else
     {
         ViewBag.PossibleCategories = categoryRepository.All;
         return(View());
     }
 }
Ejemplo n.º 15
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;
            //}
        }
Ejemplo n.º 16
0
        private void AddLinksFromMediaToCodes(IContent contentMedia, IEnumerable <EntryCode> codes)
        {
            var media = new CommerceMedia {
                AssetLink = contentMedia.ContentLink, GroupName = "default", AssetType = "episerver.core.icontentmedia"
            };

            foreach (EntryCode entryCode in codes)
            {
                ContentReference contentReference = _referenceConverter.GetContentLink(entryCode.Code);

                IAssetContainer writableContent = null;
                if (_contentRepository.TryGet(contentReference, out EntryContentBase entry))
                {
                    writableContent = (EntryContentBase)entry.CreateWritableClone();
                }

                if (_contentRepository.TryGet(contentReference, out NodeContent node))
                {
                    writableContent = (NodeContent)node.CreateWritableClone();
                }

                if (writableContent == null)
                {
                    _logger.Error($"Can't get a suitable content (with code {entryCode.Code} to add CommerceMedia to, meaning it's neither EntryContentBase nor NodeContent.");
                    continue;
                }

                CommerceMedia existingMedia = writableContent.CommerceMediaCollection.FirstOrDefault(x => x.AssetLink.Equals(media.AssetLink));
                if (existingMedia != null)
                {
                    writableContent.CommerceMediaCollection.Remove(existingMedia);
                }

                if (entryCode.IsMainPicture)
                {
                    _logger.Debug($"Setting '{contentMedia.Name}' as main media on {entryCode.Code}");
                    media.SortOrder = 0;
                    writableContent.CommerceMediaCollection.Insert(0, media);
                }
                else
                {
                    _logger.Debug($"Adding '{contentMedia.Name}' as media on {entryCode.Code}");
                    media.SortOrder = 1;
                    writableContent.CommerceMediaCollection.Add(media);
                }

                _contentRepository.Save((IContent)writableContent, SaveAction.Publish, AccessLevel.NoAccess);
            }
        }
        PageReference CreateYearContainer(string pageName, PageReference parent)
        {
            var existingContainerPage = GetContainerPageByName(pageName, parent);

            if (existingContainerPage == null)
            {
                var parentContentReference = _contentRepository.Get <PageData>(parent);
                var containerPage          = _contentRepository.GetDefault <ContainerPageType>(parentContentReference.ContentLink);
                containerPage.Name = pageName;
                _contentRepository.Save(containerPage, SaveAction.Publish, AccessLevel.NoAccess);
                _logger.Information($"Creating year container for year: {pageName}");
                return(containerPage.ContentLink.ToPageReference());
            }
            return(existingContainerPage.ContentLink.ToPageReference());
        }
Ejemplo n.º 18
0
        public ActionResult AddComment(SitePageData currentPage, string commentName, string commentText)
        {
            // get (or create if necessary) the folder for comments for the current page
            ContentReference commentsFolderReference;

            if (!ContentReference.IsNullOrEmpty(currentPage.CommentFolder))
            {
                commentsFolderReference = currentPage.CommentFolder;
            }
            else
            {
                // get the start page's comments folder
                StartPage        start = repo.Get <StartPage>(ContentReference.StartPage);
                ContentReference siteCommentsFolderReference;
                siteCommentsFolderReference = start.CommentFolder;

                // create a comments folder for this page
                ContentFolder commentsFolder = repo.GetDefault <ContentFolder>(start.CommentFolder);
                commentsFolder.Name     = $"{currentPage.Name} (Comments)";
                commentsFolderReference = repo.Save(commentsFolder,
                                                    EPiServer.DataAccess.SaveAction.Publish,
                                                    EPiServer.Security.AccessLevel.Publish);

                currentPage = currentPage.CreateWritableClone() as SitePageData;
                currentPage.CommentFolder = commentsFolderReference;
                repo.Save(currentPage,
                          EPiServer.DataAccess.SaveAction.Publish,
                          EPiServer.Security.AccessLevel.NoAccess);
            }

            // create the comment in the page's Comments folder
            CommentBlock comment = repo.GetDefault <CommentBlock>(commentsFolderReference);

            comment.When        = DateTime.Now;
            commentName         = string.IsNullOrWhiteSpace(commentName) ? "Anonymous" : commentName;
            comment.CommentName = commentName;
            comment.CommentText = commentText;

            IContent saveableComment = comment as IContent;

            saveableComment.Name = commentName;
            repo.Save(saveableComment,
                      EPiServer.DataAccess.SaveAction.Publish,
                      EPiServer.Security.AccessLevel.Publish);

            // reload the original page
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 19
0
        public ContentReference Insert(string filename, string imageExtension, byte[] data)
        {
            try
            {
                var segments = filename.Split('/');
                var folder   = GetOrCreateFolder(segments.Take(segments.Length - 1));

                var file = GetOrCreateFile(segments.Last(), folder);

                file.Name = segments.Last();

                var blob = _blobFactory.CreateBlob(file.BinaryDataContainer, imageExtension);
                using (var s = blob.OpenWrite())
                    using (var w = new StreamWriter(s))
                    {
                        w.BaseStream.Write(data, 0, data.Length);
                        w.Flush();
                    }

                //Assign to file and publish changes
                file.BinaryData = blob;
                var file1ID = _contentRepository.Save(file, SaveAction.Publish, AccessLevel.NoAccess);
                return(file1ID);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 20
0
        public ActionResult UpdateContent(UpdateContentModel updateContentModel)
        {
            var props   = updateContentModel.Properties.Split(',');
            var message = "";

            try
            {
                foreach (var updateContent in updateContentModel.Contents)
                {
                    var content = _contentRepository.Get <IContent>(updateContent.ContentLink.GuidValue.Value);
                    if (!(((IReadOnly)content)?.CreateWritableClone() is IContent clone))
                    {
                        message = "No IReadonly implementation!";
                    }
                    else
                    {
                        foreach (var prop in props)
                        {
                            var propData = clone.Property.FirstOrDefault(o => o.Name == prop);
                            propData.Value = updateContent.Properties[prop];
                            clone.Property.Set(prop, propData);
                        }
                        clone.Name = updateContent.Name;
                        _contentRepository.Save(clone, EPiServer.DataAccess.SaveAction.Publish);
                    }
                }
        public bool SaveTemplate(string virtualPath, string fileContents)
        {
            VirtualTemplateContent template;

            if (RegisteredViews.ContainsKey(_keyConverter.GetTemplateKey(virtualPath)))
            {
                var contentRef = RegisteredViews[_keyConverter.GetTemplateKey(virtualPath)];
                template =
                    _contentRepo.Get <VirtualTemplateContent>(contentRef)
                    .CreateWritableClone() as VirtualTemplateContent;
            }
            else
            {
                template      = _contentRepo.GetDefault <VirtualTemplateContent>(VirtualTemplateRootInit.VirtualTemplateRoot);
                template.Name = _keyConverter.GetTemplateKey(virtualPath);
            }

            if (template != null)
            {
                template.VirtualPath      = _keyConverter.GetTemplateKey(virtualPath);
                template.TemplateContents = fileContents;
                _contentRepo.Save(template, SaveAction.ForceNewVersion | SaveAction.Publish, AccessLevel.NoAccess);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 22
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));
        }
        /// <summary>
        /// Updates the Date property in StartPage with current time in yyyy-MM-dd HH:mm:ss format.
        /// </summary>
        /// <returns>A string with either a success or failure message </returns>
        public override string Execute()
        {
            //Call OnStatusChanged to periodically notify progress of job for manually started jobs
            OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
            SiteDefinition.Current = SiteDefinitionRepository.Service.List().First();
            IContentRepository repo           = ServiceLocator.Current.GetInstance <IContentRepository>();
            StartPage          startPageClone =
                repo.Get <StartPage>(SiteDefinition.Current.StartPage).CreateWritableClone() as StartPage;

            if (startPageClone == null)
            {
                return($"Could not execute {jobName}. Could not find the start page.");
            }

            if (_stopSignaled)
            {
                return($"{jobName} was stopped manually");
            }

            string nowString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            startPageClone.Date += nowString + "<br/>";
            repo.Save(startPageClone, SaveAction.Publish, AccessLevel.Read);

            return($"Success. {jobName} finished with result {nowString}");
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called when a scheduled job executes
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {
            //Call OnStatusChanged to periodically notify progress of job for manually started jobs
            OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));


            var page = new PageReference(1109);


            EventPage eventPage = _repo.Get <EventPage>(page).CreateWritableClone() as EventPage;


            if (eventPage != null)
            {
                var date = new DateTime(2019, 7, 9, 10, 00, 00);
                eventPage.Heading = "Fredags-event!!";
                eventPage.Date    = date;
                _repo.Save(eventPage, EPiServer.DataAccess.SaveAction.Publish,
                           EPiServer.Security.AccessLevel.NoAccess);
            }

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

            return("Change to message that describes outcome of execution");
        }
        private void Source_OnCommandOutput(IOutputCommand sender, object output)
        {
            var content = output as IContent;
            var r       = _repo.Save(content, Action);

            OnCommandOutput?.Invoke(this, r);
        }
Ejemplo n.º 26
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.º 27
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);
        }
Ejemplo n.º 28
0
 public Messages Save(ContentEntity model, UserClaimModel userClaim)
 {
     if (model != null && model.C_TITLE.IsNotNullOrEmpty() && model.C_SUBTITLE.IsNotNullOrEmpty() && model.C_SUMMARY.IsNotNullOrEmpty() && model.C_AUTHOR.IsNotNullOrEmpty() && model.C_SOURCE.IsNotNullOrEmpty() && model.C_CONTENT.IsNotNullOrEmpty())
     {
         model.C_TITLE            = model.C_TITLE.HtmlEncode();
         model.C_SUBTITLE         = model.C_SUBTITLE.HtmlEncode();
         model.C_IMAGEURL         = model.C_IMAGEURL?.HtmlEncode() ?? "";
         model.C_SUMMARY          = model.C_SUMMARY.HtmlEncode();
         model.C_AUTHOR           = model.C_AUTHOR.HtmlEncode();
         model.C_SOURCE           = model.C_SOURCE.HtmlEncode();
         model.C_KEYWORDS         = model.C_KEYWORDS?.HtmlEncode() ?? "";
         model.C_ADDUSERNAME      = userClaim.UserName;
         model.C_LASTEDITUSERNAME = userClaim.UserName;
         int result = contentRepository.Save(model);
         if (result > 0)
         {
             messages.Msg     = "提交成功!!";
             messages.Success = true;
         }
         else
         {
             messages.Msg = "提交失败!!";
         }
     }
     else
     {
         messages.Msg = "请填写必填字段信息";
     }
     return(messages);
 }
Ejemplo n.º 29
0
        private void AddMedia(string title, string fullpath, string teaser, DateTime?date, ContentFolder rootFolder)
        {
            var mediaFile = _contentRepository.GetDefault <DocumentFile>(rootFolder.ContentLink);

            mediaFile.Name        = title;
            mediaFile.Description = StripHtml(teaser);
            mediaFile.PubDate     = date == null ? DateTime.Today : date.Value;

            var extension = Path.GetExtension(fullpath);

            var blob = _blobFactory.CreateBlob(mediaFile.BinaryDataContainer, extension);

            var fileData = File.ReadAllBytes(fullpath);

            using (var s = blob.OpenWrite())
            {
                var w = new BinaryWriter(s);
                w.Write(fileData);
                w.Flush();
            }

            mediaFile.BinaryData = blob;

            _contentRepository.Save(mediaFile, SaveAction.Publish);
        }
Ejemplo n.º 30
0
        private void PublishChildren(IContentRepository repository, IContent root)
        {
            var children = repository.GetChildren <IContent>(root.ContentLink);

            foreach (IContent content in children)
            {
                try
                {
                    var imageContent = content as ImageData;
                    if (imageContent != null)
                    {
                        var unpublished = imageContent.CreateWritableClone() as ImageData;
                        repository.Save(unpublished, SaveAction.Publish);
                    }
                }
                catch (Exception e)
                {
                    _error.Add(e.Message);
                }
                if (_stopSignaled)
                {
                    break;
                }
                PublishChildren(repository, content);
            }
        }
        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 void PublishChildren(IContentRepository repository, IContent root)
        {
            var children = repository.GetChildren<IContent>(root.ContentLink);

            foreach (IContent content in children)
            {

                try
                {
                    var imageContent = content as ImageData;
                    if (imageContent != null)
                    {
                        var unpublished = imageContent.CreateWritableClone() as ImageData;
                        repository.Save(unpublished, SaveAction.Publish);
                    }
                }
                catch (Exception e)
                {
                    _error.Add(e.Message);
                }
                if (_stopSignaled)
                {
                    break;
                }
                PublishChildren(repository, content);
            }
        }
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 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.º 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;
                }
            }
        }
Ejemplo n.º 36
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;
                    }
                }
            }
        }