示例#1
0
        public void GetFullUrlBuilder_BuildsFullUrlWithoutQueryString()
        {
            // arrange
            var actionContext = MockHelpers.ActionContext();

            var actionContextAccessorMock = new Mock <IActionContextAccessor>();

            actionContextAccessorMock.SetupGet(x => x.ActionContext).Returns(actionContext);

            var host = new HostString("test.be", 99);

            Mock.Get(actionContext.HttpContext.Request).SetupGet(x => x.Host).Returns(host);
            Mock.Get(actionContext.HttpContext.Request).SetupGet(x => x.Scheme).Returns("xyz");

            var headerDictionary = new HeaderDictionary();

            headerDictionary.Add(new KeyValuePair <string, StringValues>("Host", new StringValues("test.be:99")));
            Mock.Get(actionContext.HttpContext.Request).SetupGet(x => x.Headers).Returns(headerDictionary);

            var urlHelper = new Mock <IUrlHelper>().Object;

            // act
            var linkProvider = new LinkProvider(actionContextAccessorMock.Object, urlHelper, new TestApiExtensionOptions(new Web.Api.ApiExtensionOptions()));
            var fullUrl      = linkProvider.GetFullUrlBuilder("/v1/test");

            // assert
            Assert.Equal("xyz://test.be:99/v1/test", fullUrl.ToString());
        }
示例#2
0
        private Mock <IActionContextAccessor> GetActionContextAccessorWithLinkProvider()
        {
            Mock <IServiceProvider>       serviceProvider = new Mock <IServiceProvider>();
            Mock <IActionContextAccessor> accessor        = new Mock <IActionContextAccessor>();

            var actionContext = MockHelpers.ActionContext();

            var httpContextMock = Mock.Get(actionContext.HttpContext);

            httpContextMock.SetupGet((h) => h.RequestServices).Returns(serviceProvider.Object);

            actionContext.HttpContext.RequestServices = serviceProvider.Object;

            actionContext.HttpContext.Request.Host   = new Microsoft.AspNetCore.Http.HostString("myhost.be", 999);
            actionContext.HttpContext.Request.Scheme = "XHS";
            actionContext.HttpContext.Request.Query  = new QueryCollection();
            actionContext.RouteData = new Microsoft.AspNetCore.Routing.RouteData();

            var apiExtOptions = new Mock <IOptions <ApiExtensionOptions> >();
            var urlHelper     = new Mock <IUrlHelper>();

            urlHelper.Setup((u) => u.RouteUrl(It.IsAny <UrlRouteContext>())).Returns("/test");

            accessor.SetupGet((o) => o.ActionContext).Returns(actionContext);

            var linkProvider = new LinkProvider(accessor.Object, urlHelper.Object, apiExtOptions.Object);

            serviceProvider.Setup((x) => x.GetService(typeof(ILinkProvider))).Returns(linkProvider);

            return(accessor);
        }
示例#3
0
        private Mock <IActionContextAccessor> GetActionContextAccessorWithLinkProvider()
        {
            Mock <IServiceProvider>       serviceProvider = new Mock <IServiceProvider>();
            Mock <IActionContextAccessor> accessor        = new Mock <IActionContextAccessor>();
            var actionContext = MockHelpers.ActionContext();

            var httpContextMock = Mock.Get(actionContext.HttpContext);

            httpContextMock.SetupGet((h) => h.RequestServices).Returns(serviceProvider.Object);

            actionContext.HttpContext.RequestServices = serviceProvider.Object;

            var apiExtOptions = new Mock <IOptions <ApiExtensionOptions> >();
            var urlHelper     = new Mock <IUrlHelper>();

            urlHelper.Setup((u) => u.RouteUrl(It.IsAny <UrlRouteContext>())).Returns("/test");

            accessor.SetupGet((o) => o.ActionContext).Returns(actionContext);

            var linkProvider = new LinkProvider(accessor.Object, urlHelper.Object, apiExtOptions.Object);

            serviceProvider.Setup((x) => x.GetService(typeof(ILinkProvider))).Returns(linkProvider);

            return(accessor);
        }
