示例#1
0
        protected virtual IEnumerable <Entity> FindForums(OrganizationServiceContext context, Entity website, Entity webpage)
        {
            var forumsInCurrentWebsite = context.CreateQuery("adx_communityforum")
                                         .Where(e => e.GetAttributeValue <EntityReference>("adx_websiteid") == website.ToEntityReference());

            EntityReference rootPage = webpage.ToEntityReference();

            ContextLanguageInfo languageInfo = HttpContext.Current.GetContextLanguageInfo();

            IEnumerable <Entity> forums = null;

            if (languageInfo.IsCrmMultiLanguageEnabled)
            {
                if (!webpage.GetAttributeAliasedValue <bool>("adx_isroot") && webpage.GetAttributeAliasedValue <EntityReference>("adx_rootwebpageid") != null)
                {
                    rootPage = webpage.GetAttributeAliasedValue <EntityReference>("adx_rootwebpageid");
                }

                forums = forumsInCurrentWebsite
                         .Where(e => e.GetAttributeValue <EntityReference>("adx_parentpageid") == rootPage &&
                                (e.GetAttributeValue <EntityReference>("adx_websitelanguageid") == null ||
                                 e.GetAttributeValue <EntityReference>("adx_websitelanguageid") == languageInfo.ContextLanguage.EntityReference)
                                );
            }
            else
            {
                forums = forumsInCurrentWebsite
                         .Where(e => e.GetAttributeValue <EntityReference>("adx_parentpageid") == webpage.ToEntityReference());
            }

            return(forums.ToList());
        }
        protected bool TryGetLanguageCode(out ContextLanguageInfo websiteLanguage)
        {
            var contextLanguage = HttpContext.Current.GetContextLanguageInfo();

            websiteLanguage = contextLanguage;
            return(contextLanguage.IsCrmMultiLanguageEnabled);
        }
        public Snippet(Entity entity, IPortalViewEntity viewEntity, ContextLanguageInfo language)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (viewEntity == null)
            {
                throw new ArgumentNullException("viewEntity");
            }

            if (language == null)
            {
                throw new ArgumentNullException("language");
            }

            Entity      = entity;
            Name        = entity.GetAttributeValue <string>("adx_name");
            Value       = viewEntity.GetAttribute("adx_value");
            DisplayName = entity.GetAttributeValue <string>("adx_display_name");

            // set the language name value - fails if the solutions have not been updated, so set LanguageName to null
            this.LanguageName = GetLanguageName(entity, language);
        }
        /// <summary>
        /// Renders localized script tags for the following paths.
        /// </summary>
        /// <param name="paths">Set of virtual paths for which to generate script tags.</param>
        /// <returns>The HTML string containing the script tag or tags for the bundle.</returns>
        public static IHtmlString Render(params string[] paths)
        {
            var bundles = BundleTable.Bundles;
            var current = CultureInfo.CurrentCulture;

            return(Scripts.Render(paths.Select(path => GetLocalizedBundleName(path, ContextLanguageInfo.ResolveCultureLcid(current.LCID))).ToArray()));
        }
        protected bool TryGetLanguageCode(out ContextLanguageInfo contextLanguageInfo)
        {
            var contextLanguage = this.HttpContext.GetContextLanguageInfo();

            contextLanguageInfo = contextLanguage;
            return(contextLanguage.IsCrmMultiLanguageEnabled);
        }
示例#6
0
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var route = GetRoute(GetApplicationPathForSiteMarker(httpContext));

            if (route == null)
            {
                return(null);
            }

            HttpContextBase  mockHttpContext = httpContext;
            bool             pathHasLanguageCode;
            IWebsiteLanguage websiteLangauge;                   // multilanguage is enabled if we find a language
            string           pathWithoutLanguageCode = ContextLanguageInfo.StripLanguageCodeFromAbsolutePath(httpContext, out pathHasLanguageCode, out websiteLangauge);

            if (websiteLangauge != null && pathHasLanguageCode)
            {
                var         urlWithoutLanguageCode = httpContext.Request.Url.GetLeftPart(UriPartial.Authority) + pathWithoutLanguageCode;
                HttpRequest request = new HttpRequest(httpContext.Request.FilePath, urlWithoutLanguageCode, httpContext.Request.Url.Query);
                mockHttpContext = new MockRequestHttpContext(new HttpRequestWrapper(request));
            }

            var routeData = route.GetRouteData(mockHttpContext);

            return(routeData == null
                                ? null
                                : WrapRouteData(routeData));
        }
 /// <summary>
 /// Figures out whether the given web page is a translated content WebPage and its language matches the current active portal language.
 /// If multi-language is not enabled, then true will always be returned.
 /// </summary>
 /// <param name="page">WebPageNode to check.</param>
 /// <param name="langContext">The language context.</param>
 /// <returns>Whether the given web page matches the current active portal language.</returns>
 private bool IsValidLanguageContentPage(WebPageNode page, ContextLanguageInfo langContext)
 {
     if (langContext.IsCrmMultiLanguageEnabled)
     {
         return(page.IsRoot != true && page.WebPageLanguage != null && page.WebPageLanguage.Id == langContext.ContextLanguage.EntityReference.Id);
     }
     return(true);
 }
