コード例 #1
0
        private void LoadComponentModelsFromComponentPresentationFactory(IPage page)
        {
            LoggerService.Debug(">>LoadComponentModelsFromComponentPresentationFactory ({0})", LoggingCategory.Performance, page.Id);

            foreach (DD4T.ContentModel.ComponentPresentation cp in page.ComponentPresentations)
            {
                if (cp.Component == null)
                {
                    continue;
                }

                // added by QS: only load DCPs from broker if they are in fact dynamic!
                if (cp.IsDynamic)
                {
                    try
                    {
                        ComponentPresentation dcp = (ComponentPresentation)ComponentPresentationFactory.GetComponentPresentation(cp.Component.Id, cp.ComponentTemplate.Id);
                        cp.Component         = dcp.Component;
                        cp.ComponentTemplate = dcp.ComponentTemplate;
                        cp.Conditions        = dcp.Conditions;
                    }
                    catch (ComponentPresentationNotFoundException)
                    {
                        LoggerService.Warning("dynamic component presentation {0} / {1} included on page {2} cannot be found; it may have been unpublished", LoggingCategory.Model, cp.Component.Id, cp.ComponentTemplate.Id, page.Id);
                        // DCPs can be unpublished while the page that they are embedded on remain published
                        // in this case, simply ignore the exception (the 'stub' component is still on the page)
                    }
                }
            }
            LoggerService.Debug("<<LoadComponentModelsFromComponentPresentationFactory ({0})", LoggingCategory.Performance, page.Id);
        }
コード例 #2
0
        internal static IPage GenerateTestPage()
        {
            Page p = new Page()
            {
                Id             = "tcm:1-2-64",
                Title          = GetTestTitle <Page>(),
                StructureGroup = new OrganizationalItem()
                {
                    Id    = "tcm:1-2-2",
                    Title = "Test - structuregroup.title"
                },
                Publication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - publication.title"
                },
                OwningPublication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - owningpublication.title"
                },
                ComponentPresentations = new System.Collections.Generic.List <ComponentPresentation>(),
                Regions = new List <Region>
                {
                    new Region()
                    {
                        Name = "Region A",
                        ComponentPresentations = new List <ComponentPresentation>
                        {
                            GenerateTestComponentPresentation() as ComponentPresentation
                        }
                    }
                }
            };
            List <Condition> conditions = new List <Condition>();

            conditions.Add(new CustomerCharacteristicCondition()
            {
                Name     = "CustomersOnly",
                Negate   = false,
                Operator = ConditionOperator.Equals,
                Value    = "ID"
            }
                           );
            var targetGroupConditions = new List <TargetGroupCondition>();

            targetGroupConditions.Add(new TargetGroupCondition()
            {
                TargetGroup = new TargetGroup()
                {
                    Title = "CustomersOnly", Conditions = conditions, Description = "A test target group", Id = "tcm:2-1231-256", PublicationId = "tcm:0-2-1"
                },
                Negate = false
            });
            ComponentPresentation cp = (ComponentPresentation)GenerateTestComponentPresentation();

            cp.TargetGroupConditions = targetGroupConditions;
            p.ComponentPresentations.Add(cp);
            return(p);
        }
コード例 #3
0
        private EntityModelData GetEntityModelData(ComponentPresentation cp)
        {
            ComponentTemplate ct = cp.ComponentTemplate;

            // Create a Child Rendered Item for the CP in order to make Component linking work.
            RenderedItem childRenderedItem = new RenderedItem(new ResolvedItem(cp.Component, ct),
                                                              Pipeline.RenderedItem.RenderInstruction);

            Pipeline.RenderedItem.AddRenderedItem(childRenderedItem);

            EntityModelData entityModel;

            if (ct.IsRepositoryPublishable)
            {
                Logger.Debug($"Not expanding DCP ({cp.Component}, {ct})");
                entityModel = new EntityModelData
                {
                    Id = $"{GetDxaIdentifier(cp.Component)}-{GetDxaIdentifier(ct)}"
                };
            }
            else
            {
                entityModel = Pipeline.CreateEntityModel(cp);
            }
            return(entityModel);
        }
コード例 #4
0
ファイル: Region.cs プロジェクト: NiclasCedermalm/dd4t-lite
 public ComponentPresentationInfo(Page page, ComponentPresentation componentPresentation, Region owner)
 {
     ComponentPresentation = componentPresentation;
     InnerRegion = GetInnerRegion(page, componentPresentation.ComponentTemplate);
     RegionIndex = Region.ExtractRegionIndex(componentPresentation.ComponentTemplate.Id);
     Owner = owner;
 }
        /// <summary>
        /// Gets the raw string (xml) from the broker db by URL
        /// </summary>
        /// <param name="Url">URL of the page</param>
        /// <returns>String with page xml or empty string if no page was found</returns>
        public string GetContentByUrl(string Url)
        {
            Page page = new Page();
            page.Title = Randomizer.AnyString(15);
            page.Id = Randomizer.AnyUri(64);
            page.Filename = Randomizer.AnySafeString(8) + ".html";

            PageTemplate pt = new PageTemplate();
            pt.Title = Randomizer.AnyString(20);
            Field ptfieldView = new Field();
            ptfieldView.Name = "view";
            ptfieldView.Values.Add("Standard");
            pt.MetadataFields = new FieldSet();
            pt.MetadataFields.Add(ptfieldView.Name, ptfieldView);

            page.PageTemplate = pt;

            Schema schema = new Schema();
            schema.Title = Randomizer.AnyString(10);

            Component component = new Component();
            component.Title = Randomizer.AnyString(30);
            component.Id = Randomizer.AnyUri(16);
            component.Schema = schema;

            Field field1 = Randomizer.AnyTextField(6, 120, true);
            Field field2 = Randomizer.AnyTextField(8, 40, false);

            FieldSet fieldSet = new FieldSet();
            fieldSet.Add(field1.Name, field1);
            fieldSet.Add(field2.Name, field2);
            component.Fields = fieldSet;

            ComponentTemplate ct = new ComponentTemplate();
            ct.Title = Randomizer.AnyString(20);
            Field fieldView = new Field();
            fieldView.Name = "view";
            fieldView.Values.Add("DefaultComponentView");
            ct.MetadataFields = new FieldSet();
            ct.MetadataFields.Add(fieldView.Name, fieldView);

            ComponentPresentation cp = new ComponentPresentation();
            cp.Component = component;
            cp.ComponentTemplate = ct;

            page.ComponentPresentations = new List<ComponentPresentation>();
            page.ComponentPresentations.Add(cp);

            FieldSet metadataFields = new FieldSet();
            page.MetadataFields = metadataFields;

            var serializer = new XmlSerializer(typeof(Page));
            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);
            //XmlTextWriter writer = new XmlTextWriter(page.Filename, Encoding.UTF8);
            //serializer.Serialize(writer, page);
            serializer.Serialize(writer, page);
            string pageAsString = builder.ToString();
            return pageAsString;
        }
コード例 #6
0
        private ComponentPresentationInfo AddToComponentPresentationList(ComponentPresentation componentPresentation, int pageIndex)
        {
            ComponentPresentationInfo cpInfo = new ComponentPresentationInfo(componentPresentation, this, pageIndex);

            this.ComponentPresentations.Add(cpInfo);
            return(cpInfo);
        }
コード例 #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="componentPresentation"></param>
 /// <param name="owner"></param>
 /// <param name="pageIndex"></param>
 public ComponentPresentationInfo(ComponentPresentation componentPresentation, Container owner, int pageIndex)
 {
     ComponentPresentation = componentPresentation;
     ContainerIndex        = Container.ExtractContainerIndex(componentPresentation.ComponentTemplate.Id);
     Owner     = owner;
     PageIndex = pageIndex;
 }