示例#4
0
        internal async Task DownloadLatestVersionTest(OperatingSystem os)
        {
            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => os);

            var linkProvider          = new LinkProvider(operatingSystemProvider);
            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try
            {
                FFbinariesVersionInfo currentVersion = JsonConvert.DeserializeObject <FFbinariesVersionInfo>(File.ReadAllText(Resources.FFbinariesInfo));
                FFmpeg.SetExecutablesPath("assemblies");
                if (Directory.Exists("assemblies"))
                {
                    Directory.Delete("assemblies", true);
                }
                OfficialFFmpegDownloader downloader = new OfficialFFmpegDownloader(operatingSystemProvider);
                await downloader.DownloadLatestVersion(currentVersion, FFmpeg.ExecutablesPath);

                Assert.True(File.Exists(downloader.ComputeFileDestinationPath("ffmpeg", os, FFmpeg.ExecutablesPath)));
                Assert.True(File.Exists(downloader.ComputeFileDestinationPath("ffprobe", os, FFmpeg.ExecutablesPath)));
            }
            finally
            {
                FFmpeg.SetExecutablesPath(ffmpegExecutablesPath);
            }
        }
        internal async Task DownloadLatestVersionWithProgressAndRetriesTest(OperatingSystem os)
        {
            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => os);

            var linkProvider          = new LinkProvider(operatingSystemProvider);
            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try
            {
                FFbinariesVersionInfo currentVersion = JsonConvert.DeserializeObject <FFbinariesVersionInfo>(File.ReadAllText(Resources.FFbinariesInfo));
                FFmpeg.SetExecutablesPath(_storageFixture.GetTempDirectory());
                OfficialFFmpegDownloader downloader = new OfficialFFmpegDownloader(operatingSystemProvider);
                IProgress <ProgressInfo> progress   = new Progress <ProgressInfo>();
                await downloader.DownloadLatestVersion(currentVersion, FFmpeg.ExecutablesPath, progress, 3);

                Assert.True(File.Exists(downloader.ComputeFileDestinationPath("ffmpeg", os, FFmpeg.ExecutablesPath)));
                Assert.True(File.Exists(downloader.ComputeFileDestinationPath("ffprobe", os, FFmpeg.ExecutablesPath)));
            }
            finally
            {
                FFmpeg.SetExecutablesPath(ffmpegExecutablesPath);
            }
        }
示例#6
0
 public void IsDynamicLinkCallsCurrentProvider(SwitchingLinkProvider sut, [Substitute] LinkProvider current, string linkText)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.IsDynamicLink(linkText).Should().Be(current.IsDynamicLink(linkText));
     }
 }
示例#7
0
 public void ParseRequestUrlCallsCurrentProvider(SwitchingLinkProvider sut, [Substitute] LinkProvider current, HttpRequest request)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.ParseRequestUrl(request).Should().Be(current.ParseRequestUrl(request));
     }
 }
示例#8
0
 public void ResolveTargetSiteCallsCurrentProvider(SwitchingLinkProvider sut, [Substitute] LinkProvider current, Item item)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.ResolveTargetSite(item).Should().Be(current.ResolveTargetSite(item));
     }
 }
示例#9
0
 public void GetDynamicUrlCallsCurrentProvider(SwitchingLinkProvider sut, [Substitute] LinkProvider current, Item item, LinkUrlOptions options)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.GetDynamicUrl(item, options).Should().BeSameAs(current.GetDynamicUrl(item, options));
     }
 }
示例#10
0
 public ContactSelfLinkFilter(LinkProvider linkProvider)
 {
     if (linkProvider == null)
     {
         throw new ArgumentNullException(nameof(linkProvider));
     }
     _linkProvider = linkProvider;
 }