示例#8
0
        public IdentityErrorDescriber(IContentMapProvider contentMapProvider, ContextLanguageInfo language)
        {
            if (contentMapProvider == null)
            {
                throw new ArgumentNullException("contentMapProvider");
            }

            this.ContentMapProvider = contentMapProvider;
            this.Language           = language;
        }
示例#9
0
        /// <summary> The try get language specific attribute value. </summary>
        /// <param name="startingNode"> The starting node. </param>
        /// <param name="languageCode"> The language code. </param>
        /// <param name="elementValue"> The element value. </param>
        /// <param name="baseOrgLanguageCode"> The base org language code. </param>
        /// <returns> The <see cref="bool"/>. </returns>
        public static bool TryGetLanguageSpecificLabelValue(this XNode startingNode, int languageCode, out string elementValue, int baseOrgLanguageCode = 0)
        {
            var lcid = ContextLanguageInfo.ResolveCultureLcid(languageCode);

            if (TryGetAttributeValue(startingNode, string.Format("labels/label[@languagecode='{0}']", lcid), "description", out elementValue))
            {
                return(true);
            }

            return(TryGetAttributeValue(startingNode, string.Format("labels/label[@languagecode='{0}']", baseOrgLanguageCode), "description", out elementValue));
        }
示例#10
0
        /// <summary>
        /// Set the culture for the request.
        /// </summary>
        /// <param name="app">The app.</param>
        public static void UseCurrentThreadCulture(this IAppBuilder app)
        {
            app.Use((context, next) =>
            {
                var websiteLanguage = ContextLanguageInfo.ResolveContextLanguage(context.Get <HttpContextBase>(typeof(HttpContextBase).FullName));

                if (websiteLanguage != null)
                {
                    ContextLanguageInfo.SetCultureInfo(websiteLanguage.Lcid);
                }

                return(next.Invoke());
            });
        }
示例#11
0
        private static IHtmlString Breadcrumb(Func <IEnumerable <Tuple <SiteMapNode, SiteMapNodeType> > > getSiteMapPath)
        {
            var path = getSiteMapPath().ToList();

            if (!path.Any())
            {
                return(null);
            }

            var items = new StringBuilder();

            foreach (var node in path)
            {
                var li = new TagBuilder("li");

                if (node.Item2 == SiteMapNodeType.Current)
                {
                    li.AddCssClass("active");
                    li.SetInnerText(node.Item1.Title);
                }
                else
                {
                    var breadCrumbUrl = node.Item1.Url;

                    if (ContextLanguageInfo.IsCrmMultiLanguageEnabledInWebsite(PortalContext.Current.Website) &&
                        ContextLanguageInfo.DisplayLanguageCodeInUrl)
                    {
                        breadCrumbUrl = ContextLanguageInfo
                                        .PrependLanguageCode(ApplicationPath.Parse(node.Item1.Url))
                                        .AbsolutePath;
                    }

                    var a = new TagBuilder("a");

                    a.Attributes["href"] = breadCrumbUrl;
                    a.SetInnerText(node.Item1.Title);

                    li.InnerHtml += a.ToString();
                }

                items.AppendLine(li.ToString());
            }

            var ul = new TagBuilder("ul");

            ul.AddCssClass("breadcrumb");
            ul.InnerHtml += items.ToString();

            return(new HtmlString(ul.ToString()));
        }
