/// <summary>
        /// Gets the layout name from template title. This method will strip and replace the special characters.
        /// </summary>
        /// <param name="templateTitle">The template title.</param>
        /// <returns></returns>
        public virtual string GetLayoutName(string templateTitle)
        {
            templateTitle = this.StripPackageNameFromTemplateName(templateTitle);

            var packagesManager = new PackagesManager();
            return packagesManager.StripInvalidCharacters(templateTitle);
        }
        /// <summary>
        /// Registering the scripts for ZoneEditor.
        /// </summary>
        /// <param name="event">The event.</param>
        private void RegisteringScriptsHandler(IScriptsRegisteringEvent @event)
        {
            var packagesManager = new PackagesManager();
            if (@event.Sender.GetType() == typeof(ZoneEditor))
            {
                var scriptRootPath = "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly);

                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Angular/angular.min.js"));
                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Angular/angular-route.min.js"));

                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Bootstrap/js/ui-bootstrap-tpls-0.10.0.min.js"));
                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/ModalDialogModule.js"));
                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/ControlPropertyServices.js"));
                @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Kendo/angular-kendo.js"));

                var currentPackage = packagesManager.GetCurrentPackage();
                if (!currentPackage.IsNullOrEmpty())
                {
                    var packageVar = "var sf_package = '{0}';".Arrange(currentPackage);
                    ((ZoneEditor)@event.Sender).Page.ClientScript.RegisterStartupScript(@event.Sender.GetType(), "sf_package",
                        packageVar + @"Sys.Net.WebRequestManager.add_invokingRequest(function (executor, args) {
                            var url = args.get_webRequest().get_url();
                            if (url.indexOf('?') == -1)
                                url += '?package=' + encodeURIComponent(sf_package);
                            else
                                url += '&package=' + encodeURIComponent(sf_package);
                            args.get_webRequest().set_url(url);
                        });",
                        addScriptTags: true);
                }
            }
        }
        /// <summary>
        /// Strips the name of the package name from template.
        /// If there is no existing package presented on the searched location the method will preserve the full template name.
        /// </summary>
        /// <param name="templateTitle">Title of the template.</param>
        /// <returns></returns>
        private string StripPackageNameFromTemplateName(string templateTitle)
        {
            var parts = templateTitle.Split('.');

            if (parts.Length > 1)
            {
                var packagesManager = new PackagesManager();
                var packageVirtualPath = packagesManager.GetPackageVirtualPath(parts[0]);
                var packagePath = HostingEnvironment.MapPath(packageVirtualPath);
                if (Directory.Exists(packagePath))
                    templateTitle = string.Join(".", parts, 1, parts.Length - 1);
            }

            return templateTitle;
        }
        private static IList<Func<string, string>> GetControllerPathTransformations(Controller controller, string customPath)
        {
            var packagesManager = new PackagesManager();
            var currentPackage = packagesManager.GetCurrentPackage();
            var pathTransformations = new List<Func<string, string>>();

            if (controller.RouteData != null && controller.RouteData.Values.ContainsKey("widgetName"))
            {
                var widgetName = (string)controller.RouteData.Values["widgetName"];
                var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(widgetName);
                var widgetVp = FrontendControllerFactory.AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType));
                pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(widgetVp, currentPackage, widgetName));
            }

            var controllerVp = customPath ?? FrontendControllerFactory.AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controller.GetType().Assembly));
            pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(controllerVp, currentPackage));

            return pathTransformations;
        }
        public void GetPackageFromUrl_FakeCurrentUrlInHttpContext_VerifyThePackageNameIsCorrect()
        {
            //Arrange: Initialize the PackagesManager and create fake HttpContextWrapper which has fake request URL with the package name set as query parameter
            var packageManager = new PackagesManager();
            string packageName = string.Empty;

            var context = new HttpContextWrapper(new HttpContext(
                new HttpRequest(null, "http://tempuri.org", "package=testPackageName"),
                new HttpResponse(null)));

            //Act: Get the package name from the request URL query string
            SystemManager.RunWithHttpContext(context, () =>
            {
                packageName = packageManager.GetPackageFromUrl();
            });

            //Assert: Verify if the manager properly strips all invalid characters
            Assert.AreEqual<string>("testPackageName", packageName, "The package name was not resolved correctly");
        }
        public void GetCurrentPackage_FakeContext_VerifyThePackageNameIsCorrect()
        {
            //Arrange: Initialize the PackagesManager and create fake HttpContextWrapper which has fake package name set as parameter in its parameters collection
            var packageManager = new PackagesManager();
            string packageName = string.Empty;

            var context = new HttpContextWrapper(new HttpContext(
                new HttpRequest(null, "http://tempuri.org", null),
                new HttpResponse(null)));
            context.Items[PackagesManager.CurrentPackageKey] = "testPackageName";

            //Act:  Get the package name from the request parameters collection
            SystemManager.RunWithHttpContext(context, () =>
            {
                packageName = packageManager.GetCurrentPackage();
            });

            //Assert: Verify if the manager properly strips all invalid characters
            Assert.AreEqual<string>("testPackageName", packageName, "The package name was not resolved correctly");
        }
        public void AppendPackageParam_GivenUrl_VerifyThePackageNameIsAppendedCorrectly()
        {
            //Arrange: Initialize the PackagesManager and create variables holding the package name and fake URL to which the package will be appended
            var packageManager = new PackagesManager();
            string urlWithParamters = @"http://fakedomain.org/homePage?fakeParam=0";
            string urlWithNoParamters = @"http://fakedomain.org/homePage";
            string packageName = "fakePackageName";
            string appendedUrhWithParams;
            string appendedUrWithNoParams;
            string appendedUrlWithEmptyPackagename;

            //Act: append the package name
            appendedUrlWithEmptyPackagename = packageManager.AppendPackageParam(urlWithNoParamters, null);
            appendedUrhWithParams = packageManager.AppendPackageParam(urlWithParamters, packageName);
            appendedUrWithNoParams = packageManager.AppendPackageParam(urlWithNoParamters, packageName);

            //Assert: Verify the package name is properly appended
            Assert.AreEqual<string>(urlWithNoParamters, appendedUrlWithEmptyPackagename, "The URL must not be changed due to empty package name passed as parameter");
            Assert.AreEqual<string>(string.Format("http://fakedomain.org/homePage?fakeParam=0&package={0}", packageName), appendedUrhWithParams, "The package name was not appended correctly as a second parameter");
            Assert.AreEqual<string>(string.Format("http://fakedomain.org/homePage?package={0}", packageName), appendedUrWithNoParams, "The package name was not appended correctly as a parameter");
        }
        public void PackagesManager_GetVirtualPathForGivenPackage_VerifyTheVirtualPathIsCorrect()
        {
            //Arrange: Initialize the PackagesManager and a fake package name
            var packageManager = new PackagesManager();
            string packageName = "fakePackageName";
            string packageVirtualpath;

            //Act: gets the package virtual path
            packageVirtualpath = packageManager.GetPackageVirtualPath(packageName);

            //Assert: Verify if the manager throws an error if the parameter is null and if the package virtual path is correct
            try
            {
                packageManager.GetPackageVirtualPath(null);
                Assert.Fail("Expected exception was not thrown");
            }
            catch
            {
            }
            Assert.AreEqual<string>(string.Format("~/{0}/{1}", PackagesManager.PackagesFolder, packageName), packageVirtualpath, "Package virtual path is not correct");
        }
