/// <summary>
        /// Used to register a replacement for <see cref="ILocalizedTextService"/> where the file sources are the ones within the netcore project so
        /// we don't need to copy files
        /// </summary>
        private static ILocalizedTextService GetLocalizedTextService(IServiceProvider factory)
        {
            IOptions <GlobalSettings> globalSettings = factory.GetRequiredService <IOptions <GlobalSettings> >();
            ILoggerFactory            loggerFactory  = factory.GetRequiredService <ILoggerFactory>();
            AppCaches appCaches = factory.GetRequiredService <AppCaches>();

            var localizedTextService = new LocalizedTextService(
                new Lazy <LocalizedTextServiceFileSources>(() =>
            {
                // get the src folder
                var root      = TestContext.CurrentContext.TestDirectory.Split("tests")[0];
                var srcFolder = Path.Combine(root, "src");

                var currFolder = new DirectoryInfo(srcFolder);

                DirectoryInfo uiProject = currFolder.GetDirectories("Umbraco.Web.UI", SearchOption.TopDirectoryOnly).First();
                var mainLangFolder      = new DirectoryInfo(Path.Combine(uiProject.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang"));

                return(new LocalizedTextServiceFileSources(
                           loggerFactory.CreateLogger <LocalizedTextServiceFileSources>(),
                           appCaches,
                           mainLangFolder,
                           Array.Empty <LocalizedTextServiceSupplementaryFileSource>(),
                           new EmbeddedFileProvider(typeof(IAssemblyProvider).Assembly, "Umbraco.Cms.Core.EmbeddedResources.Lang").GetDirectoryContents(string.Empty)));
            }),
                loggerFactory.CreateLogger <LocalizedTextService>());

            return(localizedTextService);
        }
        public void Using_XDocument_Gets_All_Stored_Values()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement(
                                                          "language",
                                                          new XElement("area", new XAttribute("alias", "testArea1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey2"), "testValue2")),
                                                          new XElement("area", new XAttribute("alias", "testArea2"),
                                                                       new XElement("key", new XAttribute("alias", "blah1"), "blahValue1"),
                                                                       new XElement("key", new XAttribute("alias", "blah2"), "blahValue2")))))
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            IDictionary <string, string> result = txtService.GetAllStoredValues(culture);

            Assert.AreEqual(4, result.Count());
            Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key);
            Assert.AreEqual("testArea1/testKey2", result.ElementAt(1).Key);
            Assert.AreEqual("testArea2/blah1", result.ElementAt(2).Key);
            Assert.AreEqual("testArea2/blah2", result.ElementAt(3).Key);
            Assert.AreEqual("testValue1", result["testArea1/testKey1"]);
            Assert.AreEqual("testValue2", result["testArea1/testKey2"]);
            Assert.AreEqual("blahValue1", result["testArea2/blah1"]);
            Assert.AreEqual("blahValue2", result["testArea2/blah2"]);
        }
    public void Using_Dictionary_Returns_Tokenized_Text()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
        {
            {
                culture,
                new Lazy <IDictionary <string, IDictionary <string, string> > >(() =>
                                                                                new Dictionary <string, IDictionary <string, string> >
                {
                    {
                        "testArea",
                        new Dictionary <string, string> {
                            { "testKey", "Hello %0%, you are such a %1% %2%" }
                        }
                    },
                })
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        var result = txtService.Localize(
            "testKey",
            culture,
            new Dictionary <string, string> {
            { "0", "world" }, { "1", "great" }, { "2", "planet" }
        });

        Assert.AreEqual("Hello world, you are such a great planet", result);
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Maps properties on to the generic properties tab
        /// </summary>
        /// <param name="content"></param>
        /// <param name="tabs"></param>
        /// <param name="context"></param>
        /// <remarks>
        /// The generic properties tab is responsible for
        /// setting up the properties such as Created date, updated date, template selected, etc...
        /// </remarks>
        protected virtual void MapGenericProperties(IContentBase content, List <Tab <ContentPropertyDisplay> > tabs, MapperContext context)
        {
            // add the generic properties tab, for properties that don't belong to a tab
            // get the properties, map and translate them, then add the tab
            var noGroupProperties = content.GetNonGroupedProperties()
                                    .Where(x => IgnoreProperties.Contains(x.Alias) == false) // skip ignored
                                    .ToList();
            var genericProperties = MapProperties(content, noGroupProperties, context);

            var customProperties = GetCustomGenericProperties(content);

            if (customProperties != null)
            {
                genericProperties.AddRange(customProperties);
            }

            if (genericProperties.Count > 0)
            {
                tabs.Add(new Tab <ContentPropertyDisplay>
                {
                    Id         = 0,
                    Label      = LocalizedTextService.Localize("general", "properties"),
                    Alias      = "Generic properties",
                    Properties = genericProperties
                });
            }
        }
        /// <summary>
        /// Used to register a replacement for <see cref="ILocalizedTextService"/> where the file sources are the ones within the netcore project so
        /// we don't need to copy files
        /// </summary>
        private static ILocalizedTextService GetLocalizedTextService(IServiceProvider factory)
        {
            IOptions <GlobalSettings> globalSettings = factory.GetRequiredService <IOptions <GlobalSettings> >();
            ILoggerFactory            loggerFactory  = factory.GetRequiredService <ILoggerFactory>();
            AppCaches appCaches = factory.GetRequiredService <AppCaches>();

            var localizedTextService = new LocalizedTextService(
                new Lazy <LocalizedTextServiceFileSources>(() =>
            {
                // get the src folder
                var currFolder = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
                while (!currFolder.Name.Equals("src", StringComparison.InvariantCultureIgnoreCase))
                {
                    currFolder = currFolder.Parent;
                }

                DirectoryInfo uiProject = currFolder.GetDirectories("Umbraco.Web.UI", SearchOption.TopDirectoryOnly).First();
                var mainLangFolder      = new DirectoryInfo(Path.Combine(uiProject.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang"));

                return(new LocalizedTextServiceFileSources(
                           loggerFactory.CreateLogger <LocalizedTextServiceFileSources>(),
                           appCaches,
                           mainLangFolder));
            }),
                loggerFactory.CreateLogger <LocalizedTextService>());

            return(localizedTextService);
        }
Ejemplo n.º 6
0
        protected override ActionResult <MenuItemCollection> GetMenuForNode(string id, FormCollection queryStrings)
        {
            var menu = _menuItemCollectionFactory.Create();

            if (id == Constants.System.RootString)
            {
                // set the default to create
                menu.DefaultMenuAlias = ActionNew.ActionAlias;

                // root actions
                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);
                menu.Items.Add(new RefreshNode(LocalizedTextService));
                return(menu);
            }

            var container = _entityService.Get(int.Parse(id, CultureInfo.InvariantCulture), UmbracoObjectTypes.MediaTypeContainer);

            if (container != null)
            {
                // set the default to create
                menu.DefaultMenuAlias = ActionNew.ActionAlias;

                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);

                menu.Items.Add(new MenuItem("rename", LocalizedTextService.Localize("actions", "rename"))
                {
                    Icon = "icon icon-edit"
                });

                if (container.HasChildren == false)
                {
                    // can delete doc type
                    menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true);
                }
                menu.Items.Add(new RefreshNode(LocalizedTextService, true));
            }
            else
            {
                var ct     = _mediaTypeService.Get(int.Parse(id, CultureInfo.InvariantCulture));
                var parent = ct == null ? null : _mediaTypeService.Get(ct.ParentId);

                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);

                // no move action if this is a child doc type
                if (parent == null)
                {
                    menu.Items.Add <ActionMove>(LocalizedTextService, true, opensDialog: true);
                }

                menu.Items.Add <ActionCopy>(LocalizedTextService, opensDialog: true);
                if (ct.IsSystemMediaType() == false)
                {
                    menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true);
                }
                menu.Items.Add(new RefreshNode(LocalizedTextService, true));
            }

            return(menu);
        }
        /// <summary>
        /// Maps properties on to the generic properties tab
        /// </summary>
        /// <param name="content"></param>
        /// <param name="tabs"></param>
        /// <param name="context"></param>
        /// <remarks>
        /// The generic properties tab is responsible for
        /// setting up the properties such as Created date, updated date, template selected, etc...
        /// </remarks>
        protected virtual void MapGenericProperties(IContentBase content, List <Tab <ContentPropertyDisplay> > tabs, MapperContext context)
        {
            // add the generic properties tab, for properties that don't belong to a tab
            // get the properties, map and translate them, then add the tab
            var noGroupProperties = content.GetNonGroupedProperties()
                                    .Where(x => IgnoreProperties.Contains(x.Alias) == false) // skip ignored
                                    .ToList();
            var genericproperties = MapProperties(content, noGroupProperties, context);

            tabs.Add(new Tab <ContentPropertyDisplay>
            {
                Id         = 0,
                Label      = LocalizedTextService.Localize("general", "properties"),
                Alias      = "Generic properties",
                Properties = genericproperties,
                Type       = PropertyGroupType.Group.ToString()
            });

            var genericProps = tabs.Single(x => x.Id == 0);

            //store the current props to append to the newly inserted ones
            var currProps = genericProps.Properties.ToArray();

            var contentProps = new List <ContentPropertyDisplay>();

            var customProperties = GetCustomGenericProperties(content);

            if (customProperties != null)
            {
                //add the custom ones
                contentProps.AddRange(customProperties);
            }

            //now add the user props
            contentProps.AddRange(currProps);

            //re-assign
            genericProps.Properties = contentProps;

            //Show or hide properties tab based on whether it has or not any properties
            if (genericProps.Properties.Any() == false)
            {
                //loop through the tabs, remove the one with the id of zero and exit the loop
                for (var i = 0; i < tabs.Count; i++)
                {
                    if (tabs[i].Id != 0)
                    {
                        continue;
                    }
                    tabs.RemoveAt(i);
                    break;
                }
            }
        }