示例#12
0
        /// <summary> Initializes a new instance of the <see cref="ContentMapDataAdapter"/> class. </summary>
        /// <param name="contentMapProvider"> The content map provider. </param>
        /// <param name="language"> The language. </param>
        /// <param name="dependencies"> The dependencies. </param>
        protected ContentMapDataAdapter(IContentMapProvider contentMapProvider, ContextLanguageInfo language, IDataAdapterDependencies dependencies)
        {
            if (contentMapProvider == null)
            {
                throw new ArgumentNullException("contentMapProvider");
            }
            if (dependencies == null)
            {
                throw new ArgumentNullException("dependencies");
            }

            this.ContentMapProvider = contentMapProvider;
            this.Dependencies       = dependencies;
            this.Language           = language;
        }
        protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            // Set the culture of the current request's thread to the current website's language.
            // This is necessary in .NET 4.6 and above because the current thread doesn't retain the
            // thread culture set within the Site.Startup OWIN middleware.
            // https://stackoverflow.com/questions/36455801/owinmiddleware-doesnt-preserve-culture-change-in-net-4-6
            // https://connect.microsoft.com/VisualStudio/feedback/details/2455357
            // https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.110).aspx#Async
            // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-culture-and-asynchronous-operations
            var languageContext = Context.GetContextLanguageInfo();

            if (languageContext?.ContextLanguage != null)
            {
                ContextLanguageInfo.SetCultureInfo(languageContext.ContextLanguage.Lcid);
            }
        }
        /// <summary>
        /// Updates current language based on the changed user preference.
        /// </summary>
        /// <param name="preferredLanguage">Newest language preference for the user (Portal Language). Null if preference not set.</param>
        /// <param name="languageContext">Instance of the current <see cref="ContextLanguageInfo"/>.</param>
        private void UpdateCurrentLanguage(EntityReference preferredLanguage, ContextLanguageInfo languageContext)
        {
            if (languageContext.IsCrmMultiLanguageEnabled)
            {
                var websiteLangauges   = languageContext.ActiveWebsiteLanguages.ToArray();
                var newWebsiteLanguage = preferredLanguage == null
                                        ? languageContext.DefaultLanguage
                                        : languageContext.GetWebsiteLanguageByPortalLanguageId(preferredLanguage.Id, websiteLangauges, true);

                if (languageContext.ContextLanguage != newWebsiteLanguage)
                {
                    // redirect is always required to apply a language change
                    _forceRedirect = true;
                }
            }
        }
        public ActionResult ResourceManager()
        {
            var    languageFormat = "lang={0}";
            string fallbackCode;
            string code = this.HttpContext.Request.QueryString["lang"];

            if (!string.IsNullOrWhiteSpace(code) && ContextLanguageInfo.ResolveCultureCode(code, out fallbackCode))
            {
                var current = this.Request.QueryString["lang"];
                var url     = this.Request.Url.AbsoluteUri.Replace(string.Format(languageFormat, current), string.Format(languageFormat, fallbackCode));
                return(this.Redirect(url));
            }

            Response.Cache.SetOmitVaryStar(true);
            Response.ContentType = "text/javascript";
            return(View("ResourceManager"));
        }
示例#16
0
        /// <summary>Try to apply the special case.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="dependencies">The dependencies.</param>
        /// <param name="customParameters">The custom parameters.</param>
        /// <param name="fetch">The fetch.</param>
        /// <returns>True if applied, false otherwise.</returns>
        public bool TryApply(IViewConfiguration configuration, IDataAdapterDependencies dependencies, IDictionary <string, string> customParameters, Fetch fetch)
        {
            if (!this.IsApplicable(configuration))
            {
                return(false);
            }

            var contextLanguageInfo = dependencies.GetRequestContext()?.HttpContext?.GetContextLanguageInfo();

            if (contextLanguageInfo == null || !contextLanguageInfo.IsCrmMultiLanguageEnabled)
            {
                return(false);
            }

            var serviceContext       = dependencies.GetServiceContext();
            var provisionedLanguages = ContextLanguageInfo.GetProvisionedLanugages(serviceContext as IOrganizationService);

            if (!provisionedLanguages.Any())
            {
                return(false);
            }

            var languageCondition = new Condition
            {
                Attribute = "adx_systemlanguage",
                Operator  = ConditionOperator.In,
                Values    = provisionedLanguages.Cast <object>().ToArray()
            };

            var filter = new Filter {
                Conditions = new[] { languageCondition }
            };

            if (fetch.Entity.Filters == null)
            {
                fetch.Entity.Filters = new List <Filter> {
                    filter
                };
            }
            else
            {
                fetch.Entity.Filters.Add(filter);
            }

            return(true);
        }
        private ApplicationPath GetApplicationPath(ContentMap map, Entity entity, string partialUrlAttribute, string parentReferenceAttribute, bool trailingSlash = false, bool prependLangCode = false)
        {
            var partialUrl = entity.GetAttributeValue <string>(partialUrlAttribute);

            if (string.IsNullOrEmpty(partialUrl))
            {
                return(null);
            }

            var parentReference = entity.GetAttributeValue <EntityReference>(parentReferenceAttribute);

            if (parentReference == null)
            {
                return(null);
            }

            EntityNode parentNode;

            if (!map.TryGetValue(parentReference, out parentNode))
            {
                return(null);
            }

            var parentPath = GetApplicationPath(map, parentNode);

            if (parentPath == null || parentPath.PartialPath == null)
            {
                return(null);
            }

            partialUrl = trailingSlash && !partialUrl.EndsWith("/") ? partialUrl + "/" : partialUrl;

            var parentPartialPath = parentPath.PartialPath.EndsWith("/") ? parentPath.PartialPath : parentPath.PartialPath + "/";

            var resultAppPath = ApplicationPath.FromPartialPath(parentPartialPath + partialUrl);

            if (ContextLanguageInfo.DisplayLanguageCodeInUrl &&
                ContextLanguageInfo.IsCrmMultiLanguageEnabledInWebsite(PortalContext.Current.Website) &&
                prependLangCode)
            {
                resultAppPath = ContextLanguageInfo.PrependLanguageCode(resultAppPath);
            }

            return(resultAppPath);
        }