コード例 #8
0
        public override T Deserialize <T>(string input)
        {
            // NOTE: important exception situation!!
            // if the requested type is IComponentPresentation, there is a possiblity that the data
            // provided to us actually contains a Component instead. In that case we need to add a
            // dummy CT / CP around the Component and return that!

            //if (((SerializationProperties)SerializationProperties).CompressionEnabled)
            //{
            //    input = Compressor.Decompress(input);
            //}

            using (var inputValueReader = new StringReader(input))
            {
                JsonTextReader reader = new JsonTextReader(inputValueReader);
                if (typeof(T).Name.Contains("ComponentPresentation") &&
                    !input.Contains("ComponentTemplate"))
                {
                    // handle the exception situation where we are asked to deserialize into a CP but the data is actually a Component
                    Component component = Serializer.Deserialize <Component>(reader);
                    IComponentPresentation componentPresentation = new ComponentPresentation()
                    {
                        Component         = component,
                        ComponentTemplate = new ComponentTemplate()
                    };
                    return((T)componentPresentation);
                }
                return((T)Serializer.Deserialize <T>(reader));
            }
        }
        /// <summary>
        /// Builds an Entity Data Model from a given CM Component Presentation on a Page.
        /// </summary>
        /// <param name="entityModelData">The Entity Data Model to build. Is <c>null</c> for the first Model Builder in the pipeline.</param>
        /// <param name="cp">The CM Component Presentation (obtained from a Page).</param>
        public void BuildEntityModel(ref EntityModelData entityModelData, ComponentPresentation cp)
        {
            // Add extension data for Context Expressions (if applicable)
            ContentModelData contextExpressions        = new ContentModelData();
            object           includeContextExpressions =
                GetContextExpressions(
                    ContextExpressionUtils.GetContextExpressions(
                        cp.Conditions.Where(c => !c.Negate).Select(c => c.TargetGroup)));
            object excludeContextExpressions =
                GetContextExpressions(
                    ContextExpressionUtils.GetContextExpressions(
                        cp.Conditions.Where(c => c.Negate).Select(c => c.TargetGroup)));

            if (includeContextExpressions != null)
            {
                Logger.Debug("Adding Context Expression Conditions (Include): " +
                             string.Join(", ", includeContextExpressions));
                contextExpressions.Add("Include", includeContextExpressions);
            }

            if (excludeContextExpressions != null)
            {
                Logger.Debug("Adding Context Expression Conditions (Exclude): " +
                             string.Join(", ", excludeContextExpressions));
                contextExpressions.Add("Exclude", excludeContextExpressions);
            }

            if (contextExpressions.Count > 0)
            {
                entityModelData.SetExtensionData("ContextExpressions", contextExpressions);
            }
        }
コード例 #10
0
        internal static IComponentPresentation GenerateTestComponentPresentation()
        {
            ComponentTemplate ct = new ComponentTemplate()
            {
                Id     = "tcm:1-2",
                Title  = GetTestTitle <ComponentTemplate>(),
                Folder = new OrganizationalItem()
                {
                    Id    = "tcm:1-2-2",
                    Title = "Test - folder.title"
                },
                Publication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - publication.title"
                },
                OwningPublication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - owningpublication.title"
                }
            };
            IComponentPresentation cp = new ComponentPresentation()
            {
                ComponentTemplate = ct,
                Component         = (Component)GenerateTestComponent()
            };

            return(cp);
        }
コード例 #11
0
        public string GetContent(string uri, string templateUri = "")
        {
            Schema schema = new Schema();
            schema.Title = Randomizer.AnyString(10);
            Component component = new Component();
            component.Title = Randomizer.AnyString(30);
            component.Id = Randomizer.AnyUri(16);
            component.Schema = schema;

            Field field1 = Randomizer.AnyTextField(6, 120, true);
            Field field2 = Randomizer.AnyTextField(8, 40, false);

            FieldSet fieldSet = new FieldSet();
            fieldSet.Add(field1.Name, field1);
            fieldSet.Add(field2.Name, field2);
            component.Fields = fieldSet;

            if (templateUri == "componentlink")
            {
                CustomizeCompomentForComponentLink(component);
            }
            if (templateUri == "embedded")
            {
                CustomizeCompomentForEmbeddedField(component);
            }
            if (templateUri == "keyword")
            {
                CustomizeCompomentForKeywordField(component);
            }
            if(templateUri == "componentIgnoreCase")
            {
                CustomizeCompomentForComponentLinkIgnoreCase(component);
            }
           
            if (uri == "component")
            {
                return SerializerService.Serialize<Component>(component);
            }

            ComponentTemplate ct = new ComponentTemplate();
            ct.Title = Randomizer.AnyString(20);
            Field fieldView = new Field();
            fieldView.Name = "view";
            fieldView.Values.Add("DefaultComponentView");
            ct.MetadataFields = new FieldSet();
            ct.MetadataFields.Add(fieldView.Name, fieldView);

            ComponentPresentation cp = new ComponentPresentation();
            cp.Component = component;
            cp.ComponentTemplate = ct;

            Condition condition = new KeywordCondition() { Keyword = new Keyword() { Id = "tcm:2-123-1024", Key = "test", Title = "Test" }, Operator = NumericalConditionOperator.Equals, Value = 1 };
            cp.Conditions = new List<Condition>() { condition };

            return SerializerService.Serialize<ComponentPresentation>(cp);
        }
コード例 #12
0
 public static MvcHtmlString SiteEditComponentPresentation(this HtmlHelper helper, IComponent component, string componentTemplateId, bool queryBased, string region)
 {
     ComponentTemplate ct = new ComponentTemplate();
     ct.Id = componentTemplateId;
     ComponentPresentation cp = new ComponentPresentation();
     cp.Component = component as Component;
     cp.ComponentTemplate = ct;
     cp.OrderOnPage = -1;
     return SiteEditComponentPresentation(helper, cp, queryBased, region);
 }
コード例 #13
0
 protected void PopulateDynamicPresentationPageData(ComponentPresentation presentation)
 {
     using (var view = this.GetDynamicComponentView(presentation.ComponentTemplate))
     {
         if (view != null)
         {
             view.PopulatePageData(presentation);
         }
     }
 }
コード例 #14
0
        public string GetContent(string uri, string templateUri = "")
        {
            Schema schema = new Schema();

            schema.Title = Randomizer.AnyString(10);

            Component component = new Component();

            component.Title  = Randomizer.AnyString(30);
            component.Id     = Randomizer.AnyUri(16);
            component.Schema = schema;

            Field field1 = Randomizer.AnyTextField(6, 120, true);
            Field field2 = Randomizer.AnyTextField(8, 40, false);

            FieldSet fieldSet = new FieldSet();

            fieldSet.Add(field1.Name, field1);
            fieldSet.Add(field2.Name, field2);
            component.Fields = fieldSet;
            if (uri == "component")
            {
                return(SerializerService.Serialize <Component>(component));
            }

            ComponentTemplate ct = new ComponentTemplate();

            ct.Title = Randomizer.AnyString(20);
            Field fieldView = new Field();

            fieldView.Name = "view";
            fieldView.Values.Add("DefaultComponentView");
            ct.MetadataFields = new FieldSet();
            ct.MetadataFields.Add(fieldView.Name, fieldView);

            ComponentPresentation cp = new ComponentPresentation();

            cp.Component         = component;
            cp.ComponentTemplate = ct;

            Condition condition = new KeywordCondition()
            {
                Keyword = new Keyword()
                {
                    Id = "tcm:2-123-1024", Key = "test", Title = "Test"
                }, Operator = NumericalConditionOperator.Equals, Value = 1
            };

            cp.Conditions = new List <Condition>()
            {
                condition
            };

            return(SerializerService.Serialize <ComponentPresentation>(cp));
        }
コード例 #15
0
ファイル: SearchData.cs プロジェクト: jhorsman/SI4T
        /// <summary>
        /// Prepare index data for a component presentation
        /// </summary>
        /// <param name="cp">Component Presentation to process</param>
        /// <param name="flaggedDcps">List of already processed CPs, to avoid processing the same DCP more than once</param>
        public virtual void ProcessComponentPresentation(ComponentPresentation cp, List <string> flaggedDcps)
        {
            string id = GetDcpIdentifier(cp);

            if (cp.ComponentTemplate.IsIndexed(_processor.MinimumComponentTemplatePrio) && (flaggedDcps == null || !flaggedDcps.Contains(id)))
            {
                this.Url = GetUrlForDcp(cp);
                FieldProcessorSettings settings = cp.ComponentTemplate.GetFieldProcessorSettings();
                ProcessComponent(cp.Component, settings);
            }
        }
コード例 #16
0
 public bool TryGetComponent(string componentUri, out IComponent component, string templateUri = "")
 {
     IComponentPresentation cp = new ComponentPresentation();
     if (ComponentPresentationFactory.TryGetComponentPresentation(out cp, componentUri))
     {
         component = cp.Component;
         return true;
     }
     component = null;
     return false;
 }