Ejemplo n.º 8
0
    protected override ActionResult <MenuItemCollection> GetMenuForNode(string id, FormCollection queryStrings)
    {
        MenuItemCollection menu = _menuItemCollectionFactory.Create();

        if (id == Constants.System.RootString)
        {
            //set the default to create
            menu.DefaultMenuAlias = ActionNew.ActionAlias;

            // root actions
            menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true, useLegacyIcon: false);
            menu.Items.Add(new RefreshNode(LocalizedTextService, true));
            return(menu);
        }

        IEntitySlim?container = _entityService.Get(int.Parse(id, CultureInfo.InvariantCulture),
                                                   UmbracoObjectTypes.DataTypeContainer);

        if (container != null)
        {
            //set the default to create
            menu.DefaultMenuAlias = ActionNew.ActionAlias;

            menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true, useLegacyIcon: false);

            menu.Items.Add(new MenuItem("rename", LocalizedTextService.Localize("actions", "rename"))
            {
                Icon          = "icon-edit",
                UseLegacyIcon = false,
            });

            if (container.HasChildren == false)
            {
                //can delete data type
                menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true, useLegacyIcon: false);
            }

            menu.Items.Add(new RefreshNode(LocalizedTextService, true));
        }
        else
        {
            IEnumerable <int> nonDeletableSystemDataTypeIds = GetNonDeletableSystemDataTypeIds();

            if (nonDeletableSystemDataTypeIds.Contains(int.Parse(id, CultureInfo.InvariantCulture)) == false)
            {
                menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true, useLegacyIcon: false);
            }

            menu.Items.Add <ActionMove>(LocalizedTextService, hasSeparator: true, opensDialog: true, useLegacyIcon: false);
        }

        return(menu);
    }
