Example #1
0
        /// <summary>
        /// The RegEx matches any HTML attribute values that start with a tilde (~), those that match are passed to ResolveUrl to replace the tilde with the application path.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        /// <remarks>
        /// When used with a Virtual-Directory set-up, this would resolve all URLs correctly.
        /// The recommendation is that the "ResolveUrlsFromTextString" option (in umbracoSettings.config) is set to false for non-Virtual-Directory installs.
        /// </remarks>
        public string EnsureUrls(string text)
        {
            if (_contentSettings.ResolveUrlsFromTextString == false)
            {
                return(text);
            }

            using (var timer = _profilingLogger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
            {
                // find all relative URLs (ie. URLs that contain ~)
                var tags = ResolveUrlPattern.Matches(text);
                _logger.LogDebug("After regex: {Duration} matched: {TagsCount}", timer?.Stopwatch.ElapsedMilliseconds, tags.Count);
                foreach (Match tag in tags)
                {
                    var url = "";
                    if (tag.Groups[1].Success)
                    {
                        url = tag.Groups[1].Value;
                    }

                    // The richtext editor inserts a slash in front of the URL. That's why we need this little fix
                    //                if (url.StartsWith("/"))
                    //                    text = text.Replace(url, ResolveUrl(url.Substring(1)));
                    //                else
                    if (string.IsNullOrEmpty(url) == false)
                    {
                        var resolvedUrl = (url.Substring(0, 1) == "/") ? _ioHelper.ResolveUrl(url.Substring(1)) : _ioHelper.ResolveUrl(url);
                        text = text.Replace(url, resolvedUrl);
                    }
                }
            }

            return(text);
        }
 /// <summary>
 /// Will resolve a virtual path URL to an absolute path, else if it is not a virtual path (i.e. starts with ~/) then
 /// it will just return the path as-is (relative).
 /// </summary>
 /// <param name="ioHelper"></param>
 /// <param name="path"></param>
 /// <returns></returns>
 public static string ResolveRelativeOrVirtualUrl(this IIOHelper ioHelper, string path)
 {
     if (string.IsNullOrWhiteSpace(path))
     {
         return(path);
     }
     return(path.StartsWith("~/") ? ioHelper.ResolveUrl(path) : path);
 }
        public BuildManagerTypeFinder(IIOHelper ioHelper, ILogger logger, ITypeFinderConfig typeFinderConfig = null) : base(logger, typeFinderConfig)
        {
            if (ioHelper == null)
            {
                throw new ArgumentNullException(nameof(ioHelper));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _allAssemblies = new Lazy <HashSet <Assembly> >(() =>
            {
                var isHosted = ioHelper.IsHosted;
                try
                {
                    if (isHosted)
                    {
                        var assemblies = new HashSet <Assembly>(BuildManager.GetReferencedAssemblies().Cast <Assembly>());

                        //here we are trying to get the App_Code assembly
                        var fileExtensions = new[] { ".cs", ".vb" }; //only vb and cs files are supported
                        var appCodeFolder  = new DirectoryInfo(ioHelper.MapPath(ioHelper.ResolveUrl("~/App_code")));
                        //check if the folder exists and if there are any files in it with the supported file extensions
                        if (appCodeFolder.Exists && fileExtensions.Any(x => appCodeFolder.GetFiles("*" + x).Any()))
                        {
                            try
                            {
                                var appCodeAssembly = Assembly.Load("App_Code");
                                if (assemblies.Contains(appCodeAssembly) == false) // BuildManager will find App_Code already
                                {
                                    assemblies.Add(appCodeAssembly);
                                }
                            }
                            catch (FileNotFoundException ex)
                            {
                                //this will occur if it cannot load the assembly
                                logger.Error(typeof(TypeFinder), ex, "Could not load assembly App_Code");
                            }
                        }
                    }
                }
                catch (InvalidOperationException e)
                {
                    if (e.InnerException is SecurityException == false)
                    {
                        throw;
                    }
                }

                // Not hosted, just use the default implementation
                return(new HashSet <Assembly>(base.AssembliesToScan));
            });
        }
        /// <summary>
        /// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are
        /// using does not inherit from UmbracoViewPage
        /// </summary>
        /// <remarks>
        /// See: http://issues.umbraco.org/issue/U4-1614
        /// </remarks>
        public static IHtmlContent PreviewBadge(this IHtmlHelper helper, IUmbracoContextAccessor umbracoContextAccessor, IHttpContextAccessor httpContextAccessor, GlobalSettings globalSettings, IIOHelper ioHelper, ContentSettings contentSettings)
        {
            var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext();

            if (umbracoContext.InPreviewMode)
            {
                var htmlBadge =
                    string.Format(
                        contentSettings.PreviewBadge,
                        ioHelper.ResolveUrl(globalSettings.UmbracoPath),
                        WebUtility.UrlEncode(httpContextAccessor.GetRequiredHttpContext().Request.Path),
                        umbracoContext.PublishedRequest?.PublishedContent?.Id);
                return(new HtmlString(htmlBadge));
            }

            return(HtmlString.Empty);
        }
        public ActionResult Index()
        {
            var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext();
            var store          = umbracoContext.Content;

            if (store.HasContent())
            {
                // If there is actually content, go to the root.
                return(Redirect("~/"));
            }

            var model = new NoNodesViewModel
            {
                UmbracoPath = _ioHelper.ResolveUrl(_globalSettings.Value.UmbracoPath),
            };

            return(View(_globalSettings.Value.NoNodesViewPath, model));
        }
        /// <inheritdoc/>
        public Task ExecuteResultAsync(ActionContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            HttpContext httpContext    = context.HttpContext;
            IIOHelper   ioHelper       = httpContext.RequestServices.GetRequiredService <IIOHelper>();
            string      destinationUrl = ioHelper.ResolveUrl(Url);

            if (_queryString.HasValue)
            {
                destinationUrl += _queryString.ToUriComponent();
            }

            httpContext.Response.Redirect(destinationUrl);

            return(Task.CompletedTask);
        }
        public void CanParseManifest_ScriptsAndStylesheets()
        {
            string          json     = "{}";
            PackageManifest manifest = _parser.ParseManifest(json);

            Assert.AreEqual(0, manifest.Scripts.Length);

            json     = "{javascript: []}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(0, manifest.Scripts.Length);

            json     = "{javascript: ['~/test.js', '~/test2.js']}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(2, manifest.Scripts.Length);

            json     = "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js']}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(2, manifest.Scripts.Length);

            Assert.AreEqual(_ioHelper.ResolveUrl("/test.js"), manifest.Scripts[0]);
            Assert.AreEqual(_ioHelper.ResolveUrl("/test2.js"), manifest.Scripts[1]);

            // kludge is gone - must filter before parsing
            json = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()) + "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js']}";
            Assert.Throws <JsonReaderException>(() => _parser.ParseManifest(json));

            json     = "{}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(0, manifest.Stylesheets.Length);

            json     = "{css: []}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(0, manifest.Stylesheets.Length);

            json     = "{css: ['~/style.css', '~/folder-name/sdsdsd/stylesheet.css']}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(2, manifest.Stylesheets.Length);

            json     = "{propertyEditors: [], css: ['~/stylesheet.css', '~/random-long-name.css']}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(2, manifest.Stylesheets.Length);

            json     = "{propertyEditors: [], javascript: ['~/test.js', '~/test2.js'], css: ['~/stylesheet.css', '~/random-long-name.css']}";
            manifest = _parser.ParseManifest(json);
            Assert.AreEqual(2, manifest.Scripts.Length);
            Assert.AreEqual(2, manifest.Stylesheets.Length);
        }