示例#18
0
        /// <summary>
        /// This method is created to wrap GetApplicationPath and prepend language code to link if required
        /// </summary>
        private ApplicationPath GetApplicationPath(OrganizationServiceContext context, Entity entity, ContentMap map)
        {
            var path = GetApplicationPathBase(context, entity, map);

            if (path == null || !ContextLanguageInfo.DisplayLanguageCodeInUrl)
            {
                return(path);
            }

            switch (entity.LogicalName)
            {
            case "adx_weblink":
            case "adx_webpage":
                return(ContextLanguageInfo.PrependLanguageCode(path));
            }

            return(path);
        }
        private static string GetLanguageName(Entity entity, ContextLanguageInfo language)
        {
            if (language.IsCrmMultiLanguageEnabled)
            {
                var langReference = entity.GetAttributeValue <EntityReference>("adx_contentsnippetlanguageid");
                if (langReference != null)
                {
                    var websiteLanguages = language.ActiveWebsiteLanguages.ToArray();
                    var snippetLanguage  = language.GetWebsiteLanguage(langReference.Id, websiteLanguages);

                    if (snippetLanguage != null)
                    {
                        return(snippetLanguage.DisplayName);
                    }
                }
            }

            return(null);
        }
示例#20
0
        public ContentSnippetNode GetSnippetNode(string name, ContextLanguageInfo language)
        {
            IDictionary <EntityReference, EntityNode> snippets;
            // Note: Content snippets can have a language matching the current language, or they can have no language and apply for all languages
            var userLanguageEntity = language == null || !language.IsCrmMultiLanguageEnabled ? null : language.ContextLanguage.EntityReference;

            if (this.TryGetValue("adx_contentsnippet", out snippets))
            {
                var snippet = GetSnippetNode(snippets.Values.OfType <ContentSnippetNode>(), name, language);

                ADXTrace.Instance.TraceInfo(
                    TraceCategory.Application,
                    snippet == null
                                                ? string.Format(
                        "Does not exist: SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}",
                        name,
                        userLanguageEntity == null ? null : userLanguageEntity.Id.ToString(),
                        userLanguageEntity == null ? null : userLanguageEntity.Name)
                                                : string.Format(
                        "Exist: SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}, SnippetLanguageId={3}, SnippetLanguageName={4}",
                        name,
                        userLanguageEntity == null ? null : userLanguageEntity.Id.ToString(),
                        userLanguageEntity == null ? null : userLanguageEntity.Name,
                        snippet.Language == null ? null : snippet.Language.Id.ToString(),
                        snippet.Language == null ? null : snippet.Language.Name));

                return(snippet);
            }

            ADXTrace.Instance.TraceInfo(
                TraceCategory.Application,
                string.Format(
                    "No content snippets found. SnippetName={0}, UserLanguageId={1}, UserLanguageName={2}",
                    name,
                    userLanguageEntity == null ? null : userLanguageEntity.Id.ToString(),
                    userLanguageEntity == null ? null : userLanguageEntity.Name));

            return(null);
        }