Ejemplo n.º 9
0
 public void Setup()
 {
     culture            = CultureInfo.GetCultureInfo("en-US");
     _dictionaryService = GetDictionaryLocalizedTextService(culture);
     _xmlService        = GetXmlService(culture);
     _optimized         = GetOptimizedService(culture);
     _optimizedDict     = GetOptimizedServiceDict(culture);
     var result1 = _dictionaryService.Localize("language", culture);
     var result2 = _xmlService.Localize("language", culture);
     var result3 = _dictionaryService.GetAllStoredValues(culture);
     var result4 = _xmlService.GetAllStoredValues(culture);
     var result5 = _optimized.GetAllStoredValues(culture);
     var result6 = _xmlService.GetAllStoredValues(culture);
     var result7 = _optimized.GetAllStoredValuesByAreaAndAlias(culture);
 }
    public void Using_XDocument_Returns_Default_Text_When_No_Culture_Found()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <XDocument> >
        {
            {
                culture, new Lazy <XDocument>(() => new XDocument(
                                                  new XElement("area", new XAttribute("alias", "testArea"), new XElement("key", new XAttribute("alias", "testKey"), "testValue"))))
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        Assert.AreEqual("[testKey]", txtService.Localize("testArea/testKey", CultureInfo.GetCultureInfo("en-AU")));
    }
        /// <summary>
        /// Ensures the recycle bin is appended when required (i.e. user has access to the root and it's not in dialog mode)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        /// <remarks>
        /// This method is overwritten strictly to render the recycle bin, it should serve no other purpose
        /// </remarks>
        protected sealed override ActionResult <TreeNodeCollection> GetTreeNodes(string id, FormCollection queryStrings)
        {
            //check if we're rendering the root
            if (id == Constants.System.RootString && UserStartNodes.Contains(Constants.System.Root))
            {
                var altStartId = string.Empty;

                if (queryStrings.HasKey(TreeQueryStringParameters.StartNodeId))
                {
                    altStartId = queryStrings.GetValue <string>(TreeQueryStringParameters.StartNodeId);
                }

                //check if a request has been made to render from a specific start node
                if (string.IsNullOrEmpty(altStartId) == false && altStartId != "undefined" && altStartId != Constants.System.RootString)
                {
                    id = altStartId;
                }

                var nodesResult = GetTreeNodesInternal(id, queryStrings);
                if (!(nodesResult.Result is null))
                {
                    return(nodesResult.Result);
                }

                var nodes = nodesResult.Value;

                //only render the recycle bin if we are not in dialog and the start id is still the root
                //we need to check for the "application" key in the queryString because its value is required here,
                //and for some reason when there are no dashboards, this parameter is missing
                if (IsDialog(queryStrings) == false && id == Constants.System.RootString && queryStrings.HasKey("application"))
                {
                    nodes.Add(CreateTreeNode(
                                  RecycleBinId.ToInvariantString(),
                                  id,
                                  queryStrings,
                                  LocalizedTextService.Localize("general", "recycleBin"),
                                  "icon-trash",
                                  RecycleBinSmells,
                                  queryStrings.GetRequiredValue <string>("application") + TreeAlias.EnsureStartsWith('/') + "/recyclebin"));
                }

                return(nodes);
            }

            return(GetTreeNodesInternal(id, queryStrings));
        }
    public void Using_XDocument_Returns_Text_Without_Area()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <XDocument> >
        {
            {
                culture, new Lazy <XDocument>(() => new XDocument(
                                                  new XElement("area", new XAttribute("alias", "testArea"), new XElement("key", new XAttribute("alias", "testKey"), "testValue"))))
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        var result = txtService.Localize("testKey", culture);

        Assert.AreEqual("testValue", result);
    }
Ejemplo n.º 13
0
        public void Using_XDocument_Returns_Default_Text_When_Not_Found_Without_Area()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement("area", new XAttribute("alias", "testArea"),
                                                                   new XElement("key", new XAttribute("alias", "testKey"),
                                                                                "testValue"))))
                }
            }, Mock.Of <ILogger>());

            var result = txtService.Localize("doNotFind", culture);

            Assert.AreEqual("[doNotFind]", result);
        }