コード例 #17
0
        private string GetRegionFromComponentPresentation(ComponentPresentation cp)
        {
            Match match = Regex.Match(cp.ComponentTemplate.Title, @".*?\[(.*?)\]");

            if (match.Success)
            {
                return(match.Groups[1].Value);
            }
            //default region name
            return(MainRegionName);
        }
コード例 #18
0
        public void DeserializeComponentPresentationFromComponentXml()
        {
            ISerializerService service = GetService(false);

            for (int i = 0; i < loop; i++)
            {
                ComponentPresentation cp = service.Deserialize <ComponentPresentation>(GetTestString <Component>(false));
                Assert.IsNotNull(cp);
                Assert.IsTrue(cp.Component.Title == "Test - component.title");
            }
        }
コード例 #19
0
        public bool TryGetComponent(string componentUri, out IComponent component, string templateUri = "")
        {
            IComponentPresentation cp = new ComponentPresentation();

            if (ComponentPresentationFactory.TryGetComponentPresentation(out cp, componentUri))
            {
                component = cp.Component;
                return(true);
            }
            component = null;
            return(false);
        }
コード例 #20
0
        public static MvcHtmlString SiteEditComponentPresentation(this HtmlHelper helper, IComponent component, string componentTemplateId, bool queryBased, string region)
        {
            ComponentTemplate ct = new ComponentTemplate();

            ct.Id = componentTemplateId;
            ComponentPresentation cp = new ComponentPresentation();

            cp.Component         = component as Component;
            cp.ComponentTemplate = ct;
            cp.OrderOnPage       = -1;
            return(SiteEditComponentPresentation(helper, cp, queryBased, region));
        }
コード例 #21
0
        /// <summary>
        /// Gets the <see cref="T:TcmCDService.Contracts.ComponentPresentation" /> with highest priority.
        /// </summary>
        /// <param name="componentUri">Component uri</param>
        /// <returns>
        ///   <see cref="T:TcmCDService.Contracts.ComponentPresentation" />
        /// </returns>
        public Contracts.ComponentPresentation ComponentPresentationWithHighestPriority(String componentUri)
        {
            Logger.Debug("ComponentPresentationWithHighestPriority: componentUri \"{0}\".", componentUri);

            return(Cache.Get <Contracts.ComponentPresentation>(
                       String.Format("ComponentPresentationWithHighestPriority-{0}", componentUri),
                       () =>
            {
                using (ComponentPresentation componentPresentation = ContentDelivery.DynamicContent.ComponentPresentationCache.GetComponentPresentationWithHighestPriority(componentUri))
                {
                    return componentPresentation.ToContract();
                }
            },
                       CacheRegion.ItemMeta | CacheRegion.ComponentPresentation | CacheRegion.ComponentPresentationMeta,
                       componentUri));
        }
コード例 #22
0
        /// <summary>
        /// Gets the <see cref="T:TcmCDService.Contracts.ComponentPresentation" /> with the specified templateUri
        /// </summary>
        /// <param name="publicationId">Publication id as <see cref="T:System.Int32" /></param>
        /// <param name="componentId">Component id as <see cref="T:System.Int32" /></param>
        /// <param name="templateId">Component template id as <see cref="T:System.Int32" /></param>
        /// <returns>
        ///   <see cref="T:TcmCDService.Contracts.ComponentPresentation" /> or null
        /// </returns>
        public Contracts.ComponentPresentation ComponentPresentation(int publicationId, int componentId, int templateId)
        {
            Logger.Debug("ComponentPresentation: publicationId \"{0}\", componentId \"{1}\", templateId \"{2}\".", publicationId, componentId, templateId);

            return(Cache.Get <Contracts.ComponentPresentation>(
                       String.Format("ComponentPresentation-{0}-{1}-{2}", publicationId, componentId, templateId),
                       () =>
            {
                using (ComponentPresentation componentPresentation = ContentDelivery.DynamicContent.ComponentPresentationCache.GetComponentPresentation(publicationId, componentId, templateId))
                {
                    return componentPresentation.ToContract();
                }
            },
                       CacheRegion.ItemMeta | CacheRegion.ComponentPresentation | CacheRegion.ComponentPresentationMeta,
                       new TcmUri(publicationId, componentId)));
        }
コード例 #23
0
        /// <summary>
        /// Gets the <see cref="T:TcmCDService.Contracts.ComponentPresentation" /> with the specified template id
        /// </summary>
        /// <param name="componentUri">Component uri</param>
        /// <param name="templateId">Component template id as <see cref="T:System.Int32" /></param>
        /// <returns>
        ///   <see cref="T:TcmCDService.Contracts.ComponentPresentation" />
        /// </returns>
        public Contracts.ComponentPresentation ComponentPresentation(String componentUri, int templateId)
        {
            Logger.Debug("ComponentPresentation: componentUri \"{0}\", templateId \"{1}\".", componentUri, templateId);

            return(Cache.Get <Contracts.ComponentPresentation>(
                       String.Format("ComponentPresentation-{0}-{1}", componentUri, templateId),
                       () =>
            {
                using (ComponentPresentation componentPresentation = ContentDelivery.DynamicContent.ComponentPresentationCache.GetComponentPresentation(componentUri, templateId))
                {
                    return componentPresentation.ToContract();
                }
            },
                       CacheRegion.ItemMeta | CacheRegion.ComponentPresentation | CacheRegion.ComponentPresentationMeta,
                       componentUri));
        }
コード例 #24
0
        /// <summary>
        /// Returns grouped components from the current <see cref="T:Tridion.ContentManager.CommunicationManagement.Page" />
        /// list of <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentPresentation" />
        /// </summary>
        /// <param name="component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param>
        /// <param name="page"><see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/></param>
        /// <param name="predicate"><see cref="T:System.Func{Tridion.ContentManager.CommunicationManagement.ComponentPresentation, Tridion.ContentManager.CommunicationManagement.ComponentPresentation, System.Boolean}"/></param>
        /// <returns>List of <see cref="T:Tridion.ContentManager.ContentManagement.Component"/></returns>
        /// <exception cref="System.ArgumentNullException">
        /// component or page or predicate
        /// </exception>
        public static IList <Component> ComponentGroup(this Component component, Page page, Func <ComponentPresentation, ComponentPresentation, Boolean> predicate)
        {
            if (component == null)
            {
                throw new ArgumentNullException("component");
            }

            if (page == null)
            {
                throw new ArgumentNullException("page");
            }

            if (predicate == null)
            {
                throw new ArgumentNullException("predicate");
            }

            // Obtain the component presentations after our current component
            IEnumerable <ComponentPresentation> presentations = page.ComponentPresentations.SkipWhile((cp) =>
            {
                return(cp.Component.Id.ItemId != component.Id.ItemId);
            });

            ComponentPresentation matchedPresentation = presentations.FirstOrDefault();

            if (matchedPresentation == null)
            {
                return(new List <Component>());
            }

            int matchedIndex = page.ComponentPresentations.IndexOf(matchedPresentation);

            if (matchedIndex > 0 && predicate(page.ComponentPresentations[matchedIndex - 1], matchedPresentation))
            {
                return(new List <Component>());
            }

            if (matchedPresentation.Component.Id.ItemId != component.Id.ItemId)
            {
                return(new List <Component>());
            }

            return(presentations.TakeWhile((cp) =>
            {
                return predicate(matchedPresentation, cp);
            }).Select(cp => cp.Component).ToList());
        }
コード例 #25
0
        /// <summary>
        /// Converts a <see cref="T:Tridion.ContentDelivery.DynamicContent.ComponentPresentation" /> to a <see cref="T:TcmCDService.Contracts.ComponentPresentation" /> data contract.
        /// </summary>
        /// <param name="componentPresentation"><see cref="T:Tridion.ContentDelivery.DynamicContent.ComponentPresentation" /></param>
        /// <returns><see cref="T:TcmCDService.Contracts.ComponentPresentation" /></returns>
        internal static Contracts.ComponentPresentation ToContract(this ComponentPresentation componentPresentation)
        {
            if (componentPresentation != null)
            {
                return new Contracts.ComponentPresentation()
                       {
                           ComponentId         = componentPresentation.ComponentId,
                           ComponentTemplateId = componentPresentation.ComponentTemplateId,
                           Content             = componentPresentation.Content,
                           FileLocation        = componentPresentation.FileLocation,
                           Meta          = componentPresentation.Meta.ToContract(),
                           PublicationId = componentPresentation.PublicationId
                       }
            }
            ;

            return(null);
        }