示例#11
0
 public void ParseDynamicLinkCallsCurrentProvider(SwitchingLinkProvider sut, [Substitute] LinkProvider current, ID id)
 {
     using (new Switcher <LinkProvider>(current))
     {
         var linkText = "~/link.aspx?_id=" + id;
         sut.ParseDynamicLink(linkText).Should().Be(current.ParseDynamicLink(linkText));
     }
 }
示例#12
0
 internal DiskCachedLinker(string cachePath, int version, LinkProvider provider, FreebaseDbProvider db)
 {
     _cachePath = cachePath;
     _version   = version;
     _provider  = provider;
     _db        = db;
     loadCache();
 }
 public void SwitchLinkProvider([Substitute] LinkProvider provider,
                                Item item, [Modest] UrlOptions options)
 {
     provider.GetItemUrl(item, options).Returns("http://mysite.com/myitem");
     using (new Sitecore.FakeDb.Links.LinkProviderSwitcher(provider))
     {
         Assert.Equal("http://mysite.com/myitem", LinkManager.GetItemUrl(item, options));
     }
 }
        public PairingReceiverEmail(IServiceProvider services)
        {
            entries = services.GetService <IEntryRepository>();
            links   = services.GetService <LinkProvider>();

            feedbackRequest = services.GetService <FeedbackRequest>();
            personalMessage = services.GetService <PersonalMessage>();
            optOut          = services.GetService <OptOut>();
        }
示例#15
0
 public void GetDefaultUrlOptionsCallsCurrentProvider(
     SwitchingLinkProvider sut,
     [Substitute] LinkProvider current)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.GetDefaultUrlOptions().Should().BeSameAs(current.GetDefaultUrlOptions());
     }
 }
示例#16
0
 public void SutGetCurrentProvider(
     SwitchingLinkProvider sut,
     LinkProvider expected)
 {
     using (new Switcher <LinkProvider>(expected))
     {
         sut.CurrentProvider.Should().BeSameAs(expected);
     }
 }
示例#17
0
 public void ExpandDynamicLinksCallsCurrentProvider(
     SwitchingLinkProvider sut,
     [Substitute] LinkProvider current,
     string text,
     bool resolveSite)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.ExpandDynamicLinks(text, resolveSite).Should().Be(current.ExpandDynamicLinks(text, resolveSite));
     }
 }
        public static PagedResult GenerateLinks(this PagedResult result, ActionContext actionContext)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            if (result.Links == null)
            {
                result.Links = new PagedResultLinks();
            }
            if (result.PageOptions == null)
            {
                result.PageOptions = new PageOptions();
            }

            var pageOptions = result.PageOptions;
            var links       = result.Links;
            var routeValues = result.Links.RouteValues;

            Func <int, Link> generateLinkFunc = null;

            if (!string.IsNullOrEmpty(links.ControllerName) || !string.IsNullOrEmpty(links.ActionName))
            {
                var actionName     = links.ActionName;
                var controllerName = links.ControllerName;

                generateLinkFunc = (page) => LinkProvider.GenerateLink(actionContext, pageOptions, page, actionName, controllerName, routeValues);
            }
            else if (!string.IsNullOrEmpty(links.RouteName))
            {
                var routeName = links.RouteName;
                generateLinkFunc = (page) => LinkProvider.GenerateLink(actionContext, pageOptions, page, routeName, routeValues);
            }
            else
            {
                generateLinkFunc = page => LinkProvider.GenerateLink(actionContext, pageOptions, page, routeValues);
            }

            links.First = generateLinkFunc(1);
            links.Self  = generateLinkFunc(pageOptions.Page);
            links.Last  = generateLinkFunc(result.Page.TotalPages);

            if (pageOptions.Page > 1)
            {
                result.Links.Previous = generateLinkFunc(pageOptions.Page - 1);
            }
            if (pageOptions.Page < result.Page.TotalPages)
            {
                result.Links.Next = generateLinkFunc(pageOptions.Page + 1);
            }

            return(result);
        }
 public static string GetUrl(this Item item, LinkProvider linkProvider, ItemUrlBuilderOptions urlBuilderOptions)
 {
     if (item.HasPresentationDetails())
     {
         //Ensure that the targetHostName attribute of Site Definition is set to host name of Content Delivery instance
         using (new SiteContextSwitcher(item.GetSiteContext()))
         {
             return(linkProvider.GetItemUrl(item, urlBuilderOptions));
         }
     }
     return(string.Empty);
 }