Ejemplo n.º 14
0
        private static LocalizedTextService GetOptimizedService(CultureInfo culture)
        {
            var txtService = new LocalizedTextService(new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement("language",
                                                                   new XElement("area", new XAttribute("alias", "testArea1"),
                                                                                new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"),
                                                                                new XElement("key", new XAttribute("alias", "testKey2"), "testValue2")),
                                                                   new XElement("area", new XAttribute("alias", "testArea2"),
                                                                                new XElement("key", new XAttribute("alias", "blah1"), "blahValue1"),
                                                                                new XElement("key", new XAttribute("alias", "blah2"), "blahValue2")))))
                }
            }, Mock.Of <Umbraco.Core.Logging.ILogger>());

            return(txtService);
        }
    public void Using_XDocument_Returns_Default_Text_When_Not_Found_With_Area()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <XDocument> >
        {
            {
                culture, new Lazy <XDocument>(() => new XDocument(
                                                  new XElement("area", new XAttribute("alias", "testArea"), new XElement("key", new XAttribute("alias", "testKey"), "testValue"))))
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        var result = txtService.Localize("testArea/doNotFind", culture);

        // NOTE: Based on how legacy works, the default text does not contain the area, just the key
        Assert.AreEqual("[doNotFind]", result);
    }
Ejemplo n.º 16
0
        public void Using_XDocument_Gets_All_Stored_Values_With_Duplicates()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement("language",
                                                                   new XElement("area", new XAttribute("alias", "testArea1"),
                                                                                new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"),
                                                                                new XElement("key", new XAttribute("alias", "testKey1"), "testValue1")))))
                }
            }, Mock.Of <ILogger>());

            var result = txtService.GetAllStoredValues(culture);

            Assert.AreEqual(1, result.Count());
        }
        public void Using_XDocument_Returns_Tokenized_Text()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement("area", new XAttribute("alias", "testArea"),
                                                                   new XElement("key", new XAttribute("alias", "testKey"),
                                                                                "Hello %0%, you are such a %1% %2%"))))
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            string result = txtService.Localize("testKey", culture,
                                                new Dictionary <string, string> {
                { "0", "world" }, { "1", "great" }, { "2", "planet" }
            });

            Assert.AreEqual("Hello world, you are such a great planet", result);
        }
    public void Using_Dictionary_Returns_Default_Text__When_No_Culture_Found()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
        {
            {
                culture,
                new Lazy <IDictionary <string, IDictionary <string, string> > >(() =>
                                                                                new Dictionary <string, IDictionary <string, string> >
                {
                    { "testArea", new Dictionary <string, string> {
                          { "testKey", "testValue" }
                      } },
                })
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        Assert.AreEqual("[testKey]", txtService.Localize("testArea/testKey", CultureInfo.GetCultureInfo("en-AU")));
    }
Ejemplo n.º 19
0
        public void Using_Dictionary_Returns_Default_Text__When_No_Culture_Found()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, IDictionary <string, IDictionary <string, string> > >
            {
                {
                    culture, new Dictionary <string, IDictionary <string, string> >
                    {
                        {
                            "testArea", new Dictionary <string, string>
                            {
                                { "testKey", "testValue" }
                            }
                        }
                    }
                }
            }, Mock.Of <ILogger>());

            Assert.AreEqual("[testKey]", txtService.Localize("testArea/testKey", CultureInfo.GetCultureInfo("en-AU")));
        }
