public virtual LocalizationContainer GetOrAddLocalizationContainer() { if (CachedLocalizationContainer == null) { lock (Lock) { var findLocalizationContainer = FindLocalizationContainer(LanguageSelector.MasterLanguage()) ?? AddLocalizationContainer(); CachedLocalizationContainer = findLocalizationContainer.ContentLink; return(findLocalizationContainer); } } try { return(_contentRepository.Service.Get <LocalizationContainer>(CachedLocalizationContainer, LanguageSelector.MasterLanguage())); } catch (PageNotFoundException) { // this can happen when we cached the localization pagereference but the page has been removed mean while. var newLocalizationContainer = AddLocalizationContainer(); CachedLocalizationContainer = newLocalizationContainer.ContentLink; return(newLocalizationContainer); } }
private static PageData FindPageByName(PageReference rootPage, string pageName, string pageType) { PageDataCollection children = DataFactory.Instance.GetChildren(rootPage); children.Add(DataFactory.Instance.GetChildren(rootPage, LanguageSelector.MasterLanguage())); return(children.FirstOrDefault(page => page.PageName.Equals(pageName) && page.PageTypeName.Equals(pageType))); }
public IEnumerable <ContentSummary> List(int contentTypeId) { var allContent = new List <ContentSummary>(); var contentType = _contentTypeRepository.Load(contentTypeId); if (contentType == null) { return(Enumerable.Empty <ContentSummary>()); } IList <ContentUsage> contentUsages = _contentModelUsage.ListContentOfContentType(contentType); IEnumerable <ContentSummary> collection = contentUsages .Distinct(new Comparer()) .Select(contentUsage => { ContentReference contentLink = contentUsage.ContentLink.ToReferenceWithoutVersion(); var content = _contentLoader.Get <IContent>(contentLink, LanguageSelector.MasterLanguage()); var translations = new Dictionary <string, string>(); string masterLanguageName = string.Empty; var localizable = content as ILocalizable; if (localizable != null) { CultureInfo masterLanguage = localizable.MasterLanguage; masterLanguageName = masterLanguage.Name; translations = GetTranslations(contentLink, localizable.ExistingLanguages.Except(new[] { masterLanguage })); } translations.Add(masterLanguageName, content.Name); return(new ContentSummary { ContentLink = contentLink, Translations = translations, MasterLanguage = masterLanguageName, IsDeleted = content.IsDeleted }); }).ToList(); allContent.AddRange(collection); return(allContent.OrderBy(item => item.ContentLink.ID).ToList()); }
public ContentTreeRootItem GetContentFamily(int rootId) { var page = _contentLoader.Get <PageData>(new ContentReference(rootId)); var children = _contentLoader .GetChildren <PageData>(page.ContentLink, LanguageSelector.MasterLanguage()) .Select(s => new ContentTreeChildItem { Id = s.ContentLink.ToReferenceWithoutVersion().ID, Text = s.Name, Children = _contentLoader.GetChildren <PageData>(s.ContentLink, LanguageSelector.MasterLanguage()).Any() }); return(new ContentTreeRootItem { Id = page.ContentLink.ToReferenceWithoutVersion().ID, Text = page.Name, Children = children }); }
/// <summary> /// This method creates a container page under a parent, based on a given name /// </summary> /// <param name="parent">The parent.</param> /// <param name="childName">Name of the child.</param> /// <param name="language"></param> /// <returns></returns> protected ContentReference CreateChildUnderContainer(ContentReference parent, int childName, string language) { //1. Create a new MediaContainer page with the name of the childName //2. Return the newly created PageReference try { if (YearContainerPageTypeId == 0) { return(parent); } ContentReference otherLanguage = null; foreach (PageData child in ContentRepository.GetChildren <PageData>(parent, LanguageSelector.MasterLanguage())) { if (string.Compare(child.PageName, childName.ToString(), true) == 0) { otherLanguage = child.PageLink; break; } } if (otherLanguage == null) { // first add the first language of the year container, then loop through other language of the start page. //ContentReference yearContainer; CultureInfo mainLanguage = new CultureInfo("en"); PageData yearPage = ContentRepository.GetDefault <PageData>( parent, YearContainerPageTypeId, mainLanguage); yearPage.PageName = childName.ToString(); otherLanguage = ContentRepository.Save(yearPage, SaveAction.Publish, AccessLevel.NoAccess); } if (language != "en") { CultureInfo langSel = new CultureInfo(language); var yearPage = ContentRepository.CreateLanguageBranch <PageData>(otherLanguage, langSel); yearPage.PageName = childName.ToString(); ContentRepository.Save(yearPage, SaveAction.Publish, AccessLevel.NoAccess); } return(otherLanguage); } catch { return(ContentReference.EmptyReference); } }
/// <summary> /// Starts the job /// </summary> /// <returns>A status message that will be logged</returns> public override string Execute() { IndexInformation info = new IndexInformation(); Stopwatch tmr = Stopwatch.StartNew(); IClient client = SearchClient.Instance; //Delete all client.Delete <FindProduct>(x => x.MatchType(typeof(FindProduct))); var language = LanguageSelector.MasterLanguage(); var localizationService = ServiceLocator.Current.GetInstance <LocalizationService>(); var marketService = ServiceLocator.Current.GetInstance <IMarketService>(); var allMarkets = marketService.GetAllMarkets(); var priceService = ServiceLocator.Current.GetInstance <IPriceService>(); var linksRepository = ServiceLocator.Current.GetInstance <ILinksRepository>(); // TODO: Add support for multiple catalogs. This will pick the first one. IEnumerable <ContentReference> contentLinks = contentLoader.GetDescendents(Root); int bulkSize = 100; foreach (CultureInfo availableLocalization in localizationService.AvailableLocalizations) { var market = allMarkets.FirstOrDefault(m => m.DefaultLanguage.Equals(availableLocalization)); if (market == null) { continue; } string language2 = availableLocalization.Name.ToLower(); int allContentsCount = contentLinks.Count(); for (var i = 0; i < allContentsCount; i += bulkSize) { var items = contentLoader.GetItems(contentLinks.Skip(i).Take(bulkSize), new LanguageSelector(availableLocalization.Name)); var items2 = items.OfType <IIndexableContent>().ToList(); foreach (var content in items2) { info.NumberOfProductsFound++; OnStatusChanged(String.Format("Searching product {0}/{1} - {2}", i + 1, allContentsCount, content.Name)); if (content.ShouldIndex()) { info.NumberOfProductsFoundAfterExpiredFilter++; var findProduct = content.GetFindProduct(market); if (findProduct != null) { client.Index(findProduct); info.NumberOfProductsIndexed++; } } //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { tmr.Stop(); info.Duration = tmr.ElapsedMilliseconds; break; } } //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { tmr.Stop(); info.Duration = tmr.ElapsedMilliseconds; break; } } } if (_stopSignaled) { return("Stop of job was called. " + info.ToString()); } tmr.Stop(); info.Duration = tmr.ElapsedMilliseconds; return(info.ToString()); }
public void EntryDeleted(CatalogContentUpdateEventArgs e) { Logger.Debug("EntryDeleted raised."); IEnumerable <ContentReference> contentLinks = GetContentLinks(e); // Variants IEnumerable <ContentReference> variantLinks = GetVariantReferences(contentLinks); VariationContent[] variants = _contentLoader.GetItems(variantLinks, CultureInfo.InvariantCulture) .OfType <VariationContent>() .ToArray(); foreach (VariationContent variant in variants) { foreach (var parent in variant.GetParentProducts()) { var product = _contentLoader.Get <ProductContent>(parent); IEnumerable <ContentReference> variantRefs = _relationRepository .GetChildren <ProductVariation>(product.ContentLink) .Select(r => r.Child); ICollection <VariationContent> productVariants = _contentLoader .GetItems(variantRefs, LanguageSelector.MasterLanguage()) .OfType <VariationContent>() .ToArray(); var configuration = KachingConfiguration.Instance; if (productVariants.Count == 1 && configuration.ExportSingleVariantAsProduct) { _productExportService.DeleteSingleVariantProduct(variant); } else { // Since variants are not independent datatypes in Ka-ching // a variant change is always a product update and not a delete _productExportService.ExportProduct(product, variant.Code); } } } // Products IEnumerable <ContentReference> productLinks = GetProductReferences(contentLinks); ProductContent[] products = _contentLoader.GetItems(productLinks, CultureInfo.InvariantCulture) .OfType <ProductContent>() .ToArray(); _productExportService.DeleteProducts(products); _productExportService.DeleteProductAssets(products); _productExportService.DeleteProductRecommendations(products); }
public override ContentReference Save(IContent content, SaveAction action) { //We know it's only possible to create placeholders as these are not persisted if (content is ImagePlaceholderMediaType) { ImagePlaceholderMediaType placeholderImage = content as ImagePlaceholderMediaType; //Get the type holding PNG files Type modelType = this._contentMediaResolver.GetFirstMatching(this._placeholderManager.FileExtension); ContentType contentType = this._contentTypeRepository.Load(modelType); //Get parent content IContent parentContent = this.LoadContent(content.ParentLink, LanguageSelector.MasterLanguage()); //Create a new media item MediaData newMedia = this.GetDefaultContent(parentContent, contentType.ID, null) as MediaData; if (newMedia == null) { return(null); } newMedia.Name = content.Name; newMedia.RouteSegment = placeholderImage.RouteSegment; Blob blob = newMedia.BinaryData; //Create a writeable blob if none if (blob == null) { blob = this._blobFactory.CreateBlob(newMedia.BinaryDataContainer, this._placeholderManager.FileExtension); } //Generate placeholder using (Stream placeholder = this._placeholderManager.GetStream(placeholderImage.Width, placeholderImage.Height)) { //Assign placeholder stream to blob blob.Write(placeholder); } newMedia.BinaryData = blob; IEnumerable <ValidationError> validationFeedback = this._validationService.Validate(newMedia); //Check if there were any errors bool invalid = validationFeedback.Any(error => error.Severity == ValidationErrorSeverity.Error); SaveAction saveAction = SaveAction.None | (!invalid && !this._projectService.IsInProjectMode && this._siteConfigurationRepository.GetAutoPublishMediaOnUpload() ? SaveAction.Publish : SaveAction.Save); if (this._projectService.IsInProjectMode) { saveAction = saveAction | SaveAction.SkipSetCommonDraft; } newMedia.SetChangedOnPublish = this._settings.UIDefaultValueForSetChangedOnPublish; return(base.Save(newMedia, saveAction)); } return(base.Save(content, action)); }
public Product BuildKaChingProduct( ProductContent product, ICollection <string> tags, KachingConfiguration configuration, string skipVariantCode) { var kachingProduct = new Product(); kachingProduct.Id = product.Code.SanitizeKey(); kachingProduct.Barcode = GetPropertyStringValue(product, configuration.SystemMappings.BarcodeMetaField); kachingProduct.Name = _l10nStringFactory.GetLocalizedString(product, nameof(product.DisplayName)); kachingProduct.Description = _l10nStringFactory.GetLocalizedString(product, configuration.SystemMappings.DescriptionMetaField); foreach (var mapping in configuration.AttributeMappings.Cast <AttributeMappingElement>()) { object value = GetAttributeValue(product, mapping.MetaField); if (value == null) { continue; } kachingProduct.Attributes[mapping.AttributeId] = value; } /* ---------------------------- */ /* Example of dimension and dimension value construction from the Quicksilver site. */ /* ---------------------------- */ //var dimensions = new List<Dimension>(); //var sizeDimension = new Dimension(); //sizeDimension.Id = "Size"; //sizeDimension.Name = new L10nString("Size"); //sizeDimension.Values = new List<DimensionValue>(); //foreach (var size in product.AvailableSizes) //{ // var sizeValue = new DimensionValue(); // sizeValue.Id = size.ToLower().Replace(' ', '_'); // sizeValue.Name = new L10nString(size); // sizeDimension.Values.Add(sizeValue); //} //dimensions.Add(sizeDimension); //var colorDimension = new Dimension(); //colorDimension.Id = "Color"; //colorDimension.Name = new L10nString("Color"); //colorDimension.Values = new List<DimensionValue>(); //foreach (var color in product.AvailableColors) //{ // var colorValue = new DimensionValue(); // colorValue.Id = color.ToLower().Replace(' ', '_'); // colorValue.Name = new L10nString(color); // colorDimension.Values.Add(colorValue); //} //dimensions.Add(colorDimension); //kachingProduct.Dimensions = dimensions; CommerceMedia productImage = product.CommerceMediaCollection.FirstOrDefault(); if (productImage != null) { Uri absoluteUrl = GetAbsoluteUrl(productImage.AssetLink); kachingProduct.ImageUrl = absoluteUrl?.AbsoluteUri; } IEnumerable <ContentReference> variantRefs = _relationRepository .GetChildren <ProductVariation>(product.ContentLink) .Select(r => r.Child); ICollection <VariationContent> variants = _contentLoader .GetItems(variantRefs, LanguageSelector.MasterLanguage()) .OfType <VariationContent>() .ToArray(); if (variants.Count == 1 && configuration.ExportSingleVariantAsProduct) { // If the product has only one variant and ExportSingleVariantAsProduct is configured to true, // then put all variant properties on the product instead. var variant = variants.First(); kachingProduct.Id = variant.Code.SanitizeKey(); kachingProduct.Barcode = GetPropertyStringValue(variant, configuration.SystemMappings.BarcodeMetaField); kachingProduct.Name = _l10nStringFactory.GetLocalizedString(variant, nameof(variant.DisplayName)); MarketPrice retailPrice = MarketPriceForCode(variant.Code); AddProductPricing(kachingProduct, product, retailPrice, configuration.SystemMappings.PriceUnitMetaField); foreach (var mapping in configuration.AttributeMappings.Cast <AttributeMappingElement>()) { object value = GetAttributeValue(variant, mapping.MetaField); if (value == null) { continue; } kachingProduct.Attributes[mapping.AttributeId] = value; } if (kachingProduct.ImageUrl == null) { CommerceMedia variantImage = variant.CommerceMediaCollection.FirstOrDefault(); if (variantImage != null) { Uri absoluteUrl = GetAbsoluteUrl(variantImage.AssetLink); kachingProduct.ImageUrl = absoluteUrl?.AbsoluteUri; } } } else if (variants.Count > 0) { var kachingVariants = new List <Variant>(variants.Count); foreach (var variant in variants) { if (skipVariantCode != null && skipVariantCode == variant.Code) { continue; } var kachingVariant = new Variant(); kachingVariant.Id = variant.Code.SanitizeKey(); kachingVariant.Barcode = GetPropertyStringValue(variant, configuration.SystemMappings.BarcodeMetaField); var variantName = _l10nStringFactory.GetLocalizedString(variant, nameof(variant.DisplayName)); if (!variantName.Equals(kachingProduct.Name)) { kachingVariant.Name = variantName; } if (kachingProduct.UnitPricing == null) { kachingVariant.RetailPrice = MarketPriceForCode(variant.Code); } foreach (var mapping in configuration.AttributeMappings.Cast <AttributeMappingElement>()) { object value = GetAttributeValue(variant, mapping.MetaField); if (value == null) { continue; } kachingVariant.Attributes[mapping.AttributeId] = value; } CommerceMedia variantImage = variant.CommerceMediaCollection.FirstOrDefault(); if (variantImage != null) { Uri absoluteUrl = GetAbsoluteUrl(variantImage.AssetLink); kachingVariant.ImageUrl = absoluteUrl?.AbsoluteUri; } if (kachingProduct.ImageUrl == null) { kachingProduct.ImageUrl = kachingVariant.ImageUrl; } kachingVariants.Add(kachingVariant); } kachingProduct.Variants = kachingVariants; } /* ---------------------------- */ /* Assign tags to enable category navigation */ /* ---------------------------- */ kachingProduct.Tags = new Dictionary <string, bool>(); foreach (var tag in tags) { kachingProduct.Tags[tag] = true; } return(kachingProduct); }