Exemple #9
0
        /// <summary>
        /// Resolves URL based on the current widget.
        /// </summary>
        /// <param name="helper">The URL helper.</param>
        /// <param name="contentPath">The content path.</param>
        /// <returns>Resolved URL.</returns>
        /// <exception cref="System.ArgumentNullException">contentPath</exception>
        /// <exception cref="System.InvalidOperationException">
        /// Could not resolve the given URL because RouteData of the current context is null.
        /// or
        /// Could not resolve the given URL because RouteData does not contain \controller\ key.
        /// </exception>
        public static string WidgetContent(this UrlHelper helper, string contentPath)
        {
            var packagesManager = new PackagesManager();

            if (contentPath.IsNullOrEmpty())
            {
                throw new ArgumentNullException("contentPath");
            }

            if (contentPath.StartsWith("~") || contentPath.StartsWith("/") || contentPath.Contains("://"))
            {
                return helper.Content(contentPath);
            }

            if (helper.RequestContext.RouteData == null)
            {
                throw new InvalidOperationException("Could not resolve the given URL because RouteData of the current context is null.");
            }

            string controllerName;
            if (helper.RequestContext.RouteData.Values.ContainsKey("controller"))
            {
                controllerName = (string)helper.RequestContext.RouteData.Values["controller"];
            }
            else
            {
                throw new InvalidOperationException("Could not resolve the given URL because RouteData does not contain \"controller\" key.");
            }

            var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(controllerName);
            var widgetPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType);
             var packageName = packagesManager.GetCurrentPackage();

            //"widgetName" is a parameter in the route of the Designer. It allows us to have a special fallback logic
            //where we first check for the requested resource in the widget assembly and then fallback to the current controller assembly.
            object widgetName;
            if (helper.RequestContext.RouteData.Values.TryGetValue("widgetName", out widgetName))
            {
                controllerType = FrontendManager.ControllerFactory.ResolveControllerType((string)widgetName);
                var alternatePath = FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType);
                alternatePath = packagesManager.AppendPackageParam("~/" + alternatePath + contentPath, packageName);
                if (HostingEnvironment.VirtualPathProvider == null || HostingEnvironment.VirtualPathProvider.FileExists(alternatePath))
                {
                    return helper.Content(alternatePath);
                }
            }

            var resolvedPath = packagesManager.AppendPackageParam("~/" + widgetPath + contentPath, packageName);

            //If no resource is found for the current widget virtual path then get URL for Telerik.Sitefinity.Frontend.
            if (HostingEnvironment.VirtualPathProvider == null || HostingEnvironment.VirtualPathProvider.FileExists(resolvedPath))
            {
                return helper.Content(resolvedPath);
            }
            else
            {
                resolvedPath = packagesManager.AppendPackageParam("~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(UrlHelpers).Assembly)
                     + contentPath, packageName);
                return helper.Content(resolvedPath);
            }
        }
        public void StripInvalidCharacters_TitleWithInvalidCharacters_VerifyStringIsProperlyInvalidated()
        {
            //Arrange: Initialize the PackagesManager and a fake package name
            var packageManager = new PackagesManager();
            string title = "fake\\/Title<Name>With:Invalid?Chars\"And*Symbols|Included";
            string cleanedTitle;

            //Act: clean the title
            cleanedTitle = packageManager.StripInvalidCharacters(title);

            //Assert: Verify if the manager properly strips all invalid characters
            Assert.AreEqual<string>("fake_Title_Name_With_Invalid_Chars_And_Symbols_Included", cleanedTitle, "Title is not striped correctly");
        }
Exemple #11
0
        /// <summary>
        /// Gets the path transformations.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <returns></returns>
        private IList<Func<string, string>> GetPathTransformations(Controller controller)
        {
            var packagesManager = new PackagesManager();

            var currentPackage = packagesManager.GetCurrentPackage();
            var pathTransformations = new List<Func<string, string>>(1);
            var baseVirtualPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly);

            pathTransformations.Add(path =>
                {
                    //{1} is the ControllerName argument in VirtualPathProviderViewEngines
                    var result = path
                                    .Replace("{1}", "Layouts")
                                    .Replace("~/", "~/{0}Mvc/".Arrange(baseVirtualPath));

                    if (currentPackage.IsNullOrEmpty())
                        result += "#" + currentPackage + Path.GetExtension(path);

                    return result;
                });

            return pathTransformations;
        }