Ejemplo n.º 20
0
    protected override ActionResult <TreeNodeCollection> GetTreeNodes(string id, FormCollection queryStrings)
    {
        var nodes = new TreeNodeCollection();

        if (id == Constants.System.RootString)
        {
            nodes.Add(
                CreateTreeNode(
                    Constants.Conventions.MemberTypes.AllMembersListId,
                    id,
                    queryStrings,
                    LocalizedTextService.Localize("member", "allMembers"),
                    Constants.Icons.MemberType,
                    true,
                    queryStrings.GetRequiredValue <string>("application") +
                    TreeAlias.EnsureStartsWith('/') +
                    "/list/" +
                    Constants.Conventions.MemberTypes.AllMembersListId));

            nodes.AddRange(_memberTypeService.GetAll()
                           .Select(memberType =>
                                   CreateTreeNode(
                                       memberType.Alias,
                                       id,
                                       queryStrings,
                                       memberType.Name,
                                       memberType.Icon.IfNullOrWhiteSpace(Constants.Icons.Member),
                                       true,
                                       queryStrings.GetRequiredValue <string>("application") + TreeAlias.EnsureStartsWith('/') +
                                       "/list/" + memberType.Alias)));
        }

        //There is no menu for any of these nodes
        nodes.ForEach(x => x.MenuUrl = null);

        //All nodes are containers
        nodes.ForEach(x => x.AdditionalData.Add("isContainer", true));

        return(nodes);
    }
    public void Using_Dictionary_Gets_All_Stored_Values()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
        {
            {
                culture,
                new Lazy <IDictionary <string, IDictionary <string, string> > >(() =>
                                                                                new Dictionary <string, IDictionary <string, string> >
                {
                    {
                        "testArea1",
                        new Dictionary <string, string> {
                            { "testKey1", "testValue1" }, { "testKey2", "testValue2" }
                        }
                    },
                    {
                        "testArea2",
                        new Dictionary <string, string> {
                            { "blah1", "blahValue1" }, { "blah2", "blahValue2" }
                        }
                    },
                })
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        var result = txtService.GetAllStoredValues(culture);

        Assert.AreEqual(4, result.Count);
        Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key);
        Assert.AreEqual("testArea1/testKey2", result.ElementAt(1).Key);
        Assert.AreEqual("testArea2/blah1", result.ElementAt(2).Key);
        Assert.AreEqual("testArea2/blah2", result.ElementAt(3).Key);
        Assert.AreEqual("testValue1", result["testArea1/testKey1"]);
        Assert.AreEqual("testValue2", result["testArea1/testKey2"]);
        Assert.AreEqual("blahValue1", result["testArea2/blah1"]);
        Assert.AreEqual("blahValue2", result["testArea2/blah2"]);
    }
    public void Using_Dictionary_Returns_Default_Text_When_Not_Found_Without_Area()
    {
        var culture    = CultureInfo.GetCultureInfo("en-US");
        var txtService = new LocalizedTextService(
            new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
        {
            {
                culture,
                new Lazy <IDictionary <string, IDictionary <string, string> > >(() =>
                                                                                new Dictionary <string, IDictionary <string, string> >
                {
                    { "testArea", new Dictionary <string, string> {
                          { "testKey", "testValue" }
                      } },
                })
            },
        },
            s_loggerFactory.CreateLogger <LocalizedTextService>());

        var result = txtService.Localize("doNotFind", culture);

        Assert.AreEqual("[doNotFind]", result);
    }