示例#21
0
        /// <summary>
        /// Setup Culture for localization and globalization of the application.
        /// </summary>
        /// <param name="website"></param>
        /// <param name="legacyWebsiteLcid">CrmWebsite.Language value, for backwards compatibility with legacy pre-Multi-Language CRM environments.</param>
        /// <param name="bundles"></param>
        /// <param name="registerAction"></param>
        private static void UseLocalizedBundles(Entity website, int legacyWebsiteLcid, IContentMapProvider contentMapProvider, BundleCollection bundles, Action <BundleCollection, CultureInfo> registerAction)
        {
            // For backward compatibility with pre-Multi-Language CRM environments.
            // At this point in code execution, PortalContext is not available yet, so check for existance of adx_defaultlanguage field to determine if this is legacy environment or not.
            if (!ContextLanguageInfo.IsCrmMultiLanguageEnabledInWebsite(website))
            {
                if (legacyWebsiteLcid != 0)
                {
                    CultureInfo culture = new CultureInfo(legacyWebsiteLcid);
                    CultureInfo.DefaultThreadCurrentCulture   = culture;
                    CultureInfo.DefaultThreadCurrentUICulture = culture;
                    registerAction(bundles, culture);
                }
                return;
            }

            // Note: for environments WITH multi-language, the CurrentCulture will be set by ContextLanguageInfo.BuildContextLanguageInfo(...)

            // Not able to use portal language context so getting language directly
            // (portal context depends on owin context which is accesible only per request, not on startup)

            WebsiteNode websiteNode = null;

            contentMapProvider.Using(contentMap => contentMap.TryGetValue(website, out websiteNode));

            if (websiteNode == null)
            {
                registerAction(bundles, CultureInfo.CurrentCulture);
            }

            foreach (var websiteLanguage in websiteNode.WebsiteLanguages)
            {
                var portalLanguage = websiteLanguage.PortalLanguage;
                var culture        = ContextLanguageInfo.GetCulture(portalLanguage.CrmLanguage ?? 0);

                registerAction(bundles, culture);
            }
        }
示例#22
0
        private static string GetTimeAgoLanguageCode(CultureInfo culture)
        {
            string languageLetterCode = culture.TwoLetterISOLanguageName;
            int    lcid = ContextLanguageInfo.ResolveCultureLcid(culture.LCID);

            if (lcid == 1044)             //norwegian (bokmål)
            {
                languageLetterCode = "no";
            }
            else if (lcid == 1046)             //portuguese (brazil)
            {
                languageLetterCode = "pt-br";
            }
            else if (lcid == 3098)             //serbian (cyrillic)
            {
                languageLetterCode = "sr";
            }
            else if (lcid == 2074)             //serbian (latin)
            {
                languageLetterCode = "rs";
            }
            else if (lcid == 1028)             //chinese (traditional)
            {
                languageLetterCode = "zh-TW";
            }
            else if (lcid == 2052)             //chinese (simplified)
            {
                languageLetterCode = "zh-CN";
            }
            else if (lcid == 3076)
            {
                languageLetterCode = "zh-HK";
            }

            return(languageLetterCode);
        }
