public BootstrapActionLink(HtmlHelper html, string linkText, ActionResult result)
 {
     this.html = html;
     this._linkText = linkText;
     this._result = result;
     this._actionTypePassed = ActionTypePassed.HtmlActionResult;
 }
Example #2
0
		private static MvcHtmlString GenerateNavigationFor35Or30(HtmlHelper htmlHelper, Language language, string version)
		{
			var builder = new StringBuilder();
			builder.AppendLine("<ul class='nav navbar-nav'>");

			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Getting started", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "start/getting-started" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Indexes", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "indexes/what-are-indexes" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Transformers", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "transformers/what-are-transformers" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Client API", MVC.Docs.ActionNames.Client, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Server", MVC.Docs.ActionNames.Server, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Studio", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "studio/accessing-studio" }, null)));

			builder.AppendLine("<li class='dropdown'>");
			builder.AppendLine("<a href='#' class='dropdown-toggle' data-toggle='dropdown'>Other <span class='caret'></span></a>");
			builder.AppendLine("<ul class='dropdown-menu' role='menu'>");
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Samples", MVC.Docs.ActionNames.Samples, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Glossary", MVC.Docs.ActionNames.Glossary, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Users Issues", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "users-issues/azure-router-timeout" }, null)));
			builder.AppendLine("</ul>");
			builder.AppendLine("</li>");

			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("File System", MVC.Docs.ActionNames.FileSystem, MVC.Docs.Name, new { language = language, version = version, key = "file-system/what-is-ravenfs" }, null)));

			builder.AppendLine("</ul>");

			return new MvcHtmlString(builder.ToString());
		}
 public TabStripCreated(TabFactory itemFactory, string tabStripName, HtmlHelper html, object model = null)
 {
     this.TabStripName = tabStripName;
     this.Html = html;
     this.Model = model;
     this.ItemFactory = itemFactory;
 }
 public BootstrapRadioButton(HtmlHelper html, string htmlFieldName, object value, ModelMetadata metadata)
 {
     this.html = html;
     this._model.htmlFieldName = htmlFieldName;
     this._model.value = value;
     this._model.metadata = metadata;
 }
Example #5
0
 public ListBox(HtmlHelper html, string htmlFieldName, IEnumerable<SelectListItem> selectList, ModelMetadata metadata)
 {
     this.html = html;
     this._model.htmlFieldName = htmlFieldName;
     this._model.selectList = selectList;
     this._model.metadata = metadata;
 }
Example #6
0
        /// <summary>
        /// Creates new instance of scope, here writer is replaced
        /// </summary>
        /// <param name="helper">Helper where writer shoud be replaced</param>
        /// <param name="writer">Writer to use in place</param>
        public WriterScope(HtmlHelper helper, TextWriter writer)
        {
            _helper = helper;
            _original = _helper.ViewContext.Writer;

            _helper.ViewContext.Writer = writer;
        }
            public void WritesExpectedCollectionIndexHiddenInput_WhenThereIsAnIndexInRequestData()
            {
                const string collectionName = "CollectionName";
                var index0 = Guid.NewGuid();
                var index1 = Guid.NewGuid();
                var indexes = string.Format("{0},{1}", index0, index1);
                var httpContext = new Mock<HttpContextBase>();
                var httpContextItems = new Dictionary<string, object>();
                httpContext.Setup(p => p.Items).Returns(httpContextItems);

                var httpRequest = new Mock<HttpRequestBase>();
                httpRequest.Setup(i => i[It.Is<string>(s => s == string.Format("{0}.index", collectionName))])
                    .Returns(indexes);
                httpContext.Setup(p => p.Request).Returns(httpRequest.Object);

                var viewContext = new ViewContext();
                var writer = new StringWriter();
                viewContext.Writer = writer;

                var html = new HtmlHelper(viewContext, new FakeViewDataContainer());
                viewContext.HttpContext = httpContext.Object;

                using (var result = html.BeginCollectionItem(collectionName))
                {
                    Assert.That(result, Is.Not.Null);
                }

                var text = writer.ToString();
                Assert.That(text,
                            Is.Not.Null
                              .And.Not.Empty
                              .And.StringStarting(string.Format(@"<input type=""hidden"" name=""{0}.index"" autocomplete=""off"" value=""{1}"" />", collectionName, index0)));
            }