示例#20
0
 public void InitializeCallsCurrentProviderIfSet(
     SwitchingLinkProvider sut,
     [Substitute] LinkProvider current,
     string name,
     NameValueCollection config)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.Initialize(name, config);
         current.Received().Initialize(name, config);
     }
 }
示例#21
0
        public static string GetWildcardItemUrl(Sitecore.Data.Items.Item wildcardItem, Item realItem, bool useDisplayName, UrlOptions urlOptions = null)
        {
            if (urlOptions == null)
            {
                urlOptions = UrlOptions.DefaultOptions;
            }

            urlOptions.AlwaysIncludeServerUrl = true;
            if (wildcardItem == null || realItem == null)
            {
                return(string.Empty);
            }

            var    scLinkProvider = new LinkProvider();
            string wildcardUrl    = scLinkProvider.GetItemUrl(wildcardItem, urlOptions);
            int    wildcardCount  = wildcardUrl.Split('/').Where(x => x == ",-w-,").Count();

            wildcardUrl = wildcardUrl.Replace(",-w-,", string.Empty);

            Uri            uri = new Uri(wildcardUrl);
            List <string>  wildcardItemPathParts = uri.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            ReferenceField wildcardDatasource    = wildcardItem.Fields[Templates.WildCard.Fields.WildCardDatasourceField];

            if (wildcardDatasource != null)
            {
                List <string> realItemPathParts = new List <string>();
                if (realItem.Axes.GetAncestors().Any(a => a.ID == wildcardDatasource.TargetID))
                {
                    Item ancestor = realItem.Parent;
                    int  idx      = 1;
                    while (ancestor.ID != wildcardDatasource.TargetID && idx < wildcardCount)
                    {
                        idx++;
                        realItemPathParts.Insert(0, useDisplayName ? ancestor.DisplayName : ancestor.Name);
                        ancestor = ancestor.Parent;
                    }
                }

                string itemUrlName = useDisplayName ? realItem.DisplayName : realItem.Name;
                realItemPathParts.Add(itemUrlName);
                wildcardItemPathParts.AddRange(realItemPathParts);
            }

            UriBuilder uriBuilder = new UriBuilder {
                Scheme = uri.Scheme, Host = uri.Host, Port = uri.Port, Path = string.Join("/", wildcardItemPathParts)
            };

            return(uriBuilder.Uri.ToString());
        }
示例#22
0
        public void Should_retrive_host()
        {
            // Arrange
            var fileMock = new Mock <IFormFile>();

            fileMock.Setup(_ => _.CopyToAsync(It.IsNotNull <Stream>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <object>(null));

            var service = new LinkProvider(_httpContextAccessor.Object);

            // Act
            var res = service.Host;

            // Assert
            Assert.Equal(_host, res);
        }
示例#23
0
 public void SutCallsCurrentProviderProperties(SwitchingLinkProvider sut, [Substitute] LinkProvider current)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.AddAspxExtension.Should().Be(current.AddAspxExtension);
         sut.AlwaysIncludeServerUrl.Should().Be(current.AlwaysIncludeServerUrl);
         sut.Description.Should().Be(current.Description);
         sut.EncodeNames.Should().Be(current.EncodeNames);
         sut.LanguageEmbedding.Should().Be(current.LanguageEmbedding);
         sut.LanguageLocation.Should().Be(current.LanguageLocation);
         sut.LowercaseUrls.Should().Be(current.LowercaseUrls);
         sut.ShortenUrls.Should().Be(current.ShortenUrls);
         sut.UseDisplayName.Should().Be(current.UseDisplayName);
     }
 }