示例#23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="website"></param>
        /// <param name="urlPath"></param>
        /// <param name="getRootWebPage">Whether to get the Root version of a group of translated web pages where adx_isroot = true.
        /// This should only be set to true in specific cases where we are explicitly looking for the non-translated root page,
        /// ex: we're looking for a web file which only hangs off from root web pages.
        /// This does NOT refer to the root "/" web page (typically Home page).</param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        private static UrlMappingResult <WebPageNode> LookupPageByUrlPath(WebsiteNode website, string urlPath, WebPageLookupOptions lookupOption, ContextLanguageInfo languageContext, Func <WebPageNode, bool> predicate)
        {
            if (website.Id == Guid.Empty)
            {
                throw new ArgumentException(string.Format("Unable to retrieve the Id of the website. {0}", string.Empty), "website");
            }

            ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupPageByUrlPath ENTER URL");

            var pages = website.WebPages.Where(predicate).ToArray();

            // Use _pagePathRegex to extract the right-most path segment (child path), and the remaining left
            // part of the path (parent path), while enforcing that web page paths must end in a '/'.
            var pathMatch = UrlMapping._pagePathRegex.Match(urlPath);

            if (!pathMatch.Success)
            {
                // If we don't have a valid path match, still see if there is a page with the entire literal
                // path as its partial URL. (The previous iteration of this method has this behaviour, so we
                // maintain it here.)
                // NOTE: requests for web files (ex: .png, .css) and bad links all come here.
                var mappingResult = FilterResultsOnLanguage(pages, p => IsPartialUrlMatch(p, urlPath), lookupOption, languageContext);
                ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("LookupPageByUrlPath (1)pathMatch.Fail URL {0}", mappingResult.Node == null ? "NULL" : "Found"));
                return(mappingResult);
            }

            var fullPath   = pathMatch.Groups["full"].Value;
            var parentPath = pathMatch.Groups["parent"].Value;
            var childPath  = pathMatch.Groups["child"].Value;

            // Check if we can find a page with the exact fullPath match. This may be a web page with a
            // partial URL that matches the entire path, but in the more common case, it will match the
            // root URL path "/".
            var fullPathMatchPageResult = FilterResultsOnLanguage(pages, p => IsPartialUrlMatch(p, fullPath), lookupOption, languageContext);

            if (fullPathMatchPageResult.Node != null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupPageByUrlPath (2)fullPathMatchPage ");
                return(fullPathMatchPageResult);
            }

            // If we don't have non-empty parentPath and childPath, lookup fails.
            if (string.IsNullOrEmpty(parentPath) || string.IsNullOrEmpty(childPath))
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupPageByUrlPath (3)parent/child path null ");
                return(UrlMappingResult <WebPageNode> .MatchResult(null));
            }

            // Look up the parent page, using the parent path. This will generally recurse until parentPath
            // is the root path "/", at which point fullPath will match the Home page and the recursion will
            // unwind.
            // Look for the "Root" (adx_isroot=true) web page because the parent-child relationships uses the Root web pages, not the translated Content web pages.
            // (Ignoring uniquence for parent page)
            var parentPageFilterResult = LookupPageByUrlPath(website, parentPath, WebPageLookupOptions.RootOnly, languageContext, predicate);

            // If we can't find a parent page, lookup fails.
            // Ignore IsUnique here, trying to find any possible match.
            if (parentPageFilterResult.Node == null)
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupPageByUrlPath (4)parent page null ");
                return(parentPageFilterResult);
            }

            // Look for a partial URL match for childPath, among the children of the returned parent page.
            var result = FilterResultsOnLanguage(parentPageFilterResult.Node.WebPages, p => predicate(p) && IsPartialUrlMatch(p, childPath), lookupOption, languageContext);

            ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, string.Format("LookupPageByUrlPath (5)searchByParent {0}", result.Node == null ? "NULL" : "Found"));
            return(result);
        }
示例#24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="website"></param>
        /// <param name="urlPath"></param>
        /// <param name="getRootWebPage">Whether to get the Root version of a group of translated web pages where adx_isroot = true.
        /// This should only be set to true in specific cases where we are explicitly looking for the non-translated root page,
        /// ex: we're looking for a web file which only hangs off from root web pages, or the provided urlPath is from a SiteMapNode which is not language-aware so the url will be the root's.
        /// This does NOT refer to the website root "/" (aka Home) web page.</param>
        /// <returns></returns>
        public static UrlMappingResult <WebPageNode> LookupPageByUrlPath(WebsiteNode website, string urlPath, WebPageLookupOptions lookupOption, ContextLanguageInfo languageContext)
        {
            var applicationPath = UrlMapping.GetApplicationPath(urlPath);

            CrmEntityInactiveInfo inactiveInfo;

            var filter = CrmEntityInactiveInfo.TryGetInfo("adx_webpage", out inactiveInfo)
                                ? page => !inactiveInfo.IsInactive(page.ToEntity())
                                : new Func <WebPageNode, bool>(entity => true);

            var result = LookupPageByUrlPath(website, applicationPath.PartialPath, lookupOption, languageContext, filter);

            return(result);
        }
示例#25
0
        private static WebFileNode LookupFileByUrlPath(WebsiteNode website, string urlPath, ContextLanguageInfo languageContext, Func <WebFileNode, bool> predicate)
        {
            if (website.Id == Guid.Empty)
            {
                throw new NullReferenceException(string.Format("Unable to retrieve the Id of the website. {0}", "Lookup failed."));
            }

            var urlWithoutWebsitePath = HttpUtility.UrlDecode(urlPath.TrimEnd('/'));

            string parentPath;
            string thisPath;

            if (ParseParentPath(urlWithoutWebsitePath, out parentPath, out thisPath))
            {
                // Find the language-root web page because that's what web files hang off from.
                var parentFilterResult = LookupPageByUrlPath(website, parentPath, WebPageLookupOptions.RootOnly, languageContext);

                if (parentFilterResult.Node != null)
                {
                    var file = parentFilterResult.Node.WebFiles.FirstOrDefault(f => predicate(f) && string.Equals(f.PartialUrl, thisPath, StringComparison.InvariantCultureIgnoreCase));

                    if (file != null)
                    {
                        ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupFILEByUrlPath Found");
                        return(file);
                    }
                }
            }

            ADXTrace.Instance.TraceInfo(TraceCategory.Monitoring, "LookupFILEByUrlPath NULL");
            return(null);
        }