Example #8
0
        public static string RenderSitecorePlaceHolder(string key)
        {
            var sublayoutId = GetSublayoutIdFromPlaceHolder(Sitecore.Context.Item[Sitecore.FieldIDs.LayoutField], key);
            if (!string.IsNullOrEmpty(sublayoutId))
            {
                var layoutItem = Sitecore.Context.Database.GetItem(ID.Parse(sublayoutId));
                var controllerName = layoutItem.Fields["Controller"].Value;
                var actionName = layoutItem.Fields["Action"].Value;

                HttpContext.Current.RewritePath(string.Concat("/", controllerName, "/", actionName));

                RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
                if (routeData != null)
                {
                    var factory = new ControllerFactory();
                    var httpContextBase = new HttpContextWrapper(HttpContext.Current);
                    var context = new RequestContext(httpContextBase, routeData);
                    Type type = factory.GetController(context, controllerName);

                    if (type != null)
                    {
                        var controller = (Controller)factory.GetController(context, type);

                        var controllerContext = new ControllerContext(httpContextBase, routeData, controller);
                        var viewContext = new ViewContext(controllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null);

                        var helper = new HtmlHelper(viewContext, new ViewPage());

                        return helper.Action(actionName, controllerName).ToHtmlString();
                    }
                }
                HttpContext.Current.RewritePath("default.aspx");
            }
            return "";
        }
Example #9
0
        public static IEnumerable<SelectListItem> GetSelectListItems(HtmlHelper html, ISelectListBuilder dropDownList, string expressionText)
        {
            string fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);

            bool flag = false;

            IEnumerable<SelectListItem> selectList = dropDownList.SelectList();
            bool allowMultiple = dropDownList.Attr("multiple") == "multiple";

            if (selectList == null)
            {
                selectList = html.GetSelectListItemsFromViewData(expressionText);
                flag = true;
            }
            object defaultValue = allowMultiple ? html.GetModelStateValue(fullHtmlFieldName, typeof(string[])) : html.GetModelStateValue(fullHtmlFieldName, typeof(string));
            if (!flag && defaultValue == null && !String.IsNullOrEmpty(expressionText))
            {
                defaultValue = html.ViewData.Eval(expressionText);
            }
            if (defaultValue != null)
            {
                selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
            }
            return selectList;
        }
Example #10
0
        public static MvcHtmlString RenderComponentPresentations(HtmlHelper helper, string[] byComponentTemplate, string bySchema, IComponentPresentationRenderer renderer)
        {
            _logger.Information(">>RenderComponentPresentations", LoggingCategory.Performance);
            IComponentPresentationRenderer cpr = renderer;
            IPage page = null;
            if (helper.ViewData.Model is IPage)
            {
                page = helper.ViewData.Model as IPage;
            }
            else
            {
                try
                {
                    page = helper.ViewContext.Controller.ViewBag.Page;
                }
                catch
                {
                    return new MvcHtmlString("<!-- RenderComponentPresentations can only be used if the model is an instance of IPage or if there is a Page property in the viewbag with type IPage -->");
                }
            }

            if (renderer == null)
            {
                _logger.Debug("about to create DefaultComponentPresentationRenderer", LoggingCategory.Performance);
                renderer = _renderer;
                _logger.Debug("finished creating DefaultComponentPresentationRenderer", LoggingCategory.Performance);
            }

            _logger.Debug("about to call renderer.ComponentPresentations", LoggingCategory.Performance);
            MvcHtmlString output = renderer.ComponentPresentations(page, helper, byComponentTemplate, bySchema);
            _logger.Debug("finished calling renderer.ComponentPresentations", LoggingCategory.Performance);
            _logger.Information("<<RenderComponentPresentations", LoggingCategory.Performance);

            return output;
        }
