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); } }
protected virtual PageReference GetDatePageRef(IHasDateContainer hasDateContainerPage, PageData dateContainerRoot, DateTime published, IContentRepository contentRepository) { foreach (var yearContainer in contentRepository.GetChildren<PageData>(dateContainerRoot.ContentLink)) { if (yearContainer.Name == published.Year.ToString()) { PageReference result; foreach (PageData monthContainer in contentRepository.GetChildren<PageData>(yearContainer.ContentLink)) { if (monthContainer.Name == published.Month.ToString()) { result = monthContainer.PageLink; return result; } } result = CreateDateContainer(hasDateContainerPage, yearContainer.PageLink, published.Month.ToString(), new DateTime(published.Year, published.Month, 1)); return result; } } PageReference parent = CreateDateContainer(hasDateContainerPage, dateContainerRoot.ContentLink, published.Year.ToString(), new DateTime(published.Year, 1, 1)); return CreateDateContainer(hasDateContainerPage, parent, published.Month.ToString(), new DateTime(published.Year, published.Month, 1)); }
// in here we know that the page is a blog start page and now we must create the date pages unless they are already created public PageReference GetDatePageRef(PageData blogStart, DateTime published, IContentRepository contentRepository) { foreach (var current in contentRepository.GetChildren<PageData>(blogStart.ContentLink)) { if (current.Name == published.Year.ToString()) { PageReference result; foreach (PageData current2 in contentRepository.GetChildren<PageData>(current.ContentLink)) { if (current2.Name == published.Month.ToString()) { result = current2.PageLink; return result; } } result = CreateDatePage(contentRepository, current.PageLink, published.Month.ToString(), new DateTime(published.Year, published.Month, 1)); return result; } } PageReference parent = CreateDatePage(contentRepository, blogStart.ContentLink, published.Year.ToString(), new DateTime(published.Year, 1, 1)); return CreateDatePage(contentRepository, parent, published.Month.ToString(), new DateTime(published.Year, published.Month, 1)); }
public void DeleteCatalogNode(string code) { ContentReference contentReference = _referenceConverter.GetContentLink(code, CatalogContentType.CatalogNode); if (!_contentRepository.TryGet(contentReference, out NodeContent nodeToDelete)) { _logger.Error($"DeleteCatalogNode called with a code that doesn't exist or is not a catalog node: {code}"); return; } List <IDeleteActionsHandler> importerHandlers = ServiceLocator.Current.GetAllInstances <IDeleteActionsHandler>().ToList(); if (_config.RunDeleteActionsHandlers) { foreach (IDeleteActionsHandler handler in importerHandlers) { handler.PreDeleteCatalogNode(nodeToDelete); } } IEnumerable <EntryContentBase> children = _contentRepository.GetChildren <EntryContentBase>(nodeToDelete.ContentLink); foreach (EntryContentBase child in children.Where(ShouldDeleteChild)) { _contentRepository.Delete(child.ContentLink, true, AccessLevel.NoAccess); } _contentRepository.Delete(nodeToDelete.ContentLink, true, AccessLevel.NoAccess); if (_config.RunDeleteActionsHandlers) { foreach (IDeleteActionsHandler handler in importerHandlers) { handler.PostDeleteCatalogNode(nodeToDelete); } } }
public LayoutViewModel GenerateLayout() { var layout = new LayoutViewModel(); var startPage = _contentRepository.Get <BasePage>(ContentReference.StartPage); var subPages = _contentRepository.GetChildren <BasePage>(ContentReference.StartPage); List <MenuItem> subItems = subPages .Select(subItem => new MenuItem { Link = subItem.LinkURL, Name = subItem.Name }) .ToList(); var menuItem = new MenuItem { Link = startPage.LinkURL, Name = startPage.Name, SubItems = subItems, }; layout.MenuItems.Add(menuItem); return(layout); }
/// <summary> /// The index action for the image file. Creates the view model and renders the view. /// </summary> /// <param name="currentContent">The current image file.</param> public override ActionResult Index(ContentFolder currentContent) { ContentFolderViewModel viewModel = new ContentFolderViewModel(); string language = Language; var children = _contentRepository.GetChildren <MediaData>(currentContent.ContentLink); foreach (MediaData mediaData in children) { ContentFolderItemViewModel itemModel = new ContentFolderItemViewModel(); itemModel.Content = mediaData; itemModel.Url = _urlResolver.GetUrl(mediaData.ContentLink); itemModel.ThumbnailUrl = _urlResolver.GetUrl( mediaData.ContentLink, language, new VirtualPathArguments() { ContextMode = ContextMode.Default }) + "?preset=thumbnail"; viewModel.Items.Add(itemModel); } return(PartialView("Index", viewModel)); }
public void StartWithEpiserverEngineFirstIteration_RunMultipleTimes_SinglePageExists(int _) { var engine = new EpiserverEngineFirstIteration(); engine.Start(); CreateUser("Administrator", "Administrator", "*****@*****.**"); IContentRepository repository = ServiceLocator.Current.GetInstance <IContentRepository>(); var startPage = repository.GetDefault <StartPage>(ContentReference.RootPage); startPage.Name = "Start"; startPage.Heading = "Welcome to Lorem"; startPage.StartPublish = DateTime.Now; repository.Save(startPage, SaveAction.Publish, AccessLevel.NoAccess); var pages = repository.GetChildren <StartPage>(ContentReference.RootPage); Assert.Single(pages); engine.Stop(); }
public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentInfo paymentInfo, int[] SelectedCategories) { model.PaymentInfo = paymentInfo; model.AvailableCategories = GetAvailableCategories(); model.SelectedCategories = SelectedCategories; bool requireSSN = paymentInfo.SelectedPayment == new Guid("8dca4a96-a5bb-4e85-82a4-2754f04c2117") || paymentInfo.SelectedPayment == new Guid("c2ea88f8-c702-4331-819e-0e77e7ac5450"); // validate input! ValidateFields(model, requireSSN); CartHelper ch = new CartHelper(Cart.DefaultName); // Verify that we actually have the items we're about to sell ConfirmStocks(ch.LineItems); if (ModelState.IsValid) { var billingAddress = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName); var shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName); string username = model.Email.Trim(); billingAddress.Email = username; billingAddress.DaytimePhoneNumber = model.Phone; HandleUserCreation(model, billingAddress, shippingAddress, username); if (ModelState.IsValid) { // Checkout: ch.Cart.OrderAddresses.Add(billingAddress); ch.Cart.OrderAddresses.Add(shippingAddress); AddShipping(ch.Cart, shippingAddress); ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub; if (model.SelectedCategories != null) { ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories); } OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName); AddPayment(ch.Cart, paymentInfo.SelectedPayment.ToString(), billingAddress); ch.Cart.AcceptChanges(); // TODO: This assume the different payment pages are direct children of the start page // and could break the payment if we move the pages. BasePaymentPage page = null; var startPage = _contentRepository.Get <HomePage>(ContentReference.StartPage); foreach (var p in _contentRepository.GetChildren <BasePaymentPage>(startPage.Settings.PaymentContainerPage)) { if (p.PaymentMethod.Equals(model.PaymentInfo.SelectedPayment.ToString())) { page = p; break; } } var resolver = ServiceLocator.Current.GetInstance <UrlResolver>(); if (page != null) { var url = resolver.GetUrl(page.ContentLink); return(Redirect(url)); } } } Guid?selectedPayment = model.PaymentInfo.SelectedPayment; model.PaymentInfo = GetPaymentInfo(); if (selectedPayment.HasValue) { model.PaymentInfo.SelectedPayment = selectedPayment.Value; } model.TermsArticle = currentPage.TermsArticle; return(View(model)); }
public static async Task <bool> FileParserAsync(GcFile gcFile, string postType, ContentReference contentLink, SaveAction saveAction, string action) { // Initialize fileExtensions dictionary with all the supported audio, video and generic files. var fileExtensions = new Dictionary <string, List <string> > { { "Video", new List <string> { "flv", "mp4", "webm", "avi", "wmv", "mpeg", "ogg", "mov", "ogv", "qt", "mp3", "pcm", "aac", "wma", "flac", "alac", "wav", "aiff" } }, { "Image", new List <string> { "jpg", "jpeg", "jpe", "ico", "gif", "bmp", "png", "tga", "tiff", "eps", "svg", "webp" } }, { "Generic", new List <string> { "pdf", "doc", "docx", "txt", "xsl", "xslx", "html", "css", "zip", "rtf", "rar", "csv", "xml", "log" } } }; // Get an instance of ContentAssetHelper class. var contentAssetHelper = ServiceLocator.Current.GetInstance <ContentAssetHelper>(); // Get an existing content asset folder or create a new one contentLink = contentAssetHelper.GetOrCreateAssetFolder(contentLink).ContentLink; // Get an instance of IContentRepository. var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>(); // Extract the file extension of the file by its name. var fileExtension = Path.GetExtension(gcFile.FileName).Replace(".", ""); // Initialize a new MediaData object. MediaData file; if (fileExtensions["Image"].Contains(fileExtension)) { file = contentRepository.GetDefault <GcEpiImageFile>(contentLink); } else if (fileExtensions["Generic"].Contains(fileExtension)) { file = contentRepository.GetDefault <GcEpiGenericFile>(contentLink); } else if (fileExtensions["Video"].Contains(fileExtension)) { file = contentRepository.GetDefault <GcEpiVideoFile>(contentLink); } else { return(false); } file.Name = gcFile.FileName; file.Property["GcFileInfo"].Value = gcFile.Id + "~" + gcFile.FileName + "~" + gcFile.ItemId; if (action == "Update") { // Check if the file is already imported. var importedFiles = ContentRepository.GetChildren <MediaData>(contentLink, CultureInfo.InvariantCulture).ToList(); foreach (var importedFile in importedFiles) { var propSubStrings = importedFile.Property["GcFileInfo"].Value.ToString().Split('~'); var importedFileGcFileId = Convert.ToInt32(propSubStrings[0]); var importedFileGcFileName = propSubStrings[1]; var importedFileGcFileItemId = Convert.ToInt32(propSubStrings[2]); if (importedFileGcFileName != gcFile.FileName || importedFileGcFileItemId != gcFile.ItemId) { continue; } if (importedFileGcFileId == gcFile.Id) { return(false); } contentRepository.Delete(importedFile.ContentLink, true, AccessLevel.Administer); } } var blobFactory = ServiceLocator.Current.GetInstance <IBlobFactory>(); try { using (var client = new HttpClient()) { using (var request = new HttpRequestMessage(new HttpMethod("GET"), $"https://api.gathercontent.com/files/{gcFile.Id}/download")) { request.Headers.TryAddWithoutValidation("Accept", "application/vnd.gathercontent.v0.5+json"); var creds = GcDynamicUtilities.RetrieveStore <GcDynamicCredentials>(); var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{creds.ToList().First().Email}:{creds.ToList().First().ApiKey}")); request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); var response = await client.SendAsync(request); var byteArrayData = await response.Content.ReadAsByteArrayAsync(); var blob = blobFactory.CreateBlob(file.BinaryDataContainer, Path.GetExtension(gcFile.FileName)); using (var s = blob.OpenWrite()) { var w = new StreamWriter(s); w.BaseStream.Write(byteArrayData, 0, byteArrayData.Length); w.Flush(); } file.BinaryData = blob; contentRepository.Save(file, saveAction, AccessLevel.Administer); return(true); } } } catch (Exception e) { Console.WriteLine(e); return(false); } }
private static IEnumerable <IContent> GetMenu(ContentReference reference, IContentRepository repository) { var children = repository.GetChildren <PageData>(reference); return(children.Where(page => page.VisibleInMenu).ToList()); }
public virtual IEnumerable <T> GetChildren <T>(ContentReference parentCategoryLink, CultureInfo culture) where T : CategoryData { return(ContentRepository.GetChildren <T>(parentCategoryLink, culture)); }
public IEnumerable <SiteSettingsPage> GetChildren(ContentReference parentPageReference) { return(_contentRepository.GetChildren <SiteSettingsPage>(parentPageReference)); }
protected void WalkCategoryTree(NodeContent node, IContentRepository repository, CatalogContentLoader contentLoader, ICatalogSystem catalog, ReferenceConverter referenceConverter) { // ReSharper disable PossibleMultipleEnumeration // Get all products Stopwatch tmr = Stopwatch.StartNew(); IEnumerable<EntryContentBase> entries = repository.GetChildren<EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase>(node.ContentLink); _log.Debug("Loaded {0} entries in category {1} using IContentRepository in {2}ms", entries.Count(), node.Name, tmr.ElapsedMilliseconds); // Load and cache Entry objects. Still a lot of code that uses this tmr = Stopwatch.StartNew(); foreach (EntryContentBase entryAsContent in entries) { // Load full entry int entryId = referenceConverter.GetObjectId(entryAsContent.ContentLink); // Catalog Gadget uses info //catalog.GetCatalogEntry(entryId, // new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo)); catalog.GetCatalogEntry(entryId, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull)); } // Prime the catalog gadget // IEnumerable<IContent> children = repository.GetChildren<IContent>(node.ContentLink, new LanguageSelector("en"), 0, int.MaxValue); // _log.Debug("Loaded {0} children", children.Count()); // .GetDescendents(node.ContentLink); tmr.Stop(); _log.Debug("Loaded {0} entries in category {1} using ICatalogSystem in {2}ms", entries.Count(), node.Name, tmr.ElapsedMilliseconds); // Get all products the way it is done in edit mode, but this does not seem to // use the cache. //int loadedEntries; //contentLoader.GetCatalogEntries(node.ContentLink, 0, int.MaxValue, out loadedEntries); //_log.Debug("Loaded {0} entries in category {1} using CatalogContentLoader", loadedEntries, node.Name); // Get child nodes the same way done by the UI IList<GetChildrenReferenceResult> catalogNodes = contentLoader.GetCatalogNodes(node.ContentLink); _log.Debug("Loaded {0} categories in category {1} using CatalogContentLoader", catalogNodes.Count, node.Name); foreach (GetChildrenReferenceResult catalogNode in catalogNodes) { NodeContent childNode = repository.Get<NodeContent>(catalogNode.ContentLink); WalkCategoryTree(childNode, repository, contentLoader, catalog, referenceConverter); } // ReSharper restore PossibleMultipleEnumeration }
ContainerPageType GetContainerPageByName(string containerPageName, PageReference parent) { return(_contentRepository.GetChildren <ContainerPageType>(parent).FirstOrDefault(x => x.PageName == containerPageName)); }
protected void AddAllPagesInAllLanguagesForConfiguration(SiteConfigurationElement configuration, PageData page) { //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { OnStatusChanged("Stop of job was called"); return; } // Only add pages once (have this because of how websites can be setup to have a circle reference if (page.ContentLink == null || _generatedPages.ContainsKey(page.ContentLink.ID)) { return; } _generatedPages.Add(page.ContentLink.ID, null); // This page type should be ignored var ignorePageType = page is IStaticWebIgnoreGenerate; var languages = page.ExistingLanguages; foreach (var lang in languages) { var ignorePage = ignorePageType; var langPage = _contentRepository.Get <PageData>(page.ContentLink.ToReferenceWithoutVersion(), lang); var langContentLink = langPage.ContentLink.ToReferenceWithoutVersion(); if (!langPage.CheckPublishedStatus(PagePublishedStatus.Published)) { ignorePage = true; } // This page type has a conditional for when we should generate it if (langPage is IStaticWebIgnoreGenerateDynamically generateDynamically) { if (!generateDynamically.ShouldGenerate()) { if (generateDynamically.ShouldDeleteGenerated()) { _staticWebService.RemoveGeneratedPage(configuration, langContentLink, lang); } // This page should not be generated at this time, ignore it. ignorePage = true; } } if (!ignorePage) { var urls = _staticWebService.GetUrlsForPage(configuration, page, lang, out string simpleAddress); foreach (var url in urls) { UpdateScheduledJobStatus(configuration, url); _sitePages[configuration.Name].TryAdd(url, null); } if (!string.IsNullOrEmpty(simpleAddress)) { _sitePages[configuration.Name].TryAdd(simpleAddress, null); } //_staticWebService.GeneratePage(configuration, langPage, lang, _generatedResources); _numberOfPages++; } var children = _contentRepository.GetChildren <PageData>(langContentLink, lang); foreach (PageData child in children) { AddAllPagesInAllLanguagesForConfiguration(configuration, child); //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { OnStatusChanged("Stop of job was called"); return; } } //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { OnStatusChanged("Stop of job was called"); return; } } }
public async Task <Content[]> GetChildren(Guid id) { return((await _contentRepository.GetChildren(id)).OrderBy(x => x.Name).ToArray()); }
/// <summary> /// Gets the first child of of the content item represented by the provided reference. /// </summary> /// <param name="contentRepository"></param> /// <param name="contentReference"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T GetFirstChild <T>(this IContentRepository contentRepository, ContentReference contentReference) where T : IContentData { return(contentRepository.GetChildren <T>(contentReference).FirstOrDefault()); }
private IEnumerable <StartPage> GetStartPages() => _contentRepository .GetChildren <StartPage>(SiteDefinition.Current.RootPage, new LoaderOptions { LanguageLoaderOption.MasterLanguage() });
private ProductSearchResults GetSearchResults(IContent currentContent, CommerceFilterOptionViewModel filterOptions, string selectedfacets, IEnumerable <Filter> filters = null, int catalogId = 0) { //If contact belong organization, only find product that belong the categories that has owner is this organization var contact = PrincipalInfo.CurrentPrincipal.GetCustomerContact(); var organizationId = contact?.ContactOrganization?.PrimaryKeyId ?? Guid.Empty; CatalogContent catalogOrganization = null; if (organizationId != Guid.Empty) { //get category that has owner id = organizationId catalogOrganization = _contentRepository .GetChildren <CatalogContent>(_referenceConverter.GetRootLink()) .FirstOrDefault(x => !string.IsNullOrEmpty(x.Owner) && x.Owner.Equals(organizationId.ToString(), StringComparison.OrdinalIgnoreCase)); } var pageSize = filterOptions.PageSize > 0 ? filterOptions.PageSize : DefaultPageSize; var market = _currentMarket.GetCurrentMarket(); var query = _findClient.Search <EntryContentBase>(); query = ApplyTermFilter(query, filterOptions.Q, filterOptions.TrackData); query = query.Filter(x => x.Language.Name.Match(_languageResolver.GetPreferredCulture().Name)); if (organizationId != Guid.Empty && catalogOrganization != null) { query = query.Filter(x => x.Outline().PrefixCaseInsensitive(catalogOrganization.Name)); } var nodeContent = currentContent as NodeContent; if (nodeContent != null) { var outline = GetOutline(nodeContent.Code); query = query.FilterOutline(new[] { outline }); } query = query.FilterMarket(market); var facetQuery = query; query = FilterSelected(query, filterOptions.FacetGroups); query = ApplyFilters(query, filters); query = OrderBy(query, filterOptions); //Exclude products from search //query = query.Filter(x => (x as ProductContent).ExcludeFromSearch.Match(false)); if (catalogId != 0) { query = query.Filter(x => x.CatalogId.Match(catalogId)); } query = query.ApplyBestBets() .Skip((filterOptions.Page - 1) * pageSize) .Take(pageSize) .StaticallyCacheFor(TimeSpan.FromMinutes(1)); var result = query.GetContentResult(); return(new ProductSearchResults { ProductViewModels = CreateProductViewModels(result, currentContent, filterOptions.Q), FacetGroups = GetFacetResults(filterOptions.FacetGroups, facetQuery, selectedfacets), TotalCount = result.TotalMatching, DidYouMeans = string.IsNullOrEmpty(filterOptions.Q) ? null : _findClient.Statistics().GetDidYouMean(filterOptions.Q), Query = filterOptions.Q, }); }
public static IEnumerable <ContentFolder> GetFolders(IContentRepository contentRepository, ContentFolder folder) { var subFolders = contentRepository.GetChildren <ContentFolder>(folder.ContentLink); return(subFolders); }
public static IEnumerable <IContentData> GetChildren(this IContentRepository contentRepository, Uri contentUri) { return(contentRepository.GetChildren <IContentData>(contentUri)); }
private CatalogContent GetCatalogFromName(string catalog) { var catalogs = _contentRepository.GetChildren <CatalogContent>(_referenceConverter.GetRootLink()); return(catalogs.FirstOrDefault(c => c.Name.Equals(catalog, StringComparison.InvariantCultureIgnoreCase))); }
public IEnumerable <KeyValuePage> GetChildren(ContentReference parentPageReference) { return(_contentRepository.GetChildren <KeyValuePage>(parentPageReference)); }
public virtual IEnumerable <T> GetChildren <T>(ContentReference contentLink, IEnumerable <ContentReference> categories, LoaderOptions loaderOptions) where T : ICategorizableContent, IContentData { return(ContentRepository .GetChildren <T>(contentLink, loaderOptions) .Where(x => x.Categories.MemberOfAny(categories))); }