示例#26
0
        public static WebFileNode LookupFileByUrlPath(WebsiteNode website, string urlPath, ContextLanguageInfo languageContext)
        {
            CrmEntityInactiveInfo inactiveInfo;

            var filter = CrmEntityInactiveInfo.TryGetInfo("adx_webfile", out inactiveInfo)
                                ? file => !inactiveInfo.IsInactive(file.ToEntity())
                                : new Func <WebFileNode, bool>(entity => true);

            var result = LookupFileByUrlPath(website, urlPath, languageContext, filter);

            return(result);
        }
示例#27
0
        private static UrlMappingResult <WebPageNode> FilterResultsOnLanguage(IEnumerable <WebPageNode> pages, Func <WebPageNode, bool> predicate, WebPageLookupOptions lookupOption, ContextLanguageInfo contextLanguageInfo)
        {
            var         results = pages.Where(predicate);
            WebPageNode retval  = null;

            if (contextLanguageInfo != null && contextLanguageInfo.IsCrmMultiLanguageEnabled)
            {
                if (lookupOption == WebPageLookupOptions.LanguageContentOnly)
                {
                    // when we have only a root webpage and 0 localized webpages.
                    // for example: creating new child page via portal CMS.
                    if (results.Where(p => p.IsRoot == false).Count() == 0)
                    {
                        retval = results.FirstOrDefault();
                    }
                    else
                    {
                        var websiteLanguageId = contextLanguageInfo.ContextLanguage.EntityReference.Id;
                        retval = results.FirstOrDefault(p => p.WebPageLanguage != null && p.WebPageLanguage.Id == websiteLanguageId && p.IsRoot == false);
                    }
                }
                else if (lookupOption == WebPageLookupOptions.RootOnly)
                {
                    retval = results.FirstOrDefault(p => p.IsRoot == true);
                }
                else
                {
                    retval = results.FirstOrDefault();
                }

                // If the found page is content, but the root page is deactivated, then return null as if the page itself doesn't exist.
                if (retval != null && retval.IsRoot == false && (retval.RootWebPage == null || retval.RootWebPage.IsReference))
                {
                    retval = null;
                }
            }
            else
            {
                // If multi-language is not supported, then do legacy behavior of returning first result.
                retval = results.FirstOrDefault();
            }

            // select only root pages or pages where isroot = null (MLP is not supported)
            var duplicateCheckArray = results.Where(p => p.IsRoot != false).ToArray();

            return(duplicateCheckArray.Length > 1
                                ? UrlMappingResult <WebPageNode> .DuplicateResult(retval)
                                : UrlMappingResult <WebPageNode> .MatchResult(retval));
        }