Example #11
0
 /// <summary>
 /// Render an entity (Component Presentation)
 /// </summary>
 /// <param name="item">The Component Presentation object</param>
 /// <param name="helper">The HTML Helper</param>
 /// <param name="containerSize">The size of the containing element (in grid units)</param>
 /// <param name="excludedItems">A list of view names, if the Component Presentation maps to one of these, it is skipped.</param>
 /// <returns>The rendered content</returns>
 public override MvcHtmlString RenderEntity(object item, HtmlHelper helper, int containerSize = 0, List<string> excludedItems = null)
 {
     var cp = item as IComponentPresentation;
     var mvcData = ContentResolver.ResolveMvcData(cp);
     if (cp != null && (excludedItems == null || !excludedItems.Contains(mvcData.ViewName)))
     {
         var parameters = new RouteValueDictionary();
         int parentContainerSize = helper.ViewBag.ContainerSize;
         if (parentContainerSize == 0)
         {
             parentContainerSize = SiteConfiguration.MediaHelper.GridSize;
         }
         if (containerSize == 0)
         {
             containerSize = SiteConfiguration.MediaHelper.GridSize;
         }
         parameters["containerSize"] = (containerSize * parentContainerSize) / SiteConfiguration.MediaHelper.GridSize;
         parameters["entity"] = cp;
         parameters["area"] = mvcData.ControllerAreaName;
         foreach (var key in mvcData.RouteValues.Keys)
         {
             parameters[key] = mvcData.RouteValues[key];
         }
         MvcHtmlString result = helper.Action(mvcData.ActionName, mvcData.ControllerName, parameters);
         if (WebRequestContext.IsPreview)
         {
             result = new MvcHtmlString(TridionMarkup.ParseEntity(result.ToString()));
         }
         return result;
     }
     return null;
 }
 internal PagerBuilder(HtmlHelper html, AjaxHelper ajax, string actionName, string controllerName,
     int totalPageCount, int pageIndex, PagerOptions pagerOptions, string routeName, RouteValueDictionary routeValues,
     MvcAjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
 {
     _ajaxPagingEnabled = (ajax != null);
     if (pagerOptions == null)
         pagerOptions = new PagerOptions();
     _html = html;
     _ajax = ajax;
     _actionName = actionName;
     _controllerName = controllerName;
     if (pagerOptions.MaxPageIndex == 0 || pagerOptions.MaxPageIndex > totalPageCount)
         _totalPageCount = totalPageCount;
     else
         _totalPageCount = pagerOptions.MaxPageIndex;
     _pageIndex = pageIndex;
     _pagerOptions = pagerOptions;
     _routeName = routeName;
     _routeValues = routeValues;
     _ajaxOptions = ajaxOptions;
     _htmlAttributes = htmlAttributes;
     // start page index
     _startPageIndex = pageIndex - (pagerOptions.NumericPagerItemCount / 2);
     if (_startPageIndex + pagerOptions.NumericPagerItemCount > _totalPageCount)
         _startPageIndex = _totalPageCount + 1 - pagerOptions.NumericPagerItemCount;
     if (_startPageIndex < 1)
         _startPageIndex = 1;
     // end page index
     _endPageIndex = _startPageIndex + _pagerOptions.NumericPagerItemCount - 1;
     if (_endPageIndex > _totalPageCount)
         _endPageIndex = _totalPageCount;
 }
 public BootstrapActionLink(HtmlHelper html, string linkText, string actionName)
 {
     this.html = html;
     this._linkText = linkText;
     this._actionName = actionName;
     this._actionTypePassed = ActionTypePassed.HtmlRegular;
 }
 public BootstrapActionLink(HtmlHelper html, string linkText, Task<ActionResult> taskResult)
 {
     this.html = html;
     this._linkText = linkText;
     this._taskResult = taskResult;
     this._actionTypePassed = ActionTypePassed.HtmlTaskResult;
 }
Example #15
0
        public Pager(HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary, string labelPrevious, string labelNext)
            : this()
        {
            this._htmlHelper = htmlHelper;
            this.pageSize = pageSize;
            this.currentPage = currentPage;
            this.totalItemCount = totalItemCount;
            this.linkWithoutPageValuesDictionary = valuesDictionary;
            var queryString = htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString;
            //if (queryString.Count > 0)
            //{
            //    //Add querystring into routevalues.
            //    foreach (var key in queryString.Keys)
            //    {
            //        if (!valuesDictionary.ContainsKey(key))
            //        {
            //            valuesDictionary.Add(key, queryString[key]);
            //        }
            //    }
            //}

            if (labelPrevious != null)
            {
                this.LabelPrevious = labelPrevious;
            }
            if (labelNext != null)
            {
                this.LabelNext = labelNext;
            }
        }
Example #16
0
        public static string BuildContent(HtmlHelper html, string Content)
        {
            var matches = Regex.Matches(Content, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                string url = match.Groups[1].Value;
                if (!url.Contains("cid"))
                {

                    string imagetagstr = Postal.HtmlExtensions.EmbedImage(html, url, "").ToHtmlString();
                    string newcid = Regex.Match(imagetagstr, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
                    Content = Content.Replace(url, newcid);
                }
            }

            matches = Regex.Matches(Content, @"background:url\('(?<bgpath>.*)'\)", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                string url = match.Groups[1].Value;
                if (!url.Contains("cid"))
                {
                    string imagetagstr = Postal.HtmlExtensions.EmbedImage(html, url, "").ToHtmlString();
                    string newcid = Regex.Match(imagetagstr, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;

                    Content = Content.Replace(url, newcid);
                }
            }
            return Content;
        }
Example #17
0
 public FrontHtmlHelper(Page_Context context, HtmlHelper html, ViewRender viewRender, ProxyRender proxyRender)
 {
     this.PageContext = context;
     this.Html = html;
     this.ViewRender = viewRender;
     this.ProxyRender = proxyRender;
 }
Example #18
0
        public static MvcHtmlString RenderPopup(HtmlHelper helper, TypeContext typeContext, RenderPopupMode mode, EntityBase line, bool isTemplate = false)
        {
            TypeContext tc = TypeContextUtilities.CleanTypeContext((TypeContext)typeContext);

            ViewDataDictionary vdd = GetViewData(helper, line, tc);

            string partialViewName = line.PartialViewName ?? OnPartialViewName(tc);

            vdd[ViewDataKeys.PartialViewName] = partialViewName;
            vdd[ViewDataKeys.ViewMode] = !line.ReadOnly;
            vdd[ViewDataKeys.ViewMode] = ViewMode.View;
            vdd[ViewDataKeys.ShowOperations] = true;
            vdd[ViewDataKeys.SaveProtected] = OperationLogic.IsSaveProtected(tc.UntypedValue.GetType());
            vdd[ViewDataKeys.WriteEntityState] = 
                !isTemplate &&
                !(tc.UntypedValue is EmbeddedEntity) &&
                ((ModifiableEntity)tc.UntypedValue).Modified == ModifiedState.SelfModified;

            switch (mode)
            {
                case RenderPopupMode.Popup:
                    return helper.Partial(Navigator.Manager.PopupControlView, vdd);
                case RenderPopupMode.PopupInDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                        helper.Partial(Navigator.Manager.PopupControlView, vdd),  
                        "",
                        new Dictionary<string, object> { { "style", "display:none" } });
                default:
                    throw new InvalidOperationException();
            }
        }
            public void WritesCollectionIndexHiddenInput_WhenThereIsNothingInRequestData()
            {
                const string collectionName = "CollectionName";
                var httpContext = new Mock<HttpContextBase>();
                var httpContextItems = new Dictionary<string, object>();
                httpContext.Setup(p => p.Items).Returns(httpContextItems);

                var httpRequest = new Mock<HttpRequestBase>();
                httpContext.Setup(p => p.Request).Returns(httpRequest.Object);

                var viewContext = new ViewContext();
                var writer = new StringWriter();
                viewContext.Writer = writer;

                var html = new HtmlHelper(viewContext, new FakeViewDataContainer());
                viewContext.HttpContext = httpContext.Object;

                using (var result = html.BeginCollectionItem(collectionName))
                {
                    Assert.That(result, Is.Not.Null);
                }

                var text = writer.ToString();
                Assert.That(text,
                            Is.Not.Null
                              .And.Not.Empty
                              .And.StartsWith(string.Format(@"<input type=""hidden"" name=""{0}.index"" autocomplete=""off"" value=""", collectionName))
                              .And.Contains(@""" />"));
            }
Example #20
0
        public static MvcHtmlString RenderContent(HtmlHelper helper, TypeContext typeContext, RenderContentMode mode, EntityBase line)
        {
            TypeContext tc = TypeContextUtilities.CleanTypeContext((TypeContext)typeContext);

            ViewDataDictionary vdd = GetViewData(helper, line, tc);
            
            string partialViewName = line.PartialViewName ?? OnPartialViewName(tc);

            switch (mode)
            {
                case RenderContentMode.Content:
                    return helper.Partial(partialViewName, vdd);

                case RenderContentMode.ContentInVisibleDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                      helper.Partial(partialViewName, vdd), "",
                      null);
                case RenderContentMode.ContentInInvisibleDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                        helper.Partial(partialViewName, vdd), "",
                         new Dictionary<string, object> { { "style", "display:none" } });
                default:
                    throw new InvalidOperationException();
            }
        }
Example #21
0
 private static IDictionary<string, MvcHtmlString> GetFlashMessages(HtmlHelper helper, string sessionKey)
 {
     sessionKey = "Flash." + sessionKey;
     return (helper.ViewContext.TempData[sessionKey] != null
                 ? (IDictionary<string, MvcHtmlString>)helper.ViewContext.TempData[sessionKey]
                 : null);
 }
        public void DisplayNameConsultsMetadataProviderForMetadataAboutProperty()
        {
            // Arrange
            Model model = new Model { PropertyName = "propertyValue" };

            ViewDataDictionary viewData = new ViewDataDictionary();
            Mock<ViewContext> viewContext = new Mock<ViewContext>();
            viewContext.Setup(c => c.ViewData).Returns(viewData);

            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);

            HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);
            viewData.Model = model;

            MetadataHelper metadataHelper = new MetadataHelper();

            metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), "PropertyName"))
                .Returns(metadataHelper.Metadata.Object)
                .Verifiable();

            // Act
            html.DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);

            // Assert
            metadataHelper.MetadataProvider.Verify();
        }
Example #23
0
        public Displayable(HtmlHelper helper, string propertyName, ContentItem currentItem)
            : base(helper, currentItem)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            this.propertyName = propertyName;
        }
 /// <summary>
 /// The container breaks the slider content, and we do not need it,
 /// since we won't edit the content when using this renderer
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="contentArea"></param>
 public virtual void RenderWithoutContainer(HtmlHelper htmlHelper, ContentArea contentArea)
 {
     if ((contentArea != null) && !contentArea.IsEmpty)
     {
         RenderContentAreaItems(htmlHelper, contentArea.FilteredItems);
     }
 }
Example #25
0
 public PopUpMenu(HtmlHelper helper, string id, int minWidth = 0)
     : base(helper)
 {
     Id = id;
     MinWidth = minWidth;
     Items = new List<PopUpMenuItem>();
 }
        protected override string GetContentAreaItemCssClass(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem)
        {
            var childrenCssClass = htmlHelper.ViewData["ChildrenCssClass"];
            if(childrenCssClass != null)
            {
                return childrenCssClass.ToString();
            }

            var tag = GetContentAreaItemTemplateTag(htmlHelper, contentAreaItem);

            var content = contentAreaItem.GetContent(ContentRepository);
            if(content != null)
            {
                if (tag == null )
                {
                    // Let block decide what to use as default if not
                    // specified on the content area itself
                    tag = GetDefaultDisplayOption(content);
                    if (tag == null)
                    {
                        // Default is always the smalles one we've got
                        tag = WebGlobal.ContentAreaTags.OneThirdWidth;
                    }
                }
                htmlHelper.ViewContext.ViewData["Tag"] = tag;
                return string.Format("block {0} {1} {2}",
                    GetTypeSpecificCssClasses(content),
                    GetCssClassForTag(tag),
                    tag);
            }
            else
            {
                return WebGlobal.ContentAreaTags.NoRenderer;
            }
        }
        private static void RenderPartial(HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer)
        {
            ViewDataDictionary newViewData;
            if (model == null)
            {
                newViewData = viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData);
            }
            else
            {
                newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model };
            }

            var controller = htmlHelper.ViewContext.Controller as Controller;
            var viewEngineCollection = controller != null ? controller.ViewEngineCollection : ViewEngines.Engines;
            var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer);
            var result = viewEngineCollection.FindPartialView(newViewContext, partialViewName);
            if (result.View != null)
            {
                result.View.Render(newViewContext, writer);
            }
            else
            {
                var locationsText = new StringBuilder();
                foreach (string location in result.SearchedLocations)
                {
                    locationsText.AppendLine();
                    locationsText.Append(location);
                }

                throw new InvalidOperationException("The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched: {1}".Arrange(partialViewName, locationsText));
            }
        }
Example #28
0
        public static IHtmlString Render(string alias, HtmlHelper<RenderModel> helper)
        {

            try
            {
                // If request is coming from frontend then always show frontend content, check authentication if it comes from backend (.aspx)

                var isAuthenticated = false;

                if (HttpContext.Current.Request.Path.Contains(".aspx"))
                {
                    isAuthenticated = Authorize.isAuthenticated();
                }

                var view = ViewHelper.Get(alias, isAuthenticated);

                var culture = CultureInfo.CreateSpecificCulture(UmbracoContext.Current.PublishedContentRequest.Culture.Name);

                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                var model = helper.Partial(view.viewName, view);

                return new HtmlString(model.ToString());

            }
            catch (Exception ex)
            {

                Log.Error("Canvas Error on Render in API.", ex);
                return new HtmlString("");

            }

        }
        public void VeneerScripts_handles_content_types_with_no_scripts()
        {
            // Arrange
            var service = new Mock<IContentService>();
            var content = new Content
            {
                RefreshDate = DateTime.Now,
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = "Footer", Html = "<div id='hello' />", Scripts = new List<ContentScript>()
                    }
                }
            };
            service.Setup(x => x.Get(It.IsAny<ContentTypes>())).Returns(content);
            var contentTypes = new List<ContentTypes> { ContentTypes.Footer };

            var model = new VeneerBaseViewModel(service.Object, contentTypes);

            var viewContext = new ViewContext();
            var viewDataContainer = new Mock<IViewDataContainer>();
            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer.Object);

            // Act
            var result = htmlHelper.VeneerScripts(model).ToHtmlString();

            // Assert
            Assert.That(result, Is.Empty);
        }
Example #30
0
        public static MvcHtmlString IncludeRejuicedJsFor(HtmlHelper instance, string filename)
        {
            var cachedValue = GetCachedIncludesFor(filename);
            if (cachedValue != null)
            {
                return cachedValue.RenderHtml();
            }

            var toInclude = GetIncludesFor(filename);
            var config = RejuicerEngine.GetConfigFor(filename);

            if (config == null)
            {
                return MvcHtmlString.Create("");
            }

            var dependencies = config.GetDependencies();

            var scripts = MvcHtmlString.Create(string.Join("\n", toInclude.Select(f =>
            {
                // Output <script src='' type=''>
                var script = new TagBuilder("script");
                script.Attributes.Add("src", UrlHelper.GenerateContentUrl(f, new HttpContextWrapper(HttpContext.Current)));
                script.Attributes.Add("type", "text/javascript");

                return script.ToString(TagRenderMode.Normal);
            }).ToArray()));

            var cachedIncludes = new IncludesCacheModel { IncludesHtml = scripts, HashValue = config.GetHashValue(cacheProvider) };

            SetCachedIncludesFor(filename, cachedIncludes, dependencies);

            return cachedIncludes.RenderHtml();
        }