示例#24
0
        public void GetFullUrlBuilder_BuildsFullUrlWithoutQueryString()
        {
            var actionContext = MockHelpers.ActionContext();

            var actionContextAccessorMock = new Mock <IActionContextAccessor>();

            actionContextAccessorMock.SetupGet(x => x.ActionContext).Returns(actionContext);

            var host = new HostString("test.be", 99);

            Mock.Get(actionContext.HttpContext.Request).SetupGet(x => x.Host).Returns(host);
            Mock.Get(actionContext.HttpContext.Request).SetupGet(x => x.Scheme).Returns("xyz");


            var urlHelper = new Mock <IUrlHelper>().Object;

            var linkProvider = new LinkProvider(actionContextAccessorMock.Object, urlHelper, new TestApiExtensionOptions(new Web.Api.ApiExtensionOptions()));
            var fullUrl      = linkProvider.GetFullUrlBuilder("/v1/test");

            Assert.Equal("xyz://test.be:99/v1/test", fullUrl.ToString());
        }
		public void ExpandLinks(ref string text, LinkProvider provider, UrlOptions options)
		{
			Assert.ArgumentNotNull(text, "text");
			Assert.ArgumentNotNull(options, "urlOptions");
			var linkStart = text.IndexOf("~/link.aspx?", StringComparison.InvariantCulture);
			if (linkStart == -1)
			{
				return;
			}

			var builder = new StringBuilder(text.Length);
			var linkEnd = 0;

			for (; linkStart >= 0; linkStart = text.IndexOf("~/link.aspx?", linkEnd, StringComparison.InvariantCulture))
			{
				var num = text.IndexOf("_z=z", linkStart, StringComparison.InvariantCulture);
				if (num < 0)
				{
					text = builder.ToString();
					return;
				}

				var dynamicLink = DynamicLink.Parse(text.Substring(linkStart, num - linkStart));

				var item = GetItem(dynamicLink);
				var url = "#";
				if (item != null)
				{
					url = provider.GetItemUrl(GetItem(dynamicLink), options);
				}
				var str = text.Substring(linkEnd, linkStart - linkEnd);
				builder.Append(str);
				builder.Append(url);
				linkEnd = num + "_z=z".Length;
			}

			builder.Append(text.Substring(linkEnd));
			text = builder.ToString();
		}
示例#26
0
        internal async Task DownloadLatestVersionTest(OperatingSystem os)
        {
            var operatingSystemProvider = Substitute.For <IOperatingSystemProvider>();

            operatingSystemProvider.GetOperatingSystem().Returns(x => os);

            var linkProvider          = new LinkProvider(operatingSystemProvider);
            var ffmpegExecutablesPath = FFmpeg.ExecutablesPath;

            try {
                FFbinariesVersionInfo currentVersion = JsonConvert.DeserializeObject <FFbinariesVersionInfo>(File.ReadAllText(Resources.FFbinariesInfo));
                FFmpeg.ExecutablesPath = "assemblies";
                if (Directory.Exists("assemblies"))
                {
                    Directory.Delete("assemblies", true);
                }

                FFmpegDownloader._linkProvider = linkProvider;
                await FFmpegDownloader.DownloadLatestVersion(currentVersion);

                if (os == OperatingSystem.Windows32 || os == OperatingSystem.Windows64)
                {
                    Assert.True(File.Exists(Path.Combine("assemblies", "ffmpeg.exe")));
                    Assert.True(File.Exists(Path.Combine("assemblies", "ffprobe.exe")));
                }
                else
                {
                    Assert.True(File.Exists(Path.Combine("assemblies", "ffmpeg")));
                    Assert.True(File.Exists(Path.Combine("assemblies", "ffprobe")));
                }
            }
            finally
            {
                FFmpeg.ExecutablesPath = ffmpegExecutablesPath;
            }
        }