Ejemplo n.º 23
0
        public void Using_Dictionary_Returns_Text_Without_Area()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, IDictionary <string, IDictionary <string, string> > >
            {
                {
                    culture, new Dictionary <string, IDictionary <string, string> >
                    {
                        {
                            "testArea", new Dictionary <string, string>
                            {
                                { "testKey", "testValue" }
                            }
                        }
                    }
                }
            }, Mock.Of <ILogger>());

            var result = txtService.Localize("testKey", culture);

            Assert.AreEqual("testValue", result);
        }
        public void Using_Dictionary_Returns_Text_With_Area()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
            {
                {
                    culture, new Lazy <IDictionary <string, IDictionary <string, string> > >(() => new Dictionary <string, IDictionary <string, string> >
                    {
                        {
                            "testArea", new Dictionary <string, string>
                            {
                                { "testKey", "testValue" }
                            }
                        }
                    })
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            string result = txtService.Localize("testArea/testKey", culture);

            Assert.AreEqual("testValue", result);
        }
Ejemplo n.º 25
0
    /// <summary>
    ///     The actual health check method.
    /// </summary>
    protected async Task <HealthCheckStatus> CheckForHeader()
    {
        string message;
        var    success = false;

        // Access the site home page and check for the click-jack protection header or meta tag
        var url = _hostingEnvironment.ApplicationMainUrl?.GetLeftPart(UriPartial.Authority);

        try
        {
            using HttpResponseMessage response = await HttpClient.GetAsync(url);

            // Check first for header
            success = HasMatchingHeader(response.Headers.Select(x => x.Key));

            // If not found, and available, check for meta-tag
            if (success == false && _metaTagOptionAvailable)
            {
                success = await DoMetaTagsContainKeyForHeader(response);
            }

            message = success
                ? LocalizedTextService.Localize("healthcheck", $"{_localizedTextPrefix}CheckHeaderFound")
                : LocalizedTextService.Localize("healthcheck", $"{_localizedTextPrefix}CheckHeaderNotFound");
        }
        catch (Exception ex)
        {
            message = LocalizedTextService.Localize("healthcheck", "healthCheckInvalidUrl", new[] { url, ex.Message });
        }

        return
            (new HealthCheckStatus(message)
        {
            ResultType = success ? StatusResultType.Success : StatusResultType.Error,
            ReadMoreLink = success ? null : ReadMoreLink,
        });
    }
        public void Using_Dictionary_Returns_Default_Text_When_Not_Found_With_Area()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <IDictionary <string, IDictionary <string, string> > > >
            {
                {
                    culture, new Lazy <IDictionary <string, IDictionary <string, string> > >(() => new Dictionary <string, IDictionary <string, string> >
                    {
                        {
                            "testArea", new Dictionary <string, string>
                            {
                                { "testKey", "testValue" }
                            }
                        }
                    })
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            string result = txtService.Localize("testArea/doNotFind", culture);

            // NOTE: Based on how legacy works, the default text does not contain the area, just the key
            Assert.AreEqual("[doNotFind]", result);
        }
Ejemplo n.º 27
0
        public virtual void SetUp()
        {
            // should not need this if all other tests were clean
            // but hey, never know, better avoid garbage-in
            Reset();

            // get/merge the attributes marking the method and/or the classes
            Options = TestOptionAttributeBase.GetTestOptions <UmbracoTestAttribute>();

            // FIXME: align to runtimes & components - don't redo everything here !!!! Yes this is getting painful

            var loggerFactory = GetLoggerFactory(Options.Logger);

            _loggerFactory = loggerFactory;
            var profiler   = new LogProfiler(loggerFactory.CreateLogger <LogProfiler>());
            var msLogger   = loggerFactory.CreateLogger("msLogger");
            var proflogger = new ProfilingLogger(loggerFactory.CreateLogger <ProfilingLogger>(), profiler);

            IOHelper = TestHelper.IOHelper;

            TypeFinder = new TypeFinder(loggerFactory.CreateLogger <TypeFinder>(), new DefaultUmbracoAssemblyProvider(GetType().Assembly, loggerFactory), new VaryingRuntimeHash());
            var appCaches      = GetAppCaches();
            var globalSettings = new GlobalSettings();
            var settings       = new WebRoutingSettings();

            IBackOfficeInfo backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, IOHelper, loggerFactory.CreateLogger <AspNetBackOfficeInfo>(), Microsoft.Extensions.Options.Options.Create(settings));
            IIpResolver     ipResolver     = new AspNetIpResolver();

            UmbracoVersion = new UmbracoVersion();


            LocalizedTextService = new LocalizedTextService(new Dictionary <CultureInfo, Lazy <XDocument> >(), loggerFactory.CreateLogger <LocalizedTextService>());
            var typeLoader = GetTypeLoader(IOHelper, TypeFinder, appCaches.RuntimeCache, HostingEnvironment, loggerFactory.CreateLogger <TypeLoader>(), proflogger, Options.TypeLoader);

            var services = TestHelper.GetRegister();

            Builder = new UmbracoBuilder(services, Mock.Of <IConfiguration>(), typeLoader);

            //TestHelper.GetConfigs().RegisterWith(register);
            services.AddUnique(typeof(ILoggerFactory), loggerFactory);
            services.AddTransient(typeof(ILogger <>), typeof(Logger <>));
            services.AddSingleton <ILogger>(msLogger);
            services.AddUnique(IOHelper);
            services.AddUnique(UriUtility);
            services.AddUnique(UmbracoVersion);
            services.AddUnique(TypeFinder);
            services.AddUnique(LocalizedTextService);
            services.AddUnique(typeLoader);
            services.AddUnique <IProfiler>(profiler);
            services.AddUnique <IProfilingLogger>(proflogger);
            services.AddUnique(appCaches);
            services.AddUnique(HostingEnvironment);
            services.AddUnique(backOfficeInfo);
            services.AddUnique(ipResolver);
            services.AddUnique <IPasswordHasher, AspNetPasswordHasher>();
            services.AddUnique(TestHelper.ShortStringHelper);
            //services.AddUnique<IPublicAccessChecker, PublicAccessChecker>();


            var memberService     = Mock.Of <IMemberService>();
            var memberTypeService = Mock.Of <IMemberTypeService>();

            TestObjects = new TestObjects();
            Compose();
            Current.Factory = Factory = TestHelper.CreateServiceProvider(Builder);
            Initialize();
        }