示例#28
0
        public static void RegisterLanguageSpecificBundles(BundleCollection bundles, CultureInfo culture)
        {
            var bundleName = LocalizedScripts.GetLocalizedBundleName("~/js/default.bundle.js", ContextLanguageInfo.ResolveCultureLcid(culture.LCID));

            var defaultBundle = new ScriptBundle(bundleName);

            defaultBundle.Include("~/js/bootstrap.min.js",
                                  "~/js/eventListener.polyfill.js",
                                  "~/js/handlebars.js",
                                  "~/js/date.js",
                                  "~/js/timeago/jquery.timeago.js",
                                  "~/js/google-code-prettify/prettify.js",
                                  "~/js/jquery.cookie.js",
                                  "~/js/jquery.bootstrap-pagination.js",
                                  "~/js/jquery.blockUI.js",
                                  "~/js/jquery.form.min.js",
                                  "~/js/entity-notes.js",
                                  "~/js/entity-form.js",
                                  "~/js/entity-grid.js",
                                  "~/js/entity-associate.js",
                                  "~/js/entity-lookup.js",
                                  "~/js/quickform.js",
                                  "~/js/serialized-query.js",
                                  "~/Areas/Cms/js/ads.js",
                                  "~/Areas/Cms/js/polls.js",
                                  "~/Areas/Chat/js/auth.js",
                                  "~/Areas/CaseManagement/js/case-deflection.js",
                                  "~/Areas/CaseManagement/js/entitlements.js",
                                  "~/Areas/Search/js/faceted-search.js",
                                  "~/Areas/KnowledgeManagement/js/article.js",
                                  "~/js/badges.js",
                                  "~/js/sharepoint-grid.js");

#if HIGHCHARTS
            defaultBundle.Include("~/js/charts/highcharts/highcharts.js");
#endif
#if HIGHCHARTSFUNNEL
            defaultBundle.Include("~/js/charts/highcharts/funnel.js");
#endif

            defaultBundle.Include("~/js/charts/crm/MicrosoftAjax.js",
                                  "~/js/charts/crm/Microsoft.Crm.Client.Core.js",
                                  "~/js/charts/crm/CrmInternalUtility.js",
                                  "~/js/charts/crm/CrmHighchartsLibrary.js",
                                  "~/js/charts/crm/PortalChartOrchestrator.js",
                                  "~/js/charts/chart.js",
                                  "~/js/jQuery.rateit.min.js",
                                  "~/js/rating.js",
                                  "~/js/portal.js")
            .Include(string.Format(CultureInfo.InvariantCulture, "~/js/timeago/locales/jquery.timeago.{0}.js",
                                   GetTimeAgoLanguageCode(culture)));

            bundles.Add(defaultBundle);
        }
 /// <summary>
 /// Gets the LCID of current CRM language. Ex: if current language is en-CA (4105), then 1033 (en-US) will be returned because that is the associated CRM language.
 /// </summary>
 /// <param name="languageInfo">ContextLanguageInfo to extract language info from.</param>
 /// <returns>LCID of current CRM language.</returns>
 public static int GetCrmLcid(this ContextLanguageInfo languageInfo)
 {
     return(languageInfo?.ContextLanguage?.CrmLcid ?? CultureInfo.CurrentCulture.LCID);
 }
        protected virtual IWebLinkSet Select(Predicate <Entity> match)
        {
            var serviceContext = Dependencies.GetServiceContext();
            var website        = Dependencies.GetWebsite();
            ContextLanguageInfo languageInfo = HttpContext.Current.GetContextLanguageInfo();

            // Bulk-load all web link set entities into cache.
            var fetch = new Fetch
            {
                Entity = new FetchEntity("adx_weblinkset")
                {
                    Filters = new[]
                    {
                        new Filter
                        {
                            Conditions = !languageInfo.IsCrmMultiLanguageEnabled
                                                                ? new[] { new Condition("adx_websiteid", ConditionOperator.Equal, website.Id) }
                                                                : new[] { new Condition("adx_websiteid", ConditionOperator.Equal, website.Id),
                                                                          new Condition("adx_websitelanguageid", ConditionOperator.Equal, languageInfo.ContextLanguage.EntityReference.Id) }
                        }
                    }
                }
            };

            var allEntities = HttpContext.Current.GetOrganizationService().RetrieveMultiple(fetch).Entities;
            var entity      = allEntities.FirstOrDefault(e => match(e) && IsActive(e));

            if (entity == null)
            {
                return(null);
            }

            var securityProvider = Dependencies.GetSecurityProvider();

            if (!securityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read))
            {
                return(null);
            }

            var urlProvider = Dependencies.GetUrlProvider();

            fetch = new Fetch
            {
                Entity = new FetchEntity("adx_weblink")
                {
                    Orders  = new[] { new Order("adx_displayorder") },
                    Filters = new[]
                    {
                        new Filter
                        {
                            Conditions = new[]
                            {
                                new Condition("statecode", ConditionOperator.Equal, 0),
                                new Condition("adx_weblinksetid", ConditionOperator.Equal, entity.Id)
                            }
                        }
                    }
                }
            };

            var webLinkEntities = HttpContext.Current.GetOrganizationService().RetrieveMultiple(fetch).Entities
                                  .Where(e => securityProvider.TryAssert(serviceContext, e, CrmEntityRight.Read)).ToArray();

            var childWebLinkLookup = webLinkEntities
                                     .Where(e => e.GetAttributeValue <EntityReference>("adx_parentweblinkid") != null)
                                     .ToLookup(e => e.GetAttributeValue <EntityReference>("adx_parentweblinkid").Id);

            var topLevelWebLinks = webLinkEntities
                                   .Where(e => e.GetAttributeValue <EntityReference>("adx_parentweblinkid") == null)
                                   .Select(e => CreateWebLink(serviceContext, e, securityProvider, urlProvider, childWebLinkLookup));

            var webLinkSet = new WebLinkSet(entity, new PortalViewEntity(serviceContext, entity, securityProvider, urlProvider), topLevelWebLinks);

            return(webLinkSet);
        }