示例#27
0
 public void SutUsesDefaultNameIfCurrentProviderSet(SwitchingLinkProvider sut, [Substitute] LinkProvider current)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.Name.Should().BeNull();
     }
 }
示例#28
0
 /// <summary>
 /// Mocks the link provider.
 /// </summary>
 protected virtual void MockLinkProvider()
 {
     var standardValueProvider = new LinkProvider();
       ProviderHelper<LinkProvider, LinkProviderCollection>.DefaultProvider = standardValueProvider;
       standardValueProvider.Initialize("mock", new NameValueCollection());
 }
        public static string GetWildcardItemUrl(Sitecore.Data.Items.Item wildcardItem, Item realItem, bool useDisplayName, UrlOptions urlOptions = null)
        {
            if (urlOptions == null)
            {
                urlOptions = UrlOptions.DefaultOptions;
            }

            urlOptions.AlwaysIncludeServerUrl = true;
            if (wildcardItem == null || realItem == null)
            {
                return string.Empty;
            }

            var scLinkProvider = new LinkProvider();
            string wildcardUrl = scLinkProvider.GetItemUrl(wildcardItem, urlOptions);
            int wildcardCount = wildcardUrl.Split('/').Where(x => x == ",-w-,").Count();
            wildcardUrl = wildcardUrl.Replace(",-w-,", string.Empty);

            Uri uri = new Uri(wildcardUrl);
            List<string> wildcardItemPathParts = uri.AbsolutePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            ReferenceField wildcardDatasource = wildcardItem.Fields[AppConstants.WildcardDatasourceField];
            if (wildcardDatasource != null)
            {
                List<string> realItemPathParts = new List<string>();
                if (realItem.Axes.GetAncestors().Any(a => a.ID == wildcardDatasource.TargetID))
                {
                    Item ancestor = realItem.Parent;
                    int idx = 1;
                    while (ancestor.ID != wildcardDatasource.TargetID && idx < wildcardCount)
                    {
                        idx++;
                        realItemPathParts.Insert(0, useDisplayName ? ancestor.DisplayName : ancestor.Name);
                        ancestor = ancestor.Parent;
                    }
                }

                string itemUrlName = useDisplayName ? realItem.DisplayName : realItem.Name;
                realItemPathParts.Add(itemUrlName);
                wildcardItemPathParts.AddRange(realItemPathParts);
            }

            UriBuilder uriBuilder = new UriBuilder { Scheme = uri.Scheme, Host = uri.Host, Port = uri.Port, Path = string.Join("/", wildcardItemPathParts) };
            return uriBuilder.Uri.ToString();
        }
示例#30
0
 public void InitializeCallsBaseProviderIfCurrentSet(SwitchingLinkProvider sut, [Substitute] LinkProvider current, string name, NameValueCollection config)
 {
     using (new Switcher <LinkProvider>(current))
     {
         sut.Initialize(name, config);
         current.DidNotReceiveWithAnyArgs().Initialize(name, config);
     }
 }
 public void DisposeRestoresPreviousSitecoreLinkProvider([Frozen] LinkProvider provider, LinkProviderSwitcher sut)
 {
     sut.Dispose();
     LinkManager.Provider.Name.Should().Be("sitecore");
 }
 public RemoveIndexedLinksHandler(ProviderHelper <LinkProvider, LinkProviderCollection> providerHelper)
 {
     _linkProvider = providerHelper.Provider;
 }
示例#33
0
 public OptOutEmail(IEntryRepository entries, IWorldRepository worlds, LinkProvider links)
 {
     this.entries = entries;
     this.worlds  = worlds;
     this.links   = links;
 }