コード例 #26
0
        /// <summary>
        /// Builds an Entity Data Model from a given CM Component Presentation on a Page.
        /// </summary>
        /// <param name="entityModelData">The Entity Data Model to build. Is <c>null</c> for the first Model Builder in the pipeline.</param>
        /// <param name="cp">The CM Component Presentation (obtained from a Page).</param>
        public void BuildEntityModel(ref EntityModelData entityModelData, ComponentPresentation cp)
        {
            // Add extension data for Context Expressions (if applicable)
            string[] includeContextExpressions = ContextExpressionUtils.GetContextExpressions(cp.Conditions.Where(c => !c.Negate).Select(c => c.TargetGroup));
            string[] excludeContextExpressions = ContextExpressionUtils.GetContextExpressions(cp.Conditions.Where(c => c.Negate).Select(c => c.TargetGroup));

            if (includeContextExpressions.Any())
            {
                Logger.Debug("Adding Context Expression Conditions (Include): " + string.Join(", ", includeContextExpressions));
                entityModelData.SetExtensionData("CX.Include", includeContextExpressions);
            }

            if (excludeContextExpressions.Any())
            {
                Logger.Debug("Adding Context Expression Conditions (Exclude): " + string.Join(", ", excludeContextExpressions));
                entityModelData.SetExtensionData("CX.Exclude", excludeContextExpressions);
            }
        }
コード例 #27
0
        public override T Deserialize <T>(string input)
        {
            // NOTE: important exception situation!!
            // if the requested type is IComponentPresentation, there is a possiblity that the data
            // provided to us actually contains a Component instead. In that case we need to add a
            // dummy CT / CP around the Component and return that!


            if (((SerializationProperties)SerializationProperties).CompressionEnabled)
            {
                input = Compressor.Decompress(input);
            }

            TextReader tr = new StringReader(input);

            XmlSerializer serializer = null;

            if (typeof(T) == typeof(Page) || typeof(T) == typeof(IPage))
            {
                serializer = GetXmlSerializer <PageSerializer>();
            }
            else if (typeof(T) == typeof(Component) || typeof(T) == typeof(IComponent))
            {
                serializer = GetXmlSerializer <ComponentSerializer>();
            }
            else if (typeof(T) == typeof(ComponentPresentation) || typeof(T) == typeof(IComponentPresentation))
            {
                if (typeof(T).Name.Contains("ComponentPresentation") &&
                    !input.Substring(0, 30).ToLower().Contains("componentpresentation"))
                {
                    // handle the exception situation where we are asked to deserialize into a CP but the data is actually a Component
                    serializer = GetXmlSerializer <ComponentSerializer>();
                    Component component = (Component)serializer.Deserialize(tr);
                    IComponentPresentation componentPresentation = new ComponentPresentation()
                    {
                        Component         = component,
                        ComponentTemplate = new ComponentTemplate()
                    };
                    return((T)componentPresentation);
                }
                serializer = GetXmlSerializer <ComponentPresentationSerializer>();
            }
            return((T)serializer.Deserialize(tr));
        }
コード例 #28
0
        /// <summary>
        /// Returns grouped components from the current <see cref="T:Tridion.ContentManager.CommunicationManagement.Page" />
        /// list of <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentPresentation" />
        /// </summary>
        /// <param name="component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param>
        /// <param name="template"><see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentTemplate"/></param>
        /// <param name="page"><see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/></param>
        /// <returns>List of <see cref="T:Tridion.ContentManager.ContentManagement.Component"/></returns>
        public static IList <Component> ComponentGroup(this Component component, ComponentTemplate template, Page page)
        {
            bool                  isLocated = false;
            List <Component>      result    = new List <Component>();
            ComponentPresentation previous  = null;

            if (component != null && page != null)
            {
                foreach (ComponentPresentation cp in page.ComponentPresentations)
                {
                    // Locate the first component presentation matching our current component
                    // Also ensure its the first matching component in a "block"
                    if (!isLocated &&
                        cp.Component.Id.ItemId == component.Id.ItemId &&
                        cp.ComponentTemplate.Id.ItemId == template.Id.ItemId &&
                        (previous == null ||
                         (previous.Component.Schema.Id.ItemId != component.Schema.Id.ItemId &&
                          previous.ComponentTemplate.Id.ItemId != template.Id.ItemId)))
                    {
                        isLocated = true;
                        result.Add(cp.Component);
                        continue;
                    }

                    // Now find any following components in the same "block" based on the same schema and using the same component template
                    if (isLocated)
                    {
                        if (cp.Component.Schema.Id.ItemId == component.Schema.Id.ItemId && cp.ComponentTemplate.Id.ItemId == template.Id.ItemId)
                        {
                            result.Add(cp.Component);
                        }
                        else
                        {
                            break;
                        }
                    }

                    previous = cp;
                }
            }

            return(result);
        }
