public void GetComponentPresentationFromComponent() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("component"); Assert.IsNotNull(cp); Assert.IsFalse(string.IsNullOrEmpty(cp.Component.Title) || cp.ComponentTemplate == null); }
public void BuildEntityModel(ref EntityModel entityModel, IComponentPresentation cp, Localization localization) { using (new Tracer(entityModel, cp, localization)) { IFieldSet contextExpressionsFieldSet; if (cp.ExtensionData == null || !cp.ExtensionData.TryGetValue(Constants.ContextExpressionsKey, out contextExpressionsFieldSet)) { // No Context Expressions found; nothing to do. return; } ContextExpressionConditions conditions = new ContextExpressionConditions(); IField includeField; if (contextExpressionsFieldSet.TryGetValue("Include", out includeField)) { conditions.Include = includeField.Values.ToArray(); } IField excludeField; if (contextExpressionsFieldSet.TryGetValue("Exclude", out excludeField)) { conditions.Exclude = excludeField.Values.ToArray(); } entityModel.SetExtensionData(Constants.ContextExpressionsKey, conditions); } }
public virtual void BuildEntityModel(ref EntityModel entityModel, IComponentPresentation cp, Localization localization) { using (new Tracer(entityModel, cp, localization)) { MvcData mvcData = GetMvcData(cp); Type modelType = ModelTypeRegistry.GetViewModelType(mvcData); // NOTE: not using ModelBuilderPipeline here, but directly calling our own implementation. BuildEntityModel(ref entityModel, cp.Component, modelType, localization); entityModel.XpmMetadata.Add("ComponentTemplateID", cp.ComponentTemplate.Id); entityModel.XpmMetadata.Add("ComponentTemplateModified", cp.ComponentTemplate.RevisionDate.ToString("yyyy-MM-ddTHH:mm:ss")); entityModel.XpmMetadata.Add("IsRepositoryPublished", cp.IsDynamic ? "true" : "false"); entityModel.MvcData = mvcData; // add html classes to model from metadata // TODO: move to CreateViewModel so it can be merged with the same code for a Page/PageTemplate IComponentTemplate template = cp.ComponentTemplate; if (template.MetadataFields != null && template.MetadataFields.ContainsKey("htmlClasses")) { // strip illegal characters to ensure valid html in the view (allow spaces for multiple classes) entityModel.HtmlClasses = template.MetadataFields["htmlClasses"].Value.StripIllegalCharacters(@"[^\w\-\ ]"); } if (cp.IsDynamic) { // update Entity Identifier to that of a DCP entityModel.Id = GetDxaIdentifierFromTcmUri(cp.Component.Id, cp.ComponentTemplate.Id); } } }
public void ComponentId() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "componentlink"); TestViewModelA model = ViewModelFactory.BuildViewModel(cp) as TestViewModelA; Assert.IsNotNull(model.Id, "ComponentId is not set"); }
private static MvcHtmlString RenderComponentPresentation(IComponentPresentation cp, HtmlHelper htmlHelper) { string controller = _configuration.ComponentPresentationController; if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("controller")) { controller = cp.ComponentTemplate.MetadataFields["controller"].Value; } if (string.IsNullOrEmpty(controller)) { throw new InvalidOperationException("Controller was not configured in component template metadata or in application settings. " + "Unable to Render component presentation."); } string action = _configuration.ComponentPresentationAction; if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("action")) { action = cp.ComponentTemplate.MetadataFields["action"].Value; } if (string.IsNullOrEmpty(action)) { throw new InvalidOperationException("Action was not configured in component template metadata or in application settings. " + "Unable to Render component presentation."); } _loggerService.Debug("about to render component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); //return ChildActionExtensions.Action(htmlHelper, action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); MvcHtmlString result = htmlHelper.Action(action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); _loggerService.Debug("finished rendering component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); return(result); }
/// <summary> /// Generates a SiteEdit tag for a componentpresentation. It also needs to know which region it's in (for component /// swapping) and the order of the page (for a true unique ID). /// </summary> /// <param name="cp">The componentpresentation to mark.</param> /// <returns>string representing the JSON SiteEdit tag.</returns> public static string GenerateSiteEditComponentTag(IComponentPresentation cp) { // is query based tells us if the dcp was the result of a broker query and the component presentation is not embedded on the page string isQueryBased = cp.IsDynamic ? ", \"IsQueryBased\" : true" : string.Empty; return(string.Format(ComponentSeFormat, cp.Component.Id, string.Format("{0:s}", cp.Component.RevisionDate), cp.ComponentTemplate.Id, string.Format("{0:s}", cp.ComponentTemplate.RevisionDate), cp.IsDynamic.ToString().ToLower(), isQueryBased)); }
protected virtual ViewResult GetView(IComponentPresentation componentPresentation) { if (ComponentPresentationRenderer == null) throw new ConfigurationException("No ComponentPresentationRenderer configured"); string viewName = componentPresentationRenderer.GetComponentTemplateView(componentPresentation.ComponentTemplate); return View(viewName, componentPresentation); }
public void GetComponentPresentation() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation(""); Assert.IsNotNull(cp); Assert.IsFalse(string.IsNullOrEmpty(cp.Component.Title) || string.IsNullOrEmpty(cp.ComponentTemplate.Title)); Assert.IsNotNull(cp.Conditions[0]); }
public ActionResult ShowWeather() { IComponentPresentation cp = this.GetComponentPresentation(); Weather weather = new Weather(cp); string viewName = cp.ComponentTemplate.MetadataFields["view"].Value; return(View(viewName, weather)); }
public ActionResult Index(IComponentPresentation componentPresentation) { string title = componentPresentation.Component.Schema.Title; IComponent component = componentPresentation.Component; FeaturedItems featuredItems = new FeaturedItems(); if (title == "Generic.ComponentGroup") { featuredItems.Title = component.Fields.ContainsKey("title") ? component.Fields["title"].Value : string.Empty; IList<IComponent> linkedComponentValues = component.Fields["items"].LinkedComponentValues; featuredItems.Components = new List<Component>(); if (linkedComponentValues.Count > 0) { string secondid = "fh_secondid={0}-16_tcm_{1}-{2}-32"; string str2 = string.Join("&", (from c in linkedComponentValues select string.Format(secondid, c.Id.Replace(":", "_"), WebConfiguration.Current.PublicationId, SchemaTemplate.Instance.Template[c.Schema.Title])).ToArray<string>()); DD4TComponents components = new DD4TComponents(this.Logger); this.Logger.InfoFormat("Featured static items query: {0}", new object[] { str2 }); featuredItems.Components = components.GetComponents(str2, true); } } else if (title == "Crafts.ContentByFacet") { Query query = new Query(); component.Fields.ToList<KeyValuePair<string, IField>>().ForEach(delegate (KeyValuePair<string, IField> f) { if (f.Key == "title") { featuredItems.Title = f.Value.Value; } else if ((f.Key == "facets") && (f.Value.LinkedComponentValues.Count > 0)) { int publicationId = this._settings.PublicationId; IFieldSet fieldSet = (from lcv in f.Value.LinkedComponentValues[0].Fields where lcv.Key != "promote" select lcv).ToFieldSet(); query.ParseQuery(fieldSet, publicationId, 6); DD4TComponents components = new DD4TComponents(this.Logger); this.Logger.InfoFormat("Featured items query: {0}", new object[] { query.toString() }); featuredItems.Components = components.GetComponents(query.toString(), true); } }); } else { return base.View(); } string featureComponentId = string.Empty; try { featureComponentId = componentPresentation.Page.ComponentPresentations[0].Component.Id; } catch { featureComponentId = string.Empty; } featuredItems.Components = (from c in featuredItems.Components where c.Id != featureComponentId select c).ToList<Component>(); return base.View(featuredItems); }
public static void SetupTest(TestContext context) { testComponent = GenerateTestComponent(); testComponentPresentation = GenerateTestComponentPresentation(); testComponentJson = GetService(false).Serialize <IComponent>(testComponent); testComponentJsonCompressed = GetService(true).Serialize <IComponent>(testComponent); testComponentPresentationJson = GetService(false).Serialize <IComponentPresentation>(testComponentPresentation); testComponentPresentationJsonCompressed = GetService(true).Serialize <IComponentPresentation>(testComponentPresentation); }
protected override ViewResult GetView(IComponentPresentation componentPresentation) { if (!componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } string viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Value; return View(viewName, componentPresentation.Component); }
protected override ViewResult GetView(IComponentPresentation componentPresentation) { if (!componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } string viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Value; return(View(viewName, componentPresentation.Component)); }
///// <summary> ///// Get or set the CacheAgent ///// </summary> //public override ICacheAgent CacheAgent //{ // get // { // if (_cacheAgent == null) // { // _cacheAgent = new NullCacheAgent(); // // the next line is the only reason we are overriding this property: to set a callback // _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack; // } // return _cacheAgent; // } // set // { // _cacheAgent = value; // _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack; // } //} public bool TryGetComponentPresentation(out IComponentPresentation cp, string componentUri, string templateUri = "") { cp = null; string[] cacheUris = { componentUri }; if (!String.IsNullOrEmpty(templateUri)) { cacheUris = new string[] { componentUri, templateUri }; } string cacheKey = CacheKeyFactory.GenerateKey(CacheRegion, cacheUris); cp = (IComponentPresentation)CacheAgent.Load(cacheKey); if (cp != null) { LoggerService.Debug("<<TryGetComponentPresentation ({0}) - from cache", LoggingCategory.Performance, componentUri); return(true); } string content = !String.IsNullOrEmpty(templateUri) ? ComponentPresentationProvider.GetContent(componentUri, templateUri) : ComponentPresentationProvider.GetContent(componentUri); if (string.IsNullOrEmpty(content)) { LoggerService.Debug("<<TryGetComponentPresentationOrComponent - no content found by provider for uris {0} and {1}", LoggingCategory.Performance, componentUri, templateUri); return(false); } LoggerService.Debug("about to create IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri); cp = GetIComponentPresentationObject(content); LoggerService.Debug("finished creating IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri); // if there is no ComponentTemplate, the content of this CP probably represents a component instead of a component PRESENTATION // in that case, we should at least add the template uri method parameter (if there is one) to the object if (cp.ComponentTemplate == null) { ((ComponentPresentation)cp).ComponentTemplate = new ComponentTemplate(); } if (cp.ComponentTemplate.Id == null) { ((ComponentPresentation)cp).ComponentTemplate.Id = templateUri; } LoggerService.Debug("about to store IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri); CacheAgent.Store(cacheKey, CacheRegion, cp, new List <string> { cp.Component.Id }); LoggerService.Debug("finished storing IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri); LoggerService.Debug("<<TryGetComponentPresentation ({0})", LoggingCategory.Performance, componentUri); return(cp != null); }
protected virtual ViewResult GetView(IComponentPresentation componentPresentation) { if (ComponentPresentationRenderer == null) { throw new ConfigurationException("No ComponentPresentationRenderer configured"); } string viewName = componentPresentationRenderer.GetComponentTemplateView(componentPresentation.ComponentTemplate); return(View(viewName, componentPresentation)); }
public void ResolveLinkWithPageUri() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", ""); Assert.IsNotNull(cp); TridionLinkProvider.link2 = "/this/link/works/too.html"; string url = ViewModelFactory.LinkResolver.ResolveUrl(cp.Component, "tcm:2-2-64"); Assert.IsNotNull(url); Assert.AreEqual(url, "/this/link/works/too.html"); }
/// <summary> /// Creates a Strongly Typed Entity Model for a given DD4T Component Presentation. /// </summary> /// <param name="cp">The DD4T Component Presentation.</param> /// <param name="localization">The context <see cref="Localization"/>.</param> /// <returns>The Strongly Typed Entity Model.</returns> public static EntityModel CreateEntityModel(IComponentPresentation cp, Localization localization) { using (new Tracer(cp, localization)) { EntityModel entityModel = null; foreach (IModelBuilder modelBuilder in ModelBuilders) { modelBuilder.BuildEntityModel(ref entityModel, cp, localization); } return entityModel; } }
/// <summary> /// Creates a Strongly Typed Entity Model for a given DD4T Component Presentation. /// </summary> /// <param name="cp">The DD4T Component Presentation.</param> /// <param name="localization">The context <see cref="Localization"/>.</param> /// <returns>The Strongly Typed Entity Model.</returns> public static EntityModel CreateEntityModel(IComponentPresentation cp, Localization localization) { using (new Tracer(cp, localization)) { EntityModel entityModel = null; foreach (IModelBuilder modelBuilder in ModelBuilders) { modelBuilder.BuildEntityModel(ref entityModel, cp, localization); } return(entityModel); } }
protected virtual ViewResult GetView(IComponentPresentation componentPresentation) { string viewName = null; // TODO: define field names in Web.config if (!componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Values[0]; return(View(viewName, componentPresentation)); }
public IList <IComponentPresentation> FindComponentPresentations(IQuery queryParameters) { LoggerService.Debug(">>FindComponentPresentations ({0})", LoggingCategory.Performance, queryParameters.ToString()); var results = ComponentPresentationProvider.FindComponents(queryParameters) .Select(c => { IComponentPresentation cp = null; TryGetComponentPresentation(out cp, c); return(cp); }) .Where(cp => cp != null) .ToList(); LoggerService.Debug("<<FindComponentPresentations ({0})", LoggingCategory.Performance, queryParameters.ToString()); return(results); }
public static void SetupTest(TestContext context) { testComponent = GenerateTestComponent(); testComponentPresentation = GenerateTestComponentPresentation(); testPage = GenerateTestPage(); testComponentXml = GetService(false).Serialize <IComponent>(testComponent); testComponentXmlCompressed = GetService(true).Serialize <IComponent>(testComponent); testComponentPresentationXml = GetService(false).Serialize <IComponentPresentation>(testComponentPresentation); testComponentPresentationXmlCompressed = GetService(true).Serialize <IComponentPresentation>(testComponentPresentation); testPageXml = GetService(false).Serialize <IPage>(testPage); testPageXmlCompressed = GetService(true).Serialize <IPage>(testPage); }
public ActionResult Index(IComponentPresentation componentPresentation) { string str2; Stopwatch stopwatch = new Stopwatch(); if (this.Logger.IsDebugEnabled) { stopwatch.Start(); } ((dynamic) base.ViewBag).PodGenericSpan = "span4"; string str = base.Request.QueryString["fh_params"]; Query query = null; HomePageBannerContent model = new HomePageBannerContent { Banner = componentPresentation }; if (!string.IsNullOrEmpty(str)) { query = new Query(); query.ParseQuery(str); } else { Location location = new Location(this.DefaultLocation); Criterion criterion = HomePageTabsConfig.ToCriteria(this._settings.PublicationId); location.addCriterion(criterion); query = new Query(location); } query.setView(com.fredhopper.lang.query.ViewType.LISTER); int viewsize = Convert.ToInt32(WebConfiguration.Current.HomepageItemsPerPage); viewsize = FacetedContentHelper.AssertCappedViewSize(viewsize); query.setListViewSize(viewsize); query.setSortingBy(WebConfiguration.Current.HomepageSort); DD4TComponents components = new DD4TComponents(this.Logger); if (this.Logger.IsDebugEnabled) { stopwatch.Stop(); str2 = stopwatch.Elapsed.ToString(); this.Logger.DebugFormat("HomeController Index time elapsed 1:" + str2, new object[0]); } model.FredHopperComponents = components.GetComponents(query.toString(), true); model.Tabs = HomePageTabsConfig.ToSelectList(query.toString()); IList<IComponentPresentation> ctaList = (from m in componentPresentation.Page.ComponentPresentations where m.ComponentTemplate.Id != componentPresentation.ComponentTemplate.Id select m).ToList<IComponentPresentation>(); model.FredHopperComponents = FacetedContentHelper.InjectCTAComponents(model.FredHopperComponents, ctaList, false, false); if (this.Logger.IsDebugEnabled) { stopwatch.Stop(); str2 = stopwatch.Elapsed.ToString(); this.Logger.DebugFormat("HomeController Index time elapsed 2:" + str2, new object[0]); } return base.View(model); }
public virtual ActionResult ComponentPresentation(string componentPresentationId) { try { IComponentPresentation model = GetComponentPresentation(); ViewBag.Renderer = ComponentPresentationRenderer; return(GetView(model)); } catch (ConfigurationException e) { return(View("Configuration exception: " + e.Message)); } }
public static void SetupTest(TestContext context) { testComponent = GenerateTestComponent(); testComponentPresentation = GenerateTestComponentPresentation(); // Method GetService() is a (virtual) instance method now, so we need a temp instance. JsonSerialization testInstance = new JsonSerialization(); testComponentJson = testInstance.GetService(false).Serialize <IComponent>(testComponent); testComponentJsonCompressed = testInstance.GetService(true).Serialize <IComponent>(testComponent); testComponentPresentationJson = testInstance.GetService(false).Serialize <IComponentPresentation>(testComponentPresentation); testComponentPresentationJsonCompressed = testInstance.GetService(true).Serialize <IComponentPresentation>(testComponentPresentation); }
public virtual I Create <I>(IComponentPresentation componentPresentation, string language) { I model; if (TryCreate <I>(componentPresentation, language, out model)) { return(model); } else { System.Diagnostics.Trace.TraceWarning("Could not create model for '{0}'", typeof(I).Name); return(default(I)); } }
public GeneralDetail Create(IComponentPresentation componentPresentation) { var fields = componentPresentation.Component.Fields; return new GeneralDetail { Heading = fields.Field("Heading"), Summary = RichTextHelper.ResolveRichText(fields.FieldOrEmpty("Summary")), Link = fields.Field("Link", new LinkModelBuilder(this.LinkFactory).CreateLinkText), Image = fields.Image(), TextImage = fields.Field("TextImage"), Template = componentPresentation.ComponentTemplate.Title, Paragraphs = fields.Field("Paragraph", new ParagraphBuilder(RichTextHelper).Create), }; }
public bool TryCreate <T>(IComponentPresentation componentPresentation, out T model) { try { model = (T)CreateModel(componentPresentation); return(true); } catch (Exception exception) { throw exception; model = default(T); return(false); } }
public bool TryCreate <T>(IComponentPresentation componentPresentation, string language, out T model) { try { model = (T)CreateModel(componentPresentation, language); return(true); } catch { throw; model = default(T); return(false); } }
/// <summary> /// Generates a SiteEdit tag for a componentpresentation. It also needs to know which region it's in (for component /// swapping) and the order of the page (for a true unique ID). /// </summary> /// <param name="cp">The componentpresentation to mark.</param> /// <returns>string representing the JSON SiteEdit tag.</returns> public static string GenerateSiteEditComponentTag(IComponentPresentation cp, IComponentTemplate overrideComponentTemplate = null) { // is query based tells us if the dcp was the result of a broker query and the component presentation is not embedded on the page string isQueryBased = cp.IsDynamic ? ", \"IsQueryBased\" : true" : string.Empty; // bug 48: allow developer to override the component template ID and modified date/time if (cp.ComponentTemplate == null && overrideComponentTemplate == null) { return(string.Empty); } string ctId = overrideComponentTemplate == null ? cp.ComponentTemplate.Id : overrideComponentTemplate.Id; DateTime ctModifiedDate = overrideComponentTemplate == null ? cp.ComponentTemplate.RevisionDate : overrideComponentTemplate.RevisionDate; return(string.Format(ComponentSeFormat, cp.Component.Id, string.Format("{0:s}", cp.Component.RevisionDate), ctId, string.Format("{0:s}", ctModifiedDate), cp.IsDynamic.ToString().ToLower(), isQueryBased)); }
public GeneralDetail Create(IComponentPresentation componentPresentation) { var fields = componentPresentation.Component.Fields; return(new GeneralDetail { Heading = fields.Field("Heading"), Summary = RichTextHelper.ResolveRichText(fields.FieldOrEmpty("Summary")), Link = fields.Field("Link", new LinkModelBuilder(this.LinkFactory).CreateLinkText), Image = fields.Image(), TextImage = fields.Field("TextImage"), Template = componentPresentation.ComponentTemplate.Title, Paragraphs = fields.Field("Paragraph", new ParagraphBuilder(RichTextHelper).Create), }); }
protected virtual ViewResult GetView(IComponentPresentation componentPresentation) { string viewName = null; if (componentPresentation.ComponentTemplate.MetadataFields == null || !componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) viewName = componentPresentation.ComponentTemplate.Title.Replace(" ", ""); else viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Value; if (string.IsNullOrEmpty(viewName)) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } return View(viewName, componentPresentation); }
public void KeywordIdAsTcmUri() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "keyword"); Assert.IsNotNull(cp); KeywordContainingModel vm = ViewModelFactory.BuildViewModel(cp) as KeywordContainingModel; Assert.IsNotNull(vm); KeywordModel km = vm.ConcreteKeyword; Assert.IsNotNull(km); Assert.IsNotNull(km.KeywordId, "KeywordId is not set"); }
private MvcHtmlString RenderComponentPresentation(IComponentPresentation cp, HtmlHelper htmlHelper) { string controller = WebConfigurationManager.AppSettings["Controller"]; string action = WebConfigurationManager.AppSettings["Action"]; if (cp.ComponentTemplate.MetadataFields.ContainsKey("controller")) { controller = cp.ComponentTemplate.MetadataFields["controller"].Value; } if (cp.ComponentTemplate.MetadataFields.ContainsKey("action")) { action = cp.ComponentTemplate.MetadataFields["action"].Value; } return ChildActionExtensions.Action(htmlHelper, action, controller, new { componentPresentation = cp }); }
public void MapConcreteKeywordField() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "keyword"); Assert.IsNotNull(cp); KeywordContainingModel vm = ViewModelFactory.BuildViewModel(cp) as KeywordContainingModel; Assert.IsNotNull(vm); KeywordModel km = vm.ConcreteKeyword; Assert.IsNotNull(km); Assert.IsTrue(km.Heading == "some heading"); }
public Weather(IComponentPresentation cp) { //string feedurl = "http://weather.yahooapis.com/forecastrss?w=615702&u=c"; Location = cp.Component.Fields["Location"].Value; using (XmlReader reader = XmlReader.Create(cp.Component.Fields["Url"].Value)) { XmlDocument feed = new XmlDocument(); feed.Load(reader); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(feed.NameTable); namespaceManager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0"); XmlElement condition = (XmlElement)feed.SelectSingleNode("//yweather:condition", namespaceManager); Temperature = condition.GetAttribute("temp"); Conditions = condition.GetAttribute("text"); } }
public void MapConcreteLink() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "componentlink"); Assert.IsNotNull(cp); IViewModel vm = ViewModelFactory.BuildViewModel(cp); Assert.IsNotNull(vm); TestViewModelB b = ((TestViewModelA)vm).ConcreteLink[0]; Assert.IsNotNull(b); Assert.IsTrue(b.Heading == "some heading"); }
private string ResolveRichText(string input) { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", ""); Field richTextField = new Field() { Name = "richtext", Values = new List <string>() { input } }; cp.Component.Fields.Add(richTextField.Name, richTextField); return((string)ViewModelFactory.RichTextResolver.Resolve(cp.Component.Fields["richtext"].Value)); }
public void MapAbstractEmbeddedField() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "embedded"); Assert.IsNotNull(cp); EmbeddingModel vm = ViewModelFactory.BuildViewModel(cp) as EmbeddingModel; Assert.IsNotNull(vm); EmbeddedModel em = vm.Embedded as EmbeddedModel; Assert.IsNotNull(em); Assert.IsTrue(em.Heading == "some heading"); }
public void MapComponentId() { IComponentPresentation cp = ComponentPresentationFactory.GetComponentPresentation("", "componentId"); Assert.IsNotNull(cp); IViewModel vm = ViewModelFactory.BuildViewModel(cp); Assert.IsNotNull(vm); TestViewModelA b = (TestViewModelA)vm; Assert.IsNotNull(b); Assert.IsTrue(b.Id.ItemId == 8975); Assert.IsTrue(b.Id.PublicationId == 5); }
public ActionResult Index(IComponentPresentation componentPresentation, bool clear = false) { if (clear) { if (base.Logger.IsDebugEnabled) { base.Logger.Debug("Clearing session"); } base.RouteData.Values["Level1BrandActivated"] = false; base.RouteData.Values["BrandComponent"] = new Field(); base.RouteData.Values["BrandFilter"] = string.Empty; base.RouteData.Values["BrandFacet"] = string.Empty; base.RouteData.Values["BrandFacetValue"] = string.Empty; base.RouteData.Values["BrandValueForSearch"] = string.Empty; base.Session.ClearLevel1BrandFilter(); } return base.HandleIndexGet(componentPresentation); }
protected override ViewResult GetView(IComponentPresentation componentPresentation) { // TODO: define field names in Web.config if (!componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } string viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Value; object model; // todo: implement ModelFactory //if (ModelFactory.TryCreateModel(viewName, componentPresentation, out model)) // return View(viewName, model); //else // return null; return View(viewName, componentPresentation.Component); }
protected override ViewResult GetView(IComponentPresentation componentPresentation) { var cp = (ComponentPresentation) componentPresentation; cp.Component = (Component) ComponentFactory.GetComponent(componentPresentation.Component.Id, componentPresentation.ComponentTemplate.Id); var viewResult = base.GetView(cp); string viewName = viewResult.ViewName; String language = this.ControllerContext.RouteData.Values["language"].ToString().Substring(3,2); // todo: implement ModelFactory //ModelFactory.Language = language; object model; return ModelFactory.TryCreateModel(viewName, cp, out model) ? View(viewName, model) : viewResult; }
public static MvcHtmlString RenderComponentPresentation(this HtmlHelper htmlHelper, IComponentPresentation cp) { string controller = ConfigurationHelper.ComponentPresentationController; string action = ConfigurationHelper.ComponentPresentationAction; if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("controller")) { controller = cp.ComponentTemplate.MetadataFields["controller"].Value; } if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("action")) { action = cp.ComponentTemplate.MetadataFields["action"].Value; } LoggerService.Debug("about to render component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); //return ChildActionExtensions.Action(htmlHelper, action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); MvcHtmlString result = htmlHelper.Action(action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); LoggerService.Debug("finished rendering component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); return result; }
public ActionResult Index(IComponentPresentation componentPresentation) { Stopwatch stopwatch = new Stopwatch(); if (this.Logger.IsDebugEnabled) { stopwatch.Start(); this.Logger.Debug("EventsNearYou enter >>>>>"); } EventsNearYou model = new EventsNearYou { ComponentTitle = componentPresentation.Component.Fields["title"].Value, Lat = this.Latitude.ToString(), Lng = this.Longitude.ToString() }; try { IField field = componentPresentation.Component.Fields["link"]; IFieldSet set = field.EmbeddedValues[0]; if (set.ContainsKey("linkTitle")) { model.LinkTitle = set["linkTitle"].Value; } if (set.ContainsKey("linkURL")) { model.LinkURL = set["linkURL"].Value.ToUpper().StartsWith("HTTP") ? set["linkURL"].Value : set["linkURL"].Value.AddApplicationRoot(); } if (set.ContainsKey("linkComponent")) { IComponent component = set["linkComponent"].LinkedComponentValues[0]; model.LinkComponent = component; } } catch { model.LinkTitle = string.Empty; model.LinkURL = string.Empty; } List<CraftsEvent> craftsEventsInArea = new List<CraftsEvent>(); if (base.User.Identity.IsAuthenticated) { decimal num; decimal num2; MvcApplication.CraftsPrincipal user = (MvcApplication.CraftsPrincipal) base.HttpContext.User; if (!decimal.TryParse(user.LAT, out num)) { num = 0.0M; } if (!decimal.TryParse(user.LONG, out num2)) { num2 = 0.0M; } if ((num != 0M) && (num2 != 0M)) { if (this.Logger.IsDebugEnabled) { this.Logger.DebugFormat("Getting events for user {0} who has long {1} and lat {2}", new object[] { user.UserName, num2, num }); } craftsEventsInArea = this.eventsrepository.GetCraftsEventsInArea(num, num2, this.settings.EventsNearYouRadius, this.settings.EventsNearYouMaxResults); } } if (craftsEventsInArea.Count == 0) { if (this.GeoDataAvailable) { if (this.Logger.IsDebugEnabled) { this.Logger.DebugFormat("No user available, but request has geo data available, getting events for long {0} and lat {1}", new object[] { this.Longitude, this.Latitude }); } craftsEventsInArea = this.eventsrepository.GetCraftsEventsInArea(this.Latitude, this.Longitude, this.settings.EventsNearYouRadius, this.settings.EventsNearYouMaxResults); } else { if (this.Logger.IsDebugEnabled) { this.Logger.Debug("No user available and no request geo data either, just getting some events!"); } craftsEventsInArea = this.eventsrepository.GetCraftsEventsInArea(); } } if (this.Logger.IsDebugEnabled) { this.Logger.DebugFormat("Events: {0}", new object[] { craftsEventsInArea.Count }); } model.Events = craftsEventsInArea; if (this.Logger.IsDebugEnabled) { this.Logger.Debug("<<<<< EventsNearYou finish"); } if (this.Logger.IsDebugEnabled) { stopwatch.Stop(); string str = stopwatch.Elapsed.ToString(); this.Logger.DebugFormat("EventsNearYouController.Index time elapsed:" + str, new object[0]); } return base.View(model); }
/// <summary> /// Generates a SiteEdit tag for a component presentation. Assumes that the component presentation is not query based. /// </summary> /// <param name="cp">the component presentation to mark.</param> /// <param name="region">The region the componentpresentation is to be shown in.</param> /// <returns>string representing the JSON SiteEdit tag.</returns> public static string GenerateSiteEditComponentTag(IComponentPresentation cp, string region) { return GenerateSiteEditComponentTag(cp, false, region); }
public ActionResult Index(IComponentPresentation componentPresentation, EmailNewsletter emailNewsletter, string ReturnUrl = "", string stepoverride = "register") { if (!base.User.Identity.IsAuthenticated) { stepoverride = "register"; } ((dynamic) base.ViewBag).Stage = stepoverride; try { ((dynamic) base.ViewBag).Title = componentPresentation.Component.Fields["title"].Value; } catch (Exception) { } Registration model = new Registration { RegistrationForm = new RegistrationForm(), LoginForm = new LoginForm() }; NameValueCollection @params = base.Request.Params; if (!string.IsNullOrEmpty(@params["action"])) { if (@params["action"] == "addtoshoppinglist") { ((dynamic) base.ViewBag).Title = Helper.GetResource("SignupShoppingList"); } if (@params["action"] == "download") { ((dynamic) base.ViewBag).Title = Helper.GetResource("SignupDownload"); } } if (!string.IsNullOrEmpty(ReturnUrl)) { model.LoginForm.ReturnUrl = ReturnUrl + "?" + base.Request.QueryString.ToString().Replace("iframe=true", ""); model.RegistrationForm.returnUrl = ReturnUrl + "?" + base.Request.QueryString.ToString().Replace("iframe=true", ""); } else if (!string.IsNullOrWhiteSpace(base.Request.QueryString["source"])) { model.RegistrationForm.returnUrl = model.LoginForm.ReturnUrl = base.Request.QueryString["source"]; } else { model.LoginForm.ReturnUrl = base.Url.Content(WebConfiguration.Current.MyProfile); model.RegistrationForm.returnUrl = base.Url.Content(WebConfiguration.Current.MyProfile); } this.GetModelData(model.RegistrationForm); if ((emailNewsletter.Techniques != null) && (emailNewsletter.Techniques.Count > 0)) { model.RegistrationForm.CraftTypeList = emailNewsletter.Techniques; } if (!string.IsNullOrEmpty(emailNewsletter.EmailAddress)) { model.RegistrationForm.CustomerDetails.EmailAddress = emailNewsletter.EmailAddress; } SelectListItem item = model.RegistrationForm.EmailNewsletter.SingleOrDefault<SelectListItem>(e => e.Text == "No"); if (item != null) { item.Selected = true; } return base.View(model); }
/// <summary> /// Generates a SiteEdit tag for a componentpresentation. It also needs to know which region it's in (for component /// swapping) and the order of the page (for a true unique ID). /// </summary> /// <param name="cp">The componentpresentation to mark.</param> /// <param name="queryBased">indicates whether the component presentation is the result of a query (true), or if it is really part of the page (false)</param> /// <param name="region">The region the componentpresentation is to be shown in.</param> /// <returns>string representing the JSON SiteEdit tag.</returns> public static string GenerateSiteEditComponentTag(IComponentPresentation cp, bool queryBased, string region) { if (!SiteEditSettings.Enabled) { return string.Empty; } if (SiteEditSettings.Style == SiteEditStyle.SiteEdit2012) { // is query based tells us if the dcp was the result of a broker query and the component presentation is not embedded on the page string isQueryBased = queryBased ? ", \"IsQueryBased\" : true" : string.Empty; return string.Format(Ui2012ComponentSeFormat, cp.Component.Id, string.Format("{0:s}", cp.Component.RevisionDate), cp.ComponentTemplate.Id, string.Format("{0:s}", cp.ComponentTemplate.RevisionDate), cp.IsDynamic.ToString().ToLower(), isQueryBased); } string pubIdWithoutTcm = Convert.ToString(new TcmUri(cp.Component.Id).PublicationId); if (SiteEditSettings.ContainsKey(pubIdWithoutTcm)) { SiteEditSetting setting = SiteEditSettings[pubIdWithoutTcm]; if (setting.Enabled) { int cpId; if (queryBased) { // for query based CPs, we are responsible for making the ID unique cpId = GetUniqueCpId(); } else { cpId = cp.OrderOnPage; } return string.Format(ComponentSeFormat, cpId, cp.Component.Id, cp.ComponentTemplate.Id, cp.Component.Version, Convert.ToString(queryBased).ToLower(), region); } } return string.Empty; }
public ActionResult Index(IComponentPresentation componentPresentation) { UserProfile model = this.GetModel(); try { ((dynamic) base.ViewBag).Title = componentPresentation.Component.Fields["title"].Value; } catch (Exception) { } if (model == null) { base.Response.Redirect(base.Url.Content(WebConfiguration.Current.AccessDenied.AddApplicationRoot())); } if (model != null) { if (base.Request.Url != null) { model.returnUrl = base.Request.Url.ToString(); } return base.View(model); } return null; }
public ActionResult Index(ProductExplorer productExplorer, IComponentPresentation componentPresentation) { ((dynamic) base.ViewBag).ExpandForProductExplorer = true; return base.HandleIndexPost(productExplorer, componentPresentation, "post"); }
public static string GetLocalAnchorTag(this bool useUriAsAnchor, IComponentPresentation cp) { return useUriAsAnchor ? Convert.ToString(new TcmUri(cp.Component.Id).ItemId) : Convert.ToString(cp.OrderOnPage); }
private static MvcHtmlString RenderComponentPresentation(IComponentPresentation cp, HtmlHelper htmlHelper) { string controller = _configuration.ComponentPresentationController; if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("controller")) { controller = cp.ComponentTemplate.MetadataFields["controller"].Value; } if (string.IsNullOrEmpty(controller)) { throw new InvalidOperationException("Controller was not configured in component template metadata or in application settings. " + "Unable to Render component presentation."); } string action = _configuration.ComponentPresentationAction; if (cp.ComponentTemplate.MetadataFields != null && cp.ComponentTemplate.MetadataFields.ContainsKey("action")) { action = cp.ComponentTemplate.MetadataFields["action"].Value; } if (string.IsNullOrEmpty(action)) { throw new InvalidOperationException("Action was not configured in component template metadata or in application settings. " + "Unable to Render component presentation."); } _loggerService.Debug("about to render component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); //return ChildActionExtensions.Action(htmlHelper, action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); MvcHtmlString result = htmlHelper.Action(action, controller, new { componentPresentation = ((ComponentPresentation)cp) }); _loggerService.Debug("finished rendering component presentation with controller {0} and action {1}", LoggingCategory.Performance, controller, action); return result; }
public static MvcHtmlString SiteEditComponentPresentation(this HtmlHelper helper, IComponentPresentation componentPresentation) { return SiteEditComponentPresentation(helper, componentPresentation, "default"); }
public static string GetLocalAnchor(IComponentPresentation cp) { return ConfigurationHelper.UseUriAsAnchor ? Convert.ToString(new TcmUri(cp.Component.Id).ItemId) : Convert.ToString(cp.OrderOnPage); }
protected virtual ViewResult GetView(IComponentPresentation componentPresentation) { string viewName = null; // TODO: define field names in Web.config if (!componentPresentation.ComponentTemplate.MetadataFields.ContainsKey("view")) { throw new ConfigurationException("no view configured for component template " + componentPresentation.ComponentTemplate.Id); } viewName = componentPresentation.ComponentTemplate.MetadataFields["view"].Values[0]; return View(viewName, componentPresentation); }
public void BuildEntityModel(ref EntityModel entityModel, IComponentPresentation cp, Localization localization) { // No post-processing of Entity Models needed }
///// <summary> ///// Get or set the CacheAgent ///// </summary> //public override ICacheAgent CacheAgent //{ // get // { // if (_cacheAgent == null) // { // _cacheAgent = new NullCacheAgent(); // // the next line is the only reason we are overriding this property: to set a callback // _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack; // } // return _cacheAgent; // } // set // { // _cacheAgent = value; // _cacheAgent.GetLastPublishDateCallBack = GetLastPublishedDateCallBack; // } //} public bool TryGetComponentPresentation(out IComponentPresentation cp, string componentUri, string templateUri = "") { cp = null; string cacheKey = CacheKeyFactory.GenerateKeyFromUri(componentUri, CacheRegion); cp = (IComponentPresentation)CacheAgent.Load(cacheKey); if (cp != null) { LoggerService.Debug("<<TryGetComponentPresentation ({0}) - from cache", LoggingCategory.Performance, componentUri); return true; } string content = !String.IsNullOrEmpty(templateUri) ? ComponentPresentationProvider.GetContent(componentUri, templateUri) : ComponentPresentationProvider.GetContent(componentUri); if (string.IsNullOrEmpty(content)) { LoggerService.Debug("<<TryGetComponentPresentationOrComponent - no content found by provider for uris {0} and {1}", LoggingCategory.Performance, componentUri, templateUri); return false; } LoggerService.Debug("about to create IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri); cp = GetIComponentPresentationObject(content); LoggerService.Debug("finished creating IComponentPresentation from content ({0})", LoggingCategory.Performance, componentUri); // if there is no ComponentTemplate, the content of this CP probably represents a component instead of a component PRESENTATION // in that case, we should at least add the template uri method parameter (if there is one) to the object if (cp.ComponentTemplate == null) { ((ComponentPresentation)cp).ComponentTemplate = new ComponentTemplate(); } if (cp.ComponentTemplate.Id == null) { ((ComponentPresentation)cp).ComponentTemplate.Id = templateUri; } LoggerService.Debug("about to store IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri); CacheAgent.Store(cacheKey, CacheRegion, cp, new List<string> { cp.Component.Id }); LoggerService.Debug("finished storing IComponentPresentation in cache ({0})", LoggingCategory.Performance, componentUri); LoggerService.Debug("<<TryGetComponentPresentation ({0})", LoggingCategory.Performance, componentUri); return cp != null; }
public static MvcHtmlString SiteEditComponentPresentation(this HtmlHelper helper, IComponentPresentation componentPresentation, string region) { return SiteEditComponentPresentation(helper, componentPresentation, false, region); }
public static MvcHtmlString SiteEditComponentPresentation(this HtmlHelper helper, IComponentPresentation componentPresentation, bool queryBased, string region) { return new MvcHtmlString(SiteEdit.SiteEditService.GenerateSiteEditComponentTag(componentPresentation, queryBased, region)); }