public bool SubmitTranslateContent(ContentApiInstruction apiInstruction) { var content = _contentService.GetById(apiInstruction.NodeId); var allLanguages = _localizationService.GetAllLanguages(); var defaultLanguage = allLanguages.FirstOrDefault(x => x.IsoCode == DefaultLanguageCode); if (content != null) { _contentTranslationService.TranslateContentItem(apiInstruction, SubscriptionKey, UriBase, content, defaultLanguage); if (apiInstruction.IncludeDescendants) { int pageIndex = 0; int pageSize = 10; var totalRecords = _contentTranslationService.TranslatePageOfContentItems(apiInstruction, SubscriptionKey, UriBase, defaultLanguage, pageIndex, pageSize); if (totalRecords > pageSize) { pageIndex++; while (totalRecords >= pageSize * pageIndex + 1) { totalRecords = _contentTranslationService.TranslatePageOfContentItems(apiInstruction, SubscriptionKey, UriBase, defaultLanguage, pageIndex, pageSize); pageIndex++; } } } } return(true); }
public void RefreshNodeName(string tenantUid, string tenantName) { var home = TenantHelper.GetCurrentTenantHome(contentService, tenantUid); var children = contentService.GetByLevel(2).Where(x => x.ParentId == home.Id); try { foreach (var language in localizationService.GetAllLanguages()) { if (home.GetCultureName(language.IsoCode) == null) { home.SetCultureName(tenantName, language.IsoCode); } foreach (var child in children) { if (child.GetCultureName(language.IsoCode) == null) { child.SetCultureName($"{tenantName}-{language}", language.IsoCode); contentService.Save(child); } } } ConnectorContext.AuditService.Add(AuditType.Save, -1, home.Id, "Content Node", $"Children for {tenantName} have been refreshed"); } catch (Exception ex) { logger.Error(typeof(NodeHelper), ex.Message); logger.Error(typeof(NodeHelper), ex.StackTrace); throw; } }
public ActionResult Index(int?id = null) { var availableLanguages = _localizationService.GetAllLanguages(); if (id.HasValue) { var content = _umbracoContextAccessor.UmbracoContext.Content.GetById(true, id.Value); if (content is null) { return(HttpNotFound()); } availableLanguages = availableLanguages.Where(language => content.Cultures.ContainsKey(language.IsoCode)); } var model = new BackOfficePreviewModel(_features, _globalSettings, availableLanguages, _iconService); if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false) { var viewEngineResult = ViewEngines.Engines.FindPartialView(ControllerContext, model.PreviewExtendedHeaderView); if (viewEngineResult.View == null) { throw new InvalidOperationException("Could not find the view " + model.PreviewExtendedHeaderView + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations)); } } return(View(_globalSettings.Path.EnsureEndsWith('/') + "Views/Preview/" + "Index.cshtml", model)); }
public ActionResult Index(int?id = null) { var availableLanguages = _localizationService.GetAllLanguages(); if (id.HasValue) { var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); var content = umbracoContext.Content?.GetById(true, id.Value); if (content is null) { return(NotFound()); } availableLanguages = availableLanguages.Where(language => content.Cultures.ContainsKey(language.IsoCode)); } var model = new BackOfficePreviewModel(_features, availableLanguages); if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false) { var viewEngineResult = _viewEngines.FindView(ControllerContext, model.PreviewExtendedHeaderView !, false); if (viewEngineResult.View == null) { throw new InvalidOperationException("Could not find the view " + model.PreviewExtendedHeaderView + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations)); } } var viewPath = Path.Combine( _globalSettings.UmbracoPath, Constants.Web.Mvc.BackOfficeArea, ControllerExtensions.GetControllerName <PreviewController>() + ".cshtml") .Replace("\\", "/"); // convert to forward slashes since it's a virtual path return(View(viewPath, model)); }
public override void Up() { ILocalizationService localizationService = ApplicationContext.Current.Services.LocalizationService; IEnumerable <ILanguage> languages = localizationService.GetAllLanguages(); ILanguage language = languages.FirstOrDefault(x => x.IsoCode == "en-GB" || x.IsoCode == "en-US") ?? languages.FirstOrDefault(); if (language == null) { return; } IDictionaryItem dataAnnotations = localizationService.GetDictionaryItemByKey("DataAnnotions"); if (dataAnnotations != null) { return; } dataAnnotations = localizationService.CreateDictionaryItemWithIdentity("DataAnnotations", null); foreach (var item in defaultDictionaryItems) { if (localizationService.DictionaryItemExists(item.Key)) { continue; } localizationService.CreateDictionaryItemWithIdentity(item.Key, dataAnnotations.Key, item.Value); } }
public void AddCultureAndHostname(TenantDomain tenant, bool secureUrl) { const string protocolBase = "http"; var protocol = secureUrl ? $"{protocolBase}s" : protocolBase; try { var tenantRoot = nodeHelper.GetTenantRoot(tenant.TenantUid); var languages = localizationService.GetAllLanguages(); var subDomain = tenantRoot.GetValue <string>("subDomain"); string domainName = $"{protocol}://{subDomain}.{tenant.Domain}/"; var existingDomain = domainService.GetByName(domainName); if (Uri.IsWellFormedUriString(domainName, UriKind.RelativeOrAbsolute)) { if (existingDomain == null) { var defaultLanguageId = localizationService.GetDefaultLanguageId(); existingDomain = new UmbracoDomain(domainName) { LanguageId = defaultLanguageId, RootContentId = tenantRoot.Id }; domainService.Save(existingDomain); ConnectorContext.AuditService.Add(AuditType.New, -1, existingDomain.Id, "Language", $"Domain '{domainName}' for Tenant '{tenant.TenantUid}' has been created"); } foreach (var language in languages) { var localizedDomainName = $"{domainName}{language.IsoCode}"; var localizedDomain = domainService.GetByName(localizedDomainName); if (localizedDomain == null) { localizedDomain = new UmbracoDomain(localizedDomainName) { LanguageId = language.Id, RootContentId = tenantRoot.Id }; domainService.Save(localizedDomain); ConnectorContext.AuditService.Add(AuditType.New, -1, existingDomain.Id, "Language", $"Domain '{localizedDomainName}' for Tenant '{tenant.TenantUid}' has been created"); } } } } catch (Exception ex) { logger.Error(typeof(LanguageDictionaryService), ex.Message); logger.Error(typeof(LanguageDictionaryService), ex.StackTrace); throw; } }
public IEnumerable <Language> GetLanguages() { return(_localizationService.GetAllLanguages().Select(x => new Language { Name = x.CultureName, IsoCode = x.IsoCode.ToLower() })); }
// Umbraco.Code.MapAll -Icon -Trashed -Alias private void Map(IDictionaryItem source, DictionaryDisplay target, MapperContext context) { target.Id = source.Id; target.Key = source.Key; target.Name = source.ItemKey; target.ParentId = source.ParentId ?? Guid.Empty; target.Udi = Udi.Create(Constants.UdiEntityType.DictionaryItem, source.Key); if (_commonMapper != null) { target.ContentApps.AddRange(_commonMapper.GetContentAppsForEntity(source)); } // build up the path to make it possible to set active item in tree // TODO: check if there is a better way if (source.ParentId.HasValue) { var ids = new List <int> { -1 }; var parentIds = new List <int>(); GetParentId(source.ParentId.Value, _localizationService, parentIds); parentIds.Reverse(); ids.AddRange(parentIds); ids.Add(source.Id); target.Path = string.Join(",", ids); } else { target.Path = "-1," + source.Id; } // add all languages and the translations foreach (var lang in _localizationService.GetAllLanguages()) { var langId = lang.Id; var translation = source.Translations.FirstOrDefault(x => x.LanguageId == langId); target.Translations.Add(new DictionaryTranslationDisplay { IsoCode = lang.IsoCode, DisplayName = lang.CultureInfo.DisplayName, Translation = (translation != null) ? translation.Value : string.Empty, LanguageId = lang.Id }); } }
/// <summary> /// Ensure that the correct English variant context is being used. /// </summary> private void EnsureEnglishVariantContext() { var englishLanguage = _localizationService.GetAllLanguages()?.FirstOrDefault(l => l.IsoCode.InvariantStartsWith("en")); if (englishLanguage != null) { _variantContextAccessor.VariationContext = new VariationContext(englishLanguage.IsoCode); } }
public IEnumerable <DataListItem> GetItems(Dictionary <string, object> config) { return(_localizationService .GetAllLanguages() .Select(x => new DataListItem { Name = x.CultureName, Value = x.IsoCode, Icon = UmbConstants.Icons.Language, Description = x.IsoCode, })); }
private IEnumerable <ContentEditing.Language> GetLanguages(MapperContext context) { var allLanguages = _localizationService.GetAllLanguages().OrderBy(x => x.Id).ToList(); if (allLanguages.Count == 0) { // This should never happen return(Enumerable.Empty <ContentEditing.Language>()); } return(context.MapEnumerable <ILanguage, ContentEditing.Language>(allLanguages).WhereNotNull().ToList()); }
public IEnumerable <ContentVariantDisplay> Resolve(IContent source, ContentItemDisplay destination, IEnumerable <ContentVariantDisplay> destMember, ResolutionContext context) { var result = new List <ContentVariantDisplay>(); if (!source.ContentType.VariesByCulture()) { //this is invariant so just map the IContent instance to ContentVariationDisplay result.Add(context.Mapper.Map <ContentVariantDisplay>(source)); } else { var allLanguages = _localizationService.GetAllLanguages().OrderBy(x => x.Id).ToList(); if (allLanguages.Count == 0) { return(Enumerable.Empty <ContentVariantDisplay>()); //this should never happen } var langs = context.Mapper.Map <IEnumerable <ILanguage>, IEnumerable <Language> >(allLanguages, null, context).ToList(); //create a variant for each language, then we'll populate the values var variants = langs.Select(x => { //We need to set the culture in the mapping context since this is needed to ensure that the correct property values //are resolved during the mapping context.Options.SetCulture(x.IsoCode); return(context.Mapper.Map <IContent, ContentVariantDisplay>(source, null, context)); }).ToList(); for (int i = 0; i < langs.Count; i++) { var x = langs[i]; var variant = variants[i]; variant.Language = x; variant.Name = source.GetCultureName(x.IsoCode); } //Put the default language first in the list & then sort rest by a-z var defaultLang = variants.SingleOrDefault(x => x.Language.IsDefault); //Remove the default language from the list for now variants.Remove(defaultLang); //Sort the remaining languages a-z variants = variants.OrderBy(x => x.Name).ToList(); //Insert the default language as the first item variants.Insert(0, defaultLang); return(variants); } return(result); }
/// <inheritdoc /> public virtual ISet <string> GetBackOfficeDocumentFieldsToLoad() { var fields = _backOfficeDocumentFieldsToLoad; // We need to load all nodeName_* fields but we won't know those up front so need to get // all langs (this is cached) foreach (var field in _localizationService.GetAllLanguages().Select(x => "nodeName_" + x.IsoCode.ToLowerInvariant())) { fields.Add(field); } return(fields); }
public HeaderConfiguration GetHeaderConfiguration(IPublishedContent content = null) { HeaderConfiguration headerConfig = null; var branch = content?.AncestorsOrSelf().ToList(); var index = 0; if (branch != null) { do { headerConfig = branch[index].HasValue(DocumentTypes.BasePage.Fields.HeaderConfiguration) ? new HeaderConfiguration(branch[index].Value <IEnumerable <IPublishedElement> >(DocumentTypes.BasePage.Fields.HeaderConfiguration).FirstOrDefault()) : null; index++; } while (index < branch.Count() && headerConfig == null); } if (headerConfig != null) { return new HeaderConfiguration(headerConfig) { NavigationItems = _navigationService.GetNavigation(), Logo = _imageService.GetImage(headerConfig.Value <IPublishedContent>(DocumentTypes.Configuration.Logo), height: 100), Languages = _localizationService.GetAllLanguages() .Where(l => !Equals(l.CultureInfo, CultureInfo.CurrentCulture)) .Select(a => new Language() { Name = a.CultureInfo.NativeName.Split(' ')[0], ISO = a.CultureInfo.TwoLetterISOLanguageName }), GlobalSlogan = GetGlobalSlogan() } } ; return(null); }
internal override SyncAttempt <IDictionaryItem> DeserializeCore(XElement node) { // var items = _packagingService.ImportDictionaryItems(node); // var item = items.LastOrDefault(); var langs = _localizationService.GetAllLanguages().ToList(); var item = UpdateDictionaryValues(node, null, langs); return(SyncAttempt <IDictionaryItem> .SucceedIf( item != null, item != null?item.ItemKey : node.NameFromNode(), item, ChangeType.Import)); }
// GET: LanguageSwitcher public ActionResult Index(IEnumerable <PictureLink> pictureLinks = null) { var languages = _localizationService.GetAllLanguages() .Where(l => l.CultureInfo.TwoLetterISOLanguageName != CultureInfo.CurrentCulture.TwoLetterISOLanguageName) .Select(l => new Language() { ISO = l.IsoCode, Name = l.CultureInfo.NativeName.Split(' ')[0].ToUpperInvariant(), Url = Umbraco.Content(CurrentPage.Id).Url(l.IsoCode, UrlMode.Absolute) }); return(View("~/Views/Partials/LanguageSwitcher.cshtml", new LanguageSwitcherModel() { Languages = languages })); }
public JsonResult Create(AuditDictionaryItem item) { var languages = localizationService.GetAllLanguages(); var mainLanguage = localizationService.GetDefaultLanguageIsoCode(); var ok = false; var mainLanguageDictionary = new ImportExportDictionaryItem { Key = item.Key, ParentKey = item.ParentKey, Value = string.Empty, LanguageCode = mainLanguage }; mainLanguageDictionary.Translations = new Dictionary <string, string>(); if (!languageDictionaryService.ParentExists(item.ParentKey)) { var parentDictionaryItem = new ImportExportDictionaryItem { Key = item.ParentKey, Value = item.Key, LanguageCode = mainLanguage, Translations = new Dictionary <string, string>() }; languageDictionaryService.CreateDictionaryItem(parentDictionaryItem); } foreach (var language in languages) { if (language.IsoCode != mainLanguage) { mainLanguageDictionary.Translations.Add(language.IsoCode, string.Empty); } } var result = languageDictionaryService.CreateDictionaryItem(mainLanguageDictionary); if (result.Item2) { ok = true; } else { ok = false; } return(base.Json(new { Created = ok }, JsonRequestBehavior.DenyGet)); }
public ActionResult Index() { var availableLanguages = _localizationService.GetAllLanguages(); var model = new BackOfficePreviewModel(_features, _globalSettings, availableLanguages, _iconService); if (model.PreviewExtendedHeaderView.IsNullOrWhiteSpace() == false) { var viewEngineResult = ViewEngines.Engines.FindPartialView(ControllerContext, model.PreviewExtendedHeaderView); if (viewEngineResult.View == null) { throw new InvalidOperationException("Could not find the view " + model.PreviewExtendedHeaderView + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations)); } } return(View(_globalSettings.Path.EnsureEndsWith('/') + "Views/Preview/" + "Index.cshtml", model)); }
private async Task <SyncCommandResult> List() { var languages = localizationService.GetAllLanguages(); await writer.WriteLineAsync("Language\tDefault"); await writer.WriteLineAsync("----------------------------"); foreach (var lang in languages) { await writer.WriteLineAsync( string.Format("- {0}\t\t{1}", lang.IsoCode, lang.IsDefault ? " #" : "")); } return(SyncCommandResult.Success); }
private void UpdateLanguages(IDictionaryItem item, IDictionary <string, string> values) { var languages = LocalizationService .GetAllLanguages() .ToArray(); foreach (var value in values) { var language = languages.FirstOrDefault(x => x.CultureInfo.Name == value.Key); if (language == null) { continue; } LocalizationService.AddOrUpdateDictionaryValue(item, language, value.Value); } }
/// <summary> /// Get a list of SelectListItem from the children of a dictionary key /// </summary> /// <param name="parentKey">Parent Dictionary Key</param> /// <param name="language">Two Letter ISO Language Name (e.g. en, ar, fr)</param> /// <returns></returns> public List <SelectListItem> GetDictionaryList(string parentKey, string language = null) { var result = new List <SelectListItem>(); try { //Get the dictionary item var dictionaryParent = _localizationService.GetDictionaryItemByKey(parentKey); //Check if dictionary exist if (dictionaryParent != null) { //Get the children of the dictionary item var childItems = _localizationService.GetDictionaryItemChildren(dictionaryParent.Key); if (childItems != null && childItems.Any()) { //Get the current language var currentLanguage = language ?? CultureInfo.CurrentCulture.TwoLetterISOLanguageName; var languages = _localizationService.GetAllLanguages(); var languageCode = languages.FirstOrDefault(x => x.CultureInfo.TwoLetterISOLanguageName.ToLower() == currentLanguage.Replace(" ", string.Empty).ToLower()); foreach (var item in childItems.OrderBy(x => x.ItemKey)) { var listItem = new SelectListItem(); listItem.Value = item.ItemKey; listItem.Text = item.Translations.FirstOrDefault(x => x.Language.IsoCode == languageCode.CultureInfo.Name).Value; result.Add(listItem); } } } } catch (Exception ex) { _logger.Error <List <SelectListItem> >("GetDictionaryChildren Error: ", ex); } return(result); }
/// <summary> /// Get Dictionary<string, string> from the children of a dictionary key /// </summary> /// <param name="parentKey">Parent Dictionary Key</param> /// <param name="language">Two Letter ISO Language Name (e.g. en, ar, fr)</param> /// <returns></returns> public Dictionary <string, string> GetDictionaryList(string parentKey, string language = null) { var result = new Dictionary <string, string>(); try { //Get the dictionary item var dictionaryParent = _localizationService.GetDictionaryItemByKey(parentKey); //Check if dictionary exist if (dictionaryParent != null) { //Get the children of the dictionary item var childItems = _localizationService.GetDictionaryItemChildren(dictionaryParent.Key); if (childItems != null && childItems.Any()) { //Get all the languages available var languages = _localizationService.GetAllLanguages(); //Get the current language var currentLanguage = language ?? CultureInfo.CurrentCulture.TwoLetterISOLanguageName; //Get the current language code var languageCode = languages.FirstOrDefault(x => x.CultureInfo.TwoLetterISOLanguageName.ToLower() == currentLanguage.Replace(" ", string.Empty).ToLower()); //Add the items into a dictionary foreach (var item in childItems.OrderBy(x => x.ItemKey)) { result.Add(item.ItemKey, item.Translations.FirstOrDefault(x => x.Language.IsoCode == languageCode.CultureInfo.Name).Value); } } } } catch (Exception ex) { _logger.Error <Dictionary <string, string> > ("GetDictionaryList Error: ", ex); } return(result); }
private IContent CreateSiteRoot(IContentService contentService, IContent siteContainer, IDomainService domainService, ILocalizationService localizationService, string domain) { var siteRoot = contentService.CreateAndSave("Website", siteContainer.Id, SiteRoot.ModelTypeAlias); // add hostname var language = localizationService.GetAllLanguages().First(); if (domainService.GetByName(domain) != null) { domain = $"{domain}/{siteContainer.Name}"; } domainService.Save(new UmbracoDomain(domain) { LanguageId = language.Id, RootContentId = siteRoot.Id, DomainName = domain }); return(siteRoot); }
private static CultureInfo GetDefaultCulture(ILocalizationService localizationService) { var defaultLanguage = localizationService.GetAllLanguages().FirstOrDefault(); return(defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode)); }
public void Render(int pageId, int?altTemplateId, StringWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } // instantiate a request and process // important to use CleanedUmbracoUrl - lowercase path-only version of the current url, though this isn't going to matter // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually. var contentRequest = _publishedRouter.CreateRequest(_umbracoContextAccessor.UmbracoContext); var doc = contentRequest.UmbracoContext.ContentCache.GetById(pageId); if (doc == null) { writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", pageId); return; } //in some cases the UmbracoContext will not have a PublishedRequest assigned to it if we are not in the //execution of a front-end rendered page. In this case set the culture to the default. //set the culture to the same as is currently rendering if (_umbracoContextAccessor.UmbracoContext.PublishedRequest == null) { var defaultLanguage = _languageService.GetAllLanguages().FirstOrDefault(); contentRequest.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : defaultLanguage.CultureInfo; } else { contentRequest.Culture = _umbracoContextAccessor.UmbracoContext.PublishedRequest.Culture; } //set the doc that was found by id contentRequest.PublishedContent = doc; //set the template, either based on the AltTemplate found or the standard template of the doc var templateId = _webRoutingSection.DisableAlternativeTemplates || !altTemplateId.HasValue ? doc.TemplateId : altTemplateId.Value; if (templateId.HasValue) { contentRequest.TemplateModel = _fileService.GetTemplate(templateId.Value); } //if there is not template then exit if (contentRequest.HasTemplate == false) { if (altTemplateId.HasValue == false) { writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId); } else { writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", altTemplateId); } return; } //First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these //after this page has rendered. SaveExistingItems(out var oldPublishedRequest, out var oldAltTemplate); try { //set the new items on context objects for this templates execution SetNewItemsOnContextObjects(contentRequest); //Render the template ExecuteTemplateRendering(writer, contentRequest); } finally { //restore items on context objects to continuing rendering the parent template RestoreItems(oldPublishedRequest, oldAltTemplate); } }
public IEnumerable <Language> GetAllLanguages() { var allLanguages = _localizationService.GetAllLanguages(); return(_umbracoMapper.Map <IEnumerable <ILanguage>, IEnumerable <Language> >(allLanguages)); }
public DictionaryMapperProfile(ILocalizationService localizationService) { CreateMap <IDictionaryItem, DictionaryDisplay>() .ForMember(x => x.Translations, expression => expression.Ignore()) .ForMember(x => x.Notifications, expression => expression.Ignore()) .ForMember(x => x.Icon, expression => expression.Ignore()) .ForMember(x => x.Trashed, expression => expression.Ignore()) .ForMember(x => x.Alias, expression => expression.Ignore()) .ForMember(x => x.Path, expression => expression.Ignore()) .ForMember(x => x.AdditionalData, expression => expression.Ignore()) .ForMember( x => x.Udi, expression => expression.MapFrom( content => Udi.Create(Constants.UdiEntityType.DictionaryItem, content.Key))).ForMember( x => x.Name, expression => expression.MapFrom(content => content.ItemKey)) .AfterMap( (src, dest) => { // build up the path to make it possible to set active item in tree // TODO check if there is a better way if (src.ParentId.HasValue) { var ids = new List <int> { -1 }; var parentIds = new List <int>(); this.GetParentId(src.ParentId.Value, localizationService, parentIds); parentIds.Reverse(); ids.AddRange(parentIds); ids.Add(src.Id); dest.Path = string.Join(",", ids); } else { dest.Path = "-1," + src.Id; } // add all languages and the translations foreach (var lang in localizationService.GetAllLanguages()) { var langId = lang.Id; var translation = src.Translations.FirstOrDefault(x => x.LanguageId == langId); dest.Translations.Add(new DictionaryTranslationDisplay { IsoCode = lang.IsoCode, DisplayName = lang.CultureInfo.DisplayName, Translation = (translation != null) ? translation.Value : string.Empty, LanguageId = lang.Id }); } }); CreateMap <IDictionaryItem, DictionaryOverviewDisplay>() .ForMember(dest => dest.Level, expression => expression.Ignore()) .ForMember(dest => dest.Translations, expression => expression.Ignore()) .ForMember( x => x.Name, expression => expression.MapFrom(content => content.ItemKey)) .AfterMap( (src, dest) => { // add all languages and the translations foreach (var lang in localizationService.GetAllLanguages()) { var langId = lang.Id; var translation = src.Translations.FirstOrDefault(x => x.LanguageId == langId); dest.Translations.Add( new DictionaryOverviewTranslationDisplay { DisplayName = lang.CultureInfo.DisplayName, HasTranslation = translation != null && string.IsNullOrEmpty(translation.Value) == false }); } }); }
private bool BuildQuery(StringBuilder sb, string query, string searchFrom, List <string> fields, string type) { //build a lucene query: // the nodeName will be boosted 10x without wildcards // then nodeName will be matched normally with wildcards // the rest will be normal without wildcards var allLangs = _languageService.GetAllLanguages().Select(x => x.IsoCode.ToLowerInvariant()).ToList(); //check if text is surrounded by single or double quotes, if so, then exact match var surroundedByQuotes = Regex.IsMatch(query, "^\".*?\"$") || Regex.IsMatch(query, "^\'.*?\'$"); if (surroundedByQuotes) { //strip quotes, escape string, the replace again query = query.Trim('\"', '\''); query = Lucene.Net.QueryParsers.QueryParser.Escape(query); //nothing to search if (searchFrom.IsNullOrWhiteSpace() && query.IsNullOrWhiteSpace()) { return(false); } //update the query with the query term if (query.IsNullOrWhiteSpace() == false) { //add back the surrounding quotes query = string.Format("{0}{1}{0}", "\"", query); sb.Append("+("); AppendNodeNamePhraseWithBoost(sb, query, allLangs); foreach (var f in fields) { //additional fields normally sb.Append(f); sb.Append(": ("); sb.Append(query); sb.Append(") "); } sb.Append(") "); } } else { var trimmed = query.Trim(new[] { '\"', '\'' }); //nothing to search if (searchFrom.IsNullOrWhiteSpace() && trimmed.IsNullOrWhiteSpace()) { return(false); } //update the query with the query term if (trimmed.IsNullOrWhiteSpace() == false) { query = Lucene.Net.QueryParsers.QueryParser.Escape(query); var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); sb.Append("+("); AppendNodeNameExactWithBoost(sb, query, allLangs); AppendNodeNameWithWildcards(sb, querywords, allLangs); foreach (var f in fields) { var queryWordsReplaced = new string[querywords.Length]; // when searching file names containing hyphens we need to replace the hyphens with spaces if (f.Equals(UmbracoExamineIndex.UmbracoFileFieldName)) { for (var index = 0; index < querywords.Length; index++) { queryWordsReplaced[index] = querywords[index].Replace("\\-", " ").Replace("_", " ").Trim(" "); } } else { queryWordsReplaced = querywords; } //additional fields normally sb.Append(f); sb.Append(":"); sb.Append("("); foreach (var w in queryWordsReplaced) { sb.Append(w.ToLower()); sb.Append("* "); } sb.Append(")"); sb.Append(" "); } sb.Append(") "); } } //must match index type sb.Append("+__IndexType:"); sb.Append(type); return(true); }
/// <summary> /// Gets the Urls of the content item. /// </summary> /// <remarks> /// <para>Use when displaying Urls. If errors occur when generating the Urls, they will show in the list.</para> /// <para>Contains all the Urls that we can figure out (based upon domains, etc).</para> /// </remarks> public static IEnumerable <UrlInfo> GetContentUrls(this IContent content, PublishedRouter publishedRouter, UmbracoContext umbracoContext, ILocalizationService localizationService, ILocalizedTextService textService, IContentService contentService, ILogger logger) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (publishedRouter == null) { throw new ArgumentNullException(nameof(publishedRouter)); } if (umbracoContext == null) { throw new ArgumentNullException(nameof(umbracoContext)); } if (localizationService == null) { throw new ArgumentNullException(nameof(localizationService)); } if (textService == null) { throw new ArgumentNullException(nameof(textService)); } if (contentService == null) { throw new ArgumentNullException(nameof(contentService)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (content.Published == false) { yield return(UrlInfo.Message(textService.Localize("content/itemNotPublished"))); yield break; } // build a list of urls, for the back-office // which will contain // - the 'main' urls, which is what .Url would return, for each culture // - the 'other' urls we know (based upon domains, etc) // // need to work through each installed culture: // on invariant nodes, each culture returns the same url segment but, // we don't know if the branch to this content is invariant, so we need to ask // for URLs for all cultures. // and, not only for those assigned to domains in the branch, because we want // to show what GetUrl() would return, for every culture. var urls = new HashSet <UrlInfo>(); var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList(); //get all URLs for all cultures //in a HashSet, so de-duplicates too foreach (var cultureUrl in GetContentUrlsByCulture(content, cultures, publishedRouter, umbracoContext, contentService, textService, logger)) { urls.Add(cultureUrl); } //return the real urls first, then the messages foreach (var urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key)) { //in some cases there will be the same URL for multiple cultures: // * The entire branch is invariant // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed foreach (var dUrl in urlGroup.DistinctBy(x => x.Text.ToUpperInvariant()).OrderBy(x => x.Text).ThenBy(x => x.Culture)) { yield return(dUrl); } } // get the 'other' urls - ie not what you'd get with GetUrl() but urls that would route to the document, nevertheless. // for these 'other' urls, we don't check whether they are routable, collide, anything - we just report them. foreach (var otherUrl in umbracoContext.UrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text).ThenBy(x => x.Culture)) { if (urls.Add(otherUrl)) //avoid duplicates { yield return(otherUrl); } } }
/// <summary> /// Gets the URLs of the content item. /// </summary> /// <remarks> /// <para>Use when displaying URLs. If errors occur when generating the URLs, they will show in the list.</para> /// <para>Contains all the URLs that we can figure out (based upon domains, etc).</para> /// </remarks> public static async Task <IEnumerable <UrlInfo> > GetContentUrlsAsync( this IContent content, IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, ILocalizationService localizationService, ILocalizedTextService textService, IContentService contentService, IVariationContextAccessor variationContextAccessor, ILogger <IContent> logger, UriUtility uriUtility, IPublishedUrlProvider publishedUrlProvider) { ArgumentNullException.ThrowIfNull(content); ArgumentNullException.ThrowIfNull(publishedRouter); ArgumentNullException.ThrowIfNull(umbracoContext); ArgumentNullException.ThrowIfNull(localizationService); ArgumentNullException.ThrowIfNull(textService); ArgumentNullException.ThrowIfNull(contentService); ArgumentNullException.ThrowIfNull(variationContextAccessor); ArgumentNullException.ThrowIfNull(logger); ArgumentNullException.ThrowIfNull(uriUtility); ArgumentNullException.ThrowIfNull(publishedUrlProvider); var result = new List <UrlInfo>(); if (content.Published == false) { result.Add(UrlInfo.Message(textService.Localize("content", "itemNotPublished"))); return(result); } // build a list of URLs, for the back-office // which will contain // - the 'main' URLs, which is what .Url would return, for each culture // - the 'other' URLs we know (based upon domains, etc) // // need to work through each installed culture: // on invariant nodes, each culture returns the same URL segment but, // we don't know if the branch to this content is invariant, so we need to ask // for URLs for all cultures. // and, not only for those assigned to domains in the branch, because we want // to show what GetUrl() would return, for every culture. var urls = new HashSet <UrlInfo>(); var cultures = localizationService.GetAllLanguages().Select(x => x.IsoCode).ToList(); // get all URLs for all cultures // in a HashSet, so de-duplicates too foreach (UrlInfo cultureUrl in await GetContentUrlsByCultureAsync(content, cultures, publishedRouter, umbracoContext, contentService, textService, variationContextAccessor, logger, uriUtility, publishedUrlProvider)) { urls.Add(cultureUrl); } // return the real URLs first, then the messages foreach (IGrouping <bool, UrlInfo> urlGroup in urls.GroupBy(x => x.IsUrl).OrderByDescending(x => x.Key)) { // in some cases there will be the same URL for multiple cultures: // * The entire branch is invariant // * If there are less domain/cultures assigned to the branch than the number of cultures/languages installed if (urlGroup.Key) { result.AddRange(urlGroup.DistinctBy(x => x.Text, StringComparer.OrdinalIgnoreCase).OrderBy(x => x.Text).ThenBy(x => x.Culture)); } else { result.AddRange(urlGroup); } } // get the 'other' URLs - ie not what you'd get with GetUrl() but URLs that would route to the document, nevertheless. // for these 'other' URLs, we don't check whether they are routable, collide, anything - we just report them. foreach (UrlInfo otherUrl in publishedUrlProvider.GetOtherUrls(content.Id).OrderBy(x => x.Text).ThenBy(x => x.Culture)) { // avoid duplicates if (urls.Add(otherUrl)) { result.Add(otherUrl); } } return(result); }