コード例 #29
0
        protected void ExecuteHealthChecks(TextWriter textWriter)
        {
            foreach (HealthCheckElement healthCheck in HealthChecks)
            {
                textWriter.Write("{0,-19:dd-MM HH:mm:ss.ff}{1}: ", Config.Instance.LocalTime ? DateTime.Now : DateTime.UtcNow, healthCheck.ToString());

                switch (healthCheck.HealthCheckType)
                {
                case Configuration.HealthCheckType.ComponentLink:

                    if (!String.IsNullOrEmpty(ContentDelivery.Web.Linking.ComponentLinkCache.ResolveComponentLink(healthCheck.Uri)))
                    {
                        textWriter.WriteLine("Success");
                    }
                    else
                    {
                        textWriter.WriteLine("Failure");
                    }
                    break;

                case Configuration.HealthCheckType.ComponentPresentation:


                    using (ComponentPresentation componentPresentation = ContentDelivery.DynamicContent.ComponentPresentationCache.GetComponentPresentationWithHighestPriority(healthCheck.Uri))
                    {
                        if (componentPresentation != null && !String.IsNullOrEmpty(componentPresentation.Content))
                        {
                            textWriter.WriteLine("Success");
                        }
                        else
                        {
                            textWriter.WriteLine("Failure");
                        }
                    }
                    break;

                default:
                    textWriter.WriteLine("Unknown healthcheck type");
                    break;
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Determines whether the specified <see cref="T:Tridion.ContentManager.ContentManagement.Component"/>
        /// is used in the last <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentPresentation" />
        /// on the <see cref="T:Tridion.ContentManager.CommunicationManagement.Page" />
        /// </summary>
        /// <param name="component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param>
        /// <param name="page"><see cref="T:Tridion.ContentManager.CommunicationManagement.Page" /></param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="T:Tridion.ContentManager.ContentManagement.Component"/> is used in the last <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentPresentation" />
        ///   on the <see cref="T:Tridion.ContentManager.CommunicationManagement.Page" />; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsLastComponent(this Component component, Page page)
        {
            if (component != null)
            {
                if (page != null)
                {
                    ComponentPresentation last = page.ComponentPresentations.Last();

                    if (last != null)
                    {
                        return(last.Component.Id == component.Id);
                    }
                }

                // No page present, this component is the only component
                return(true);
            }

            return(false);
        }
コード例 #31
0
ファイル: TridionDataHelper.cs プロジェクト: hem-kant/Mi4T
        /// <summary>
        ///
        /// </summary>
        /// <param name="URI"></param>
        /// <returns></returns>
        public static XmlDocument GetComponent(string URI)
        {
            ComponentPresentationFactory cpf;
            XmlDocument result = null;
            int         contentRepositoryId = GetContentRepositoryId(URI);

            cpf = new ComponentPresentationFactory(contentRepositoryId);
            ComponentPresentation cp = cpf.GetComponentPresentationWithHighestPriority(URI);

            if (cp != null && (!string.IsNullOrEmpty(cp.Content)))
            {
                result = new XmlDocument();
                result.LoadXml(cp.Content);
            }
            else
            {
                result = null;
            }

            return(result);
        }
コード例 #32
0
 public static Region GetMatchingRegion(IList<Region> regions, ComponentPresentation componentPresentation)
 {
     foreach (Region region in regions)
     {
         if (region.CanContain(componentPresentation))
         {
             return region;
         }
         foreach (var cp in region.ComponentPresentations)
         {
             if (cp.InnerRegion != null)
             {
                 if (cp.InnerRegion.CanContain(componentPresentation))
                 {
                     return cp.InnerRegion;
                 }
             }
         }
     }
     return null;
 }
コード例 #33
0
        internal static IPage GenerateTestPage()
        {
            Page p = new Page()
            {
                Id             = "tcm:1-2-64",
                Title          = GetTestTitle <Page>(),
                StructureGroup = new OrganizationalItem()
                {
                    Id    = "tcm:1-2-2",
                    Title = "Test - structuregroup.title"
                },
                Publication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - publication.title"
                },
                OwningPublication = new Publication()
                {
                    Id    = "tcm:0-2-1",
                    Title = "Test - owningpublication.title"
                },
                ComponentPresentations = new System.Collections.Generic.List <ComponentPresentation>()
            };
            List <Condition> conditions = new List <Condition>();

            conditions.Add(new CustomerCharacteristicCondition()
            {
                Name     = "CustomersOnly",
                Negate   = false,
                Operator = ConditionOperator.Equals,
                Value    = "ID"
            }
                           );
            ComponentPresentation cp = (ComponentPresentation)GenerateTestComponentPresentation();

            cp.Conditions = conditions;
            p.ComponentPresentations.Add(cp);
            return(p);
        }
コード例 #34
0
        /// <summary>
        /// Check if a component presentation is own by this container
        /// </summary>
        /// <param name="componentPresentation"></param>
        /// <returns></returns>
        public bool Owns(ComponentPresentation componentPresentation)
        {
            int containerIndex = ExtractContainerIndex(componentPresentation.ComponentTemplate.Id);

            if (containerIndex != -1)
            {
                return(containerIndex == this.Index);
            }
            else if (componentPresentation.ComponentTemplate.Metadata != null && componentPresentation.ComponentTemplate.MetadataSchema != null)
            {
                var metadata = new ItemFields(componentPresentation.ComponentTemplate.Metadata, componentPresentation.ComponentTemplate.MetadataSchema);
                if (metadata.Contains("regionName"))
                {
                    TextField regionName = (TextField)metadata["regionName"];
                    if (regionName.Values.Count() > 0)
                    {
                        return(regionName.Value.Equals(this.containerName));
                    }
                }
            }
            return(false);
        }
コード例 #35
0
        public void BuildEntityModel(ref EntityModelData entityModelData, ComponentPresentation cp)
        {
            Logger.Debug("Adding target groups to entity model data.");
            if (cp.Conditions == null || cp.Conditions.Count <= 0)
            {
                return;
            }
            List <Condition> conditions = new List <Condition>();

            foreach (var condition in cp.Conditions)
            {
                var mapped = MapConditions(condition.TargetGroup.Conditions);
                if (mapped == null || mapped.Count <= 0)
                {
                    continue;
                }
                conditions.AddRange(mapped);
            }
            if (conditions.Count > 0)
            {
                entityModelData.SetExtensionData("TargetGroupConditions", conditions.ToArray());
            }
        }
コード例 #36
0
ファイル: PageFactory.cs プロジェクト: sanalmenon/DD4T.Core
        private void LoadComponentModelsFromComponentPresentationFactory(IPage page)
        {
            LoggerService.Debug(">>LoadComponentModelsFromComponentPresentationFactory ({0})", LoggingCategory.Performance, page.Id);

            foreach (DD4T.ContentModel.ComponentPresentation cp in page.ComponentPresentations)
            {
                if (cp.Component == null)
                {
                    continue;
                }

                // added by QS: only load DCPs from broker if they are in fact dynamic!
                if (cp.IsDynamic)
                {
                    try
                    {
                        ComponentPresentation dcp = (ComponentPresentation)ComponentPresentationFactory.GetComponentPresentation(cp.Component.Id, cp.ComponentTemplate.Id);
                        cp.Component = dcp.Component;
                        //Fix for backward compatibility. We keep using the template on the page as 1.x version of dd4t doesn't have the componenttemplate data in the dcp
                        //The title is mandatory in tridion, so it can't be null or empty when successful, the id will still be set by the factory
                        if (!String.IsNullOrEmpty(dcp.ComponentTemplate.Title))
                        {
                            cp.ComponentTemplate = dcp.ComponentTemplate;
                        }
                        cp.TargetGroupConditions = dcp.TargetGroupConditions;
                    }
                    catch (ComponentPresentationNotFoundException)
                    {
                        LoggerService.Warning("dynamic component presentation {0} / {1} included on page {2} cannot be found; it may have been unpublished", LoggingCategory.Model, cp.Component.Id, cp.ComponentTemplate.Id, page.Id);
                        // DCPs can be unpublished while the page that they are embedded on remain published
                        // in this case, simply ignore the exception (the 'stub' component is still on the page)
                    }
                }
            }
            LoggerService.Debug("<<LoadComponentModelsFromComponentPresentationFactory ({0})", LoggingCategory.Performance, page.Id);
        }
コード例 #37
0
 public ActionResult Component(ComponentPresentation componentPresentation)
 {
     return this.ComponentPresentation(componentPresentation.Component.Id);
 }
コード例 #38
0
 public static ComponentPresentation CreateComponentPresentation(int publicationId, int componentId, int templateId, string presentationContent, string outputFormat)
 {
     ComponentPresentation componentPresentation = new ComponentPresentation();
     componentPresentation.PublicationId = publicationId;
     componentPresentation.ComponentId = componentId;
     componentPresentation.TemplateId = templateId;
     componentPresentation.PresentationContent = presentationContent;
     componentPresentation.OutputFormat = outputFormat;
     return componentPresentation;
 }
コード例 #39
0
ファイル: SearchData.cs プロジェクト: RAJMITTAL/dxa-modules
 public virtual string GetUrlForDcp(ComponentPresentation cp)
 {
     //Need to cover the case where a DCP is allowed on page - should we then use dynamic linking to get the URL?
     return cp.Component.Id.ToString();
 }
コード例 #40
0
ファイル: SearchData.cs プロジェクト: RAJMITTAL/dxa-modules
 /// <summary>
 /// Get an ID that will uniquely identify a DCP
 /// </summary>
 /// <param name="cp">The DCP</param>
 /// <returns>Id in the form: dcp:{pubid}-{compid}-{ctid}</returns>
 public virtual string GetDcpIdentifier(ComponentPresentation cp)
 {
     return GetDcpIdentifier(cp.Component.Id.PublicationId, cp.Component.Id.ItemId, cp.ComponentTemplate.Id.ItemId);
 }
コード例 #41
0
ファイル: SearchData.cs プロジェクト: RAJMITTAL/dxa-modules
 /// <summary>
 /// Prepare index data for a component presentation
 /// </summary>
 /// <param name="cp">Component Presentation to process</param>
 /// <param name="flaggedDcps">List of already processed CPs, to avoid processing the same DCP more than once</param>
 public virtual void ProcessComponentPresentation(ComponentPresentation cp, List<string> flaggedDcps)
 {
     string id = GetDcpIdentifier(cp);
     if (cp.ComponentTemplate.IsIndexed(_processor.MinimumComponentTemplatePrio) && (flaggedDcps == null || !flaggedDcps.Contains(id)))
     {
         this.Url = GetUrlForDcp(cp);
         FieldProcessorSettings settings = cp.ComponentTemplate.GetFieldProcessorSettings();
         ProcessComponent(cp.Component, settings);
     }
 }
コード例 #42
0
 public ActionResult EmailShoppingList(ComponentPresentation componentPresentation, string EmailButton)
 {
     ShoppingListEmail email = new ShoppingListEmail {
         items = this.shoppinglistrepository.GetShoppingListItemsByProduct(base.User.Identity.Name),
         itemHtml = "\n\n"
     };
     string projectName = string.Empty;
     foreach (IGrouping<string, ShoppingListItem> grouping in email.items)
     {
         int num = 0;
         foreach (ShoppingListItem item in grouping)
         {
             num += item.Quantity;
         }
         if (num != 0)
         {
             string itemHtml;
             if (projectName != grouping.First<ShoppingListItem>().ProjectName)
             {
                 itemHtml = email.itemHtml;
                 email.itemHtml = itemHtml + Helper.GetResource("ShoppingListProject") + ": " + grouping.First<ShoppingListItem>().ProjectName + "\n\n";
             }
             itemHtml = email.itemHtml;
             email.itemHtml = itemHtml + Helper.GetResource("ShoppingListProduct") + ": " + grouping.First<ShoppingListItem>().ProductName + "\n";
             itemHtml = email.itemHtml;
             email.itemHtml = itemHtml + Helper.GetResource("ShoppingListBrand") + ": " + grouping.First<ShoppingListItem>().Brand + "\n";
             object obj2 = email.itemHtml;
             email.itemHtml = string.Concat(new object[] { obj2, Helper.GetResource("ShoppingListQuantity"), ": ", num, "\n" });
             email.itemHtml = email.itemHtml + "\n";
         }
         projectName = grouping.First<ShoppingListItem>().ProjectName;
     }
     email.itemHtml = email.itemHtml + "\n";
     email.EmailAddress = base.User.Identity.Name;
     bool flag = this.shoppinglistrepository.SendShoppingListEmail(email);
     ShoppingList model = new ShoppingList {
         componentPresentation = componentPresentation,
         items = this.shoppinglistrepository.GetShoppingListItemsByProject(base.User.Identity.Name)
     };
     if (base.Request.IsAjaxRequest())
     {
         var data = new {
             success = flag
         };
         return base.Json(data, JsonRequestBehavior.AllowGet);
     }
     return base.View(model);
 }
コード例 #43
0
        public ActionResult Index(ComponentPresentation componentPresentation, Registration model, string Stage)
        {
            bool flag = base.Request.IsAjaxRequest();
            bool flag2 = false;
            bool flag3 = false;
            string errorMessage = string.Empty;
            string returnUrl = string.Empty;
            LoginForm loginForm = model.LoginForm;
            RegistrationForm registrationForm = model.RegistrationForm;
            string str3 = !string.IsNullOrWhiteSpace(base.Request["source"]) ? base.Request["source"] : string.Empty;
            if (loginForm != null)
            {
                if (!string.IsNullOrEmpty(loginForm.ReturnUrl))
                {
                    returnUrl = loginForm.ReturnUrl;
                }
                if (!string.IsNullOrEmpty(str3))
                {
                    returnUrl = str3;
                }
                errorMessage = Helper.GetResource("LoginFailed");
                if (this.Login(loginForm))
                {
                    errorMessage = Helper.GetResource("LoginSuccess");
                    flag3 = true;
                    flag2 = true;
                }
                else
                {
                    ((dynamic) base.ViewBag).Stage = "register";
                    base.ModelState.AddModelError("LoginFailed", errorMessage);
                }
                if (flag)
                {
                    return base.Json(new { 
                        success = flag3,
                        allowRedirect = flag2,
                        redirect = returnUrl,
                        message = errorMessage
                    });
                }
            }
            if (registrationForm != null)
            {
                EmailUtility utility;
                string str4;
                string str5;
                string str6;
                Exception exception;
                if (!string.IsNullOrEmpty(registrationForm.returnUrl))
                {
                    returnUrl = registrationForm.returnUrl;
                }
                if (!string.IsNullOrEmpty(str3))
                {
                    returnUrl = str3;
                }
                errorMessage = Helper.GetResource("RegistrationFailed");
                PublicasterServiceRequest request = new PublicasterServiceRequest();
                switch (Stage)
                {
                    case "register":
                        errorMessage = Helper.GetResource("RegistrationFailed");
                        if (!this.IsProfileValid(registrationForm))
                        {
                            ((dynamic) base.ViewBag).Stage = "register";
                            flag3 = false;
                            errorMessage = Helper.GetResource("RegistrationFailed");
                            base.ModelState.AddModelError("UnableToCreateNewUser", Helper.GetResource("UnableToCreateNewUser"));
                            break;
                        }
                        if (this.Register(registrationForm))
                        {
                            ((dynamic) base.ViewBag).Stage = "preferences";
                            flag3 = true;
                            errorMessage = Helper.GetResource("RegisteredSuccessfully");
                            this.Logger.InfoFormat("RegistrationController : User created: {0} - {1}", new object[] { registrationForm.CustomerDetails.DisplayName, registrationForm.CustomerDetails.EmailAddress });
                            try
                            {
                                if (!WebConfiguration.Current.CheckEmailNewsletterOption)
                                {
                                    utility = new EmailUtility();
                                    str4 = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"];
                                    str5 = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"];
                                    str6 = utility.SendEmail(registrationForm.CustomerDetails, str5, str4, registrationForm.CustomerDetails.EmailAddress);
                                    this.Logger.DebugFormat("RegistrationController : Register Confirmation Email > result {0}", new object[] { str6 });
                                }
                            }
                            catch (Exception exception1)
                            {
                                exception = exception1;
                                this.Logger.Debug("Unable to send confirmation email to user.");
                            }
                        }
                        else
                        {
                            ((dynamic) base.ViewBag).Stage = "register";
                            flag3 = false;
                            errorMessage = Helper.GetResource("UnableToCreateNewUser");
                            base.ModelState.AddModelError("UnableToCreateNewUser", Helper.GetResource("UnableToCreateNewUser"));
                        }
                        break;

                    case "preferences":
                        errorMessage = Helper.GetResource("PreferencesFailed");
                        model.RegistrationForm.returnUrl = this._settings.RegisterWelcome;
                        if (this.Preferences(registrationForm))
                        {
                            ((dynamic) base.ViewBag).Stage = "profile";
                            flag3 = true;
                            errorMessage = Helper.GetResource("PreferencesSaved");
                            try
                            {
                                MvcApplication.CraftsPrincipal user = (MvcApplication.CraftsPrincipal) base.HttpContext.User;
                                CoatsUserProfile profile = CoatsUserProfile.GetProfile(base.User.Identity.Name);
                                utility = new EmailUtility();
                                str4 = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"];
                                str5 = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"];
                                string newsletter = "No";
                                string interests = string.Empty;
                                foreach (KeyValuePair<string, string> pair in registrationForm.Keywords)
                                {
                                    interests = interests + pair.Key + ",";
                                }
                                if (interests.Length > 0)
                                {
                                    interests = interests.Substring(0, interests.LastIndexOf(",") - 1);
                                }
                                KeyValuePair<string, string> pair2 = registrationForm.Keywords.SingleOrDefault<KeyValuePair<string, string>>(e => e.Key == WebConfiguration.Current.EmailNewsletterYes);
                                if (pair2.Key != null)
                                {
                                    newsletter = "yes";
                                }
                                if (WebConfiguration.Current.CheckEmailNewsletterOption && (pair2.Key != null))
                                {
                                    newsletter = "yes";
                                    string str9 = string.Empty;
                                    if (base.Request.Url != null)
                                    {
                                        str9 = base.Request.Url.Scheme + "://" + base.Request.Url.Host;
                                    }
                                    else
                                    {
                                        str9 = ConfigurationManager.AppSettings["SiteUrl"];
                                    }
                                    string registerThankYou = this._settings.RegisterThankYou;
                                    string str11 = HttpUtility.UrlEncode(General.Encrypt(profile.MAIL.Trim()));
                                    str9 = registerThankYou + "?UserEmail=" + str11;
                                    registrationForm.CustomerDetails.SiteUrl = str9;
                                    registrationForm.CustomerDetails.DisplayName = profile.DISPLAYNAME;
                                    registrationForm.CustomerDetails.LastName = profile.SURNAME;
                                    registrationForm.CustomerDetails.FirstName = profile.NAME;
                                    registrationForm.CustomerDetails.EmailAddress = profile.MAIL;
                                    str6 = utility.SendEmail(registrationForm.CustomerDetails, str5, str4, profile.MAIL);
                                    this.Logger.DebugFormat("RegistrationController : Register Confirmation Email > result {0}", new object[] { str6 });
                                    string clientIP = this.GetClientIP();
                                    this._registrationrepository.SaveRegisterData(registrationForm.CustomerDetails.EmailAddress, clientIP, "");
                                    request.createJsonPublicasterRequest(registrationForm.CustomerDetails.EmailAddress, registrationForm.CustomerDetails.FirstName, registrationForm.CustomerDetails.LastName, interests, registrationForm.CustomerDetails.DisplayName, newsletter);
                                }
                            }
                            catch (Exception exception2)
                            {
                                exception = exception2;
                                this.Logger.Debug("Unable to send confirmation email to user.");
                            }
                        }
                        else
                        {
                            ((dynamic) base.ViewBag).Stage = "preferences";
                            flag3 = false;
                        }
                        break;

                    case "profile":
                        errorMessage = Helper.GetResource("PreferencesSaved");
                        model.RegistrationForm.returnUrl = this._settings.RegisterWelcome;
                        if (this.Preferences(registrationForm))
                        {
                            flag3 = true;
                            errorMessage = Helper.GetResource("ProfileSaved");
                            base.HttpContext.Session["registrationStatus"] = "";
                            returnUrl = this._settings.RegisterWelcome;
                            flag2 = true;
                        }
                        else
                        {
                            ((dynamic) base.ViewBag).Stage = "profile";
                            flag3 = false;
                        }
                        break;
                }
            }
            if (flag2)
            {
                returnUrl = !string.IsNullOrEmpty(returnUrl) ? returnUrl : base.Url.Content(WebConfiguration.Current.MyProfile);
                if (flag)
                {
                    return base.Json(new { 
                        success = flag3,
                        allowRedirect = flag2,
                        redirect = returnUrl,
                        message = errorMessage
                    });
                }
                base.HttpContext.Response.Redirect(returnUrl);
            }
            model.RegistrationForm = (registrationForm != null) ? registrationForm : new RegistrationForm();
            model.LoginForm = (loginForm != null) ? loginForm : new LoginForm();
            model.RegistrationForm.returnUrl = returnUrl;
            model.LoginForm.ReturnUrl = returnUrl;
            this.GetModelData(model.RegistrationForm);
            return base.View(model);
        }
コード例 #44
0
ファイル: Region.cs プロジェクト: NiclasCedermalm/dd4t-lite
 private ComponentPresentationInfo AddToComponentPresentationList(ComponentPresentation componentPresentation)
 {
     ComponentPresentationInfo cpInfo = new ComponentPresentationInfo(this.page, componentPresentation, this);
     this.ComponentPresentations.Add(cpInfo);
     return cpInfo;
 }
コード例 #45
0
ファイル: Region.cs プロジェクト: NiclasCedermalm/dd4t-lite
        public bool CanContain(ComponentPresentation componentPresentation)
        {
            if (this.ComponentPresentations.Count < this.MaxOccurs)
            {
                foreach (ComponentType componentType in this.ComponentTypes)
                {
                    if (componentPresentation.Component.Schema.Id.Equals(componentType.SchemaUri) &&
                         componentPresentation.ComponentTemplate.Id.Equals(componentType.TemplateUri))
                    {
                        return true;
                    }

                }
            }
            return false;
        }
コード例 #46
0
ファイル: Region.cs プロジェクト: NiclasCedermalm/dd4t-lite
 public virtual void Add(ComponentPresentation componentPresentation)
 {
     Logger.Write("Adding CP to page index: " + pageIndex, "RegionGravityHandler", LogCategory.Custom, System.Diagnostics.TraceEventType.Information);
     this.AddToComponentPresentationList(componentPresentation);
     page.ComponentPresentations.Insert(pageIndex + this.ComponentPresentations.Count(), componentPresentation);
 }
コード例 #47
0
ファイル: Region.cs プロジェクト: NiclasCedermalm/dd4t-lite
 public static bool IsRegion(ComponentPresentation componentPresentation)
 {
     return componentPresentation.Component.Schema.Title.Equals("DD4T Lite Region");
 }
コード例 #48
0
 public ActionResult Index(ComponentPresentation componentPresentation, UserProfile model)
 {
     this.Logger.DebugFormat("Called Update Profile >>>> ", new object[0]);
     try
     {
         ((dynamic) base.ViewBag).Title = componentPresentation.Component.Fields["title"].Value;
     }
     catch (Exception)
     {
     }
     string email = string.Empty;
     if (base.User.Identity.IsAuthenticated)
     {
         email = base.User.Identity.Name;
     }
     bool flag = this.IsEditModelValid(model);
     if (flag)
     {
         try
         {
             MembershipUser user = Membership.GetUser();
             if (user == null)
             {
                 flag = false;
                 this.Logger.DebugFormat("Update Profile mUser null", new object[0]);
             }
             if (model.AddressDetails.Postcode != null)
             {
                 this.FindPostcode(model);
             }
             if (model.RegistrationStatus == "postcode invalid")
             {
                 flag = false;
             }
             if (flag)
             {
                 this.Logger.DebugFormat("User profile start  >>>>", new object[0]);
                 CoatsUserProfile userProfile = CoatsUserProfile.GetProfile(user.Email);
                 if (userProfile != null)
                 {
                     string selectedKeywords = base.Request["CraftType"];
                     string str3 = base.Request["email-newsletter"];
                     string str4 = base.Request["visibile-profile"];
                     PublicasterServiceRequest request = new PublicasterServiceRequest();
                     string newsletter = "No";
                     if (str3.Trim() == WebConfiguration.Current.EmailNewsletterYes.Trim())
                     {
                         newsletter = "yes";
                     }
                     if (((selectedKeywords != null) || (str3 != null)) || (str4 != null))
                     {
                         List<TridionTcmUri> keywordsSelectListItems = GetKeywordsSelectListItems(selectedKeywords);
                         List<TridionTcmUri> second = GetKeywordsSelectListItems(str3);
                         List<TridionTcmUri> list3 = GetKeywordsSelectListItems(str4);
                         IEnumerable<TridionTcmUri> enumerable = keywordsSelectListItems.Union<TridionTcmUri>(second).Union<TridionTcmUri>(list3);
                         Dictionary<string, string> dictionary = new Dictionary<string, string>();
                         foreach (TridionTcmUri uri in enumerable)
                         {
                             dictionary.Add(uri.TcmId, "tcm");
                         }
                         userProfile.Keywords = dictionary;
                         model.Keywords = dictionary;
                     }
                     if (!string.IsNullOrEmpty(model.NewPassword))
                     {
                         if (model.NewPassword == model.VerifyNewPassword)
                         {
                             if (!string.IsNullOrEmpty(model.CurrentPassword))
                             {
                                 CoatsUserProfile profile = CoatsUserProfile.GetProfile(email);
                                 if (model.CurrentPassword == profile.PASSWORD)
                                 {
                                     model.CustomerDetails.Password = model.NewPassword;
                                 }
                                 else
                                 {
                                     flag = false;
                                     base.ModelState.AddModelError("CurrentPasswordIncorrect", Helper.GetResource("CurrentPasswordIncorrect"));
                                 }
                             }
                             else
                             {
                                 flag = false;
                             }
                         }
                         else
                         {
                             flag = false;
                             base.ModelState.AddModelError("NewPasswordsNotMatch", Helper.GetResource("NewPasswordsNotMatch"));
                         }
                     }
                     if (flag)
                     {
                         this.MapUserProfileForUpdate(model, userProfile);
                         userProfile.Save();
                         if ((str3 != null) && WebConfiguration.Current.CheckEmailNewsletterOption)
                         {
                             if (str3.Trim() == WebConfiguration.Current.EmailNewsletterYes.Trim())
                             {
                                 EmailUtility utility = new EmailUtility();
                                 string fromEmailAddress = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"];
                                 string emailTemplate = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"];
                                 string registerThankYou = this._settings.RegisterThankYou;
                                 string str9 = HttpUtility.UrlEncode(General.Encrypt(userProfile.MAIL.Trim()));
                                 registerThankYou = registerThankYou + "?UserEmail=" + str9;
                                 model.CustomerDetails.SiteUrl = registerThankYou;
                                 model.CustomerDetails.DisplayName = userProfile.DISPLAYNAME;
                                 model.CustomerDetails.EmailAddress = userProfile.MAIL;
                                 string str10 = utility.SendEmail(model.CustomerDetails, emailTemplate, fromEmailAddress, userProfile.MAIL);
                                 this.Logger.DebugFormat("ProfileController : Register Confirmation Email > result {0}", new object[] { str10 });
                                 request.createJsonPublicasterRequest(userProfile.MAIL, userProfile.NAME, userProfile.SURNAME, selectedKeywords, userProfile.DISPLAYNAME, newsletter);
                             }
                             else
                             {
                                 request.UnSubscripePublicaster(userProfile.MAIL);
                             }
                         }
                         CoatsUserProfile profile3 = CoatsUserProfile.GetProfile(userProfile.MAIL);
                         CookieHelper.WriteFormsCookie(userProfile.MAIL, userProfile.DISPLAYNAME, userProfile.NAME, userProfile.SURNAME, userProfile.LONG, userProfile.LAT, "");
                         ((dynamic) base.ViewBag).profileStatus = "saved";
                         if (profile3 == null)
                         {
                             flag = false;
                             base.ModelState.AddModelError(string.Empty, "");
                             this.Logger.DebugFormat("Update Profile newUser null", new object[0]);
                         }
                     }
                 }
             }
         }
         catch (Exception exception)
         {
             this.Logger.DebugFormat("Update Profile exception {0} {1}", new object[] { exception.Message, exception.InnerException });
             flag = false;
         }
     }
     if (base.ModelState.ContainsKey("CustomerDetails.DisplayName"))
     {
         base.ModelState["CustomerDetails.DisplayName"].Errors.Clear();
     }
     if (base.ModelState.ContainsKey("CustomerDetails.EmailAddress"))
     {
         base.ModelState["CustomerDetails.EmailAddress"].Errors.Clear();
     }
     if (!flag)
     {
         UserProfile profile4 = this.GetModel();
         base.ModelState.AddModelError(string.Empty, "");
         var typeArray = (from x in base.ModelState
             where x.Value.Errors.Count > 0
             select new { 
                 Key = x.Key,
                 Errors = x.Value.Errors
             }).ToArray();
         foreach (var type in typeArray)
         {
             this.Logger.DebugFormat("Update Profile error {0}", new object[] { type });
         }
         this.GetModelData(profile4);
         base.Session["feedback"] = Helper.GetResource("ProfileError");
         ((dynamic) base.ViewBag).profileStatus = "error";
         return base.View(profile4);
     }
     UserProfile profile5 = this.GetModel();
     base.Session["feedback"] = Helper.GetResource("ProfileChangesSaved");
     return base.View(profile5);
 }
コード例 #49
0
 public void AddToComponentPresentations(ComponentPresentation componentPresentation)
 {
     base.AddObject("ComponentPresentations", componentPresentation);
 }
コード例 #50
0
 public ActionResult Index(ComponentPresentation componentPresentation)
 {
     ShoppingList model = new ShoppingList {
         componentPresentation = componentPresentation,
         items = this.shoppinglistrepository.GetShoppingListItemsByProject(base.User.Identity.Name)
     };
     return base.View(model);
 }
コード例 #51
0
        public ActionResult Index(ComponentPresentation presentation, string Location = "", decimal Latitude = 0, decimal Longitude = 0, string Distance = null, bool clear = false, string Address = "", string NoJS = "", string WithinVal = null)
        {
            if (clear)
            {
                if (this.Logger.IsDebugEnabled)
                {
                    this.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();
            }
            bool flag = false;
            bool flag2 = false;
            if ((Latitude != 0M) && (Longitude != 0M))
            {
                flag = true;
            }
            else if (string.IsNullOrEmpty(Location))
            {
                flag2 = true;
            }
            string filterByBrandname = "";
            if (!string.IsNullOrEmpty(base.Session.GetLevel1BrandFilter()))
            {
                filterByBrandname = base.RouteData.Values.GetLevel1BrandSearchValue();
            }
            if (Distance == null)
            {
                Distance = WebConfiguration.Current.StoreLocatorDefaultValue;
            }
            StoreLocatorResults results = new StoreLocatorResults {
                DistanceItems = this.storelocatorrepository.GetDistanceItems(Distance),
                Distance = Convert.ToInt16(Distance)
            };
            if (!string.IsNullOrEmpty(WebConfiguration.Current.StoreLocatorWithinVals))
            {
                if (WithinVal != null)
                {
                    results.WithinItems = this.storelocatorrepository.GetWithinItems(WithinVal);
                }
                else
                {
                    results.WithinItems = this.storelocatorrepository.GetWithinItems(null);
                }
            }
            else
            {
                results.WithinItems = new List<SelectListItem>();
            }
            GoogleMapsMarker marker = null;
            List<GoogleMapsMarker> markerForPostcode = new List<GoogleMapsMarker>();
            if (!string.IsNullOrEmpty(Address))
            {
                base.Session["SelectedAddress"] = Address;
            }
            else if ((string.IsNullOrEmpty(Address) && !string.IsNullOrEmpty(Location)) && (Location == (base.Session["SelectedAddress"] as string)))
            {
                Address = Location;
            }
            if ((flag && (NoJS != "true")) || (!string.IsNullOrEmpty(Address) && (NoJS == "true")))
            {
                marker = new GoogleMapsMarker("current", Latitude, Longitude);
                if (!string.IsNullOrEmpty(Address))
                {
                    marker = this.setAddressOnMarker(Address, ',', marker);
                }
                results.Latitude = Latitude;
                results.Longitude = Longitude;
            }
            else if (string.IsNullOrEmpty(Location))
            {
                results.Latitude = Convert.ToDecimal(WebConfiguration.Current.StoreLocatorLatitude, CultureInfo.InvariantCulture);
                results.Longitude = Convert.ToDecimal(WebConfiguration.Current.StoreLocatorLongitude, CultureInfo.InvariantCulture);
            }
            else
            {
                results.Location = Location;
                string culture = WebConfiguration.Current.Culture;
                string bias = "";
                if (string.IsNullOrEmpty(WithinVal))
                {
                    bias = culture.Substring(culture.Length - 2);
                }
                else
                {
                    bias = WithinVal;
                }
                markerForPostcode = this.storelocatorrepository.GetMarkerForPostcode(Location, bias);
                int result = 5;
                int.TryParse(WebConfiguration.Current.StoreLocatorMaxDisambigResults, out result);
                switch (markerForPostcode.Count)
                {
                    case 0:
                        results.Error = Helper.GetResource("StoreLocatorPostcodeNotFound");
                        break;

                    case 1:
                        if (markerForPostcode[0].type == "country")
                        {
                            results.Error = Helper.GetResource("StoreLocatorPostcodeNotFound");
                            break;
                        }
                        marker = markerForPostcode[0];
                        results.Latitude = marker.lat;
                        Latitude = marker.lat;
                        results.Longitude = marker.lng;
                        Longitude = marker.lng;
                        break;

                    default:
                        results.Options = markerForPostcode.GetRange(0, (markerForPostcode.Count >= result) ? result : markerForPostcode.Count);
                        results.Latitude = Convert.ToDecimal(WebConfiguration.Current.StoreLocatorLatitude, CultureInfo.InvariantCulture);
                        results.Longitude = Convert.ToDecimal(WebConfiguration.Current.StoreLocatorLongitude, CultureInfo.InvariantCulture);
                        break;
                }
            }
            if (marker != null)
            {
                List<StoreLocatorRetailer> list2 = this.storelocatorrepository.GetStoreLocatorRetailers(marker, Convert.ToInt16(Distance), filterByBrandname);
                if (list2.Count > 0)
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    results.Retailers = list2;
                    results.RetailersJSON = serializer.Serialize(list2);
                    results.StaticMapAddress = this.storelocatorrepository.GetStaticMap(marker, list2);
                }
                else
                {
                    results.Error = Helper.GetResource("StoreLocatorNoRetailers");
                }
                results.Location = this.getAddressFromLocation(marker);
                results.Latitude = marker.lat;
                results.Longitude = marker.lng;
            }
            this.SetComponentTypes(results);
            if (base.RouteData.Values.IsLevel1BrandFilterActivated())
            {
                results.Brand = base.RouteData.Values.GetLevel1BrandComponent();
                ((dynamic) base.ViewBag).StoreLocator = true;
            }
            return base.View(results);
        }
コード例 #52
0
 private string GetRegionFromComponentPresentation(ComponentPresentation cp)
 {
     Match match = Regex.Match(cp.ComponentTemplate.Title, @".*?\[(.*?)\]");
     if (match.Success)
     {
         return match.Groups[1].Value;
     }
     //default region name
     return MainRegionName;
 }