public static Dynamic.PageTemplate BuildPageTemplate(TComm.PageTemplate tcmPageTemplate, BuildManager manager)
        {
            Dynamic.PageTemplate pt = new Dynamic.PageTemplate();
            pt.Title = tcmPageTemplate.Title;
            pt.Id = tcmPageTemplate.Id.ToString();
            pt.FileExtension = tcmPageTemplate.FileExtension;
            pt.RevisionDate = tcmPageTemplate.RevisionDate;

            if (tcmPageTemplate.Metadata != null && tcmPageTemplate.MetadataSchema != null)
            {
                pt.MetadataFields = new Dynamic.FieldSet();
                TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmPageTemplate.Metadata, tcmPageTemplate.MetadataSchema);
                pt.MetadataFields = manager.BuildFields(tcmMetadataFields);
            }
            else
            {
                pt.MetadataFields = null;
            }

            if (!manager.BuildProperties.OmitContextPublications)
                pt.Publication = manager.BuildPublication(tcmPageTemplate.ContextRepository);

            if (!manager.BuildProperties.OmitOwningPublications)
                pt.OwningPublication = manager.BuildPublication(tcmPageTemplate.OwningRepository);

            if (!manager.BuildProperties.OmitFolders)
                pt.Folder = manager.BuildOrganizationalItem((TCM.Folder)tcmPageTemplate.OrganizationalItem);

            return pt;
        }
        public static Dynamic.Schema BuildSchema(TCM.Schema tcmSchema, BuildManager manager)
        {
			if (tcmSchema == null) {
				return null;
			}
			Dynamic.Schema s = new Dynamic.Schema();
			s.Title = tcmSchema.Title;
			s.Id = tcmSchema.Id.ToString();

            if (!manager.BuildProperties.OmitContextPublications)
                s.Publication = manager.BuildPublication(tcmSchema.ContextRepository);
            if (!manager.BuildProperties.OmitFolders)
                s.Folder = manager.BuildOrganizationalItem((TCM.Folder)tcmSchema.OrganizationalItem);

            if (!String.IsNullOrEmpty(tcmSchema.RootElementName))
            {
                s.RootElementName = tcmSchema.RootElementName;
            }
            // note that non-webschemas and multimedia schema's lack a root element. In order not
            // to break deserialization, setting it to undefined will do
            else
            {
                s.RootElementName = "undefined";
            }

			return s;
		}
        public static List<Dynamic.Category> BuildCategories(TCM.Component component, BuildManager manager)
        {
            // note that there might be multiple fields based on the same category, so we need to combine them
            // for that purpose we use a dictionary
            Dictionary<string, Dynamic.Category> categories = new Dictionary<string, Dynamic.Category>();

            // first, add categories from the content (note that mm components have no content!)
            if (component.Content != null)
            {
                ItemFields tcmFields = new TCM.Fields.ItemFields(component.Content, component.Schema);
                addFromItemFields(tcmFields, categories, manager);
            }

            // next, add categories from the metadata
            if (component.Metadata != null)
            {
                ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(component.Metadata, component.MetadataSchema);
                addFromItemFields(tcmMetadataFields, categories, manager);
            }

            // finally, create a List from the Dictionary and return it
            List<Dynamic.Category> categoryList = new List<Dynamic.Category>();
            foreach (Dynamic.Category cat in categories.Values)
            {
                categoryList.Add(cat);
            }
            return categoryList;
        }
        public static List<Dynamic.Category> BuildCategories(TComm.Page page, BuildManager manager)
        {
            // note that there might be multiple fields based on the same category, so we need to combine them
            // for that purpose we use a dictionary


            if (page.Metadata == null || page.MetadataSchema == null)
            {
                return new List<Dynamic.Category>();
            }

            Dictionary<string, Dynamic.Category> categories = new Dictionary<string, Dynamic.Category>();


            // first, add categires from the metadata
            ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(page.Metadata, page.MetadataSchema);
            addFromItemFields(tcmMetadataFields, categories, manager);

            // finally, create a List from the Dictionary and return it
            List<Dynamic.Category> categoryList = new List<Dynamic.Category>();
            foreach (Dynamic.Category cat in categories.Values)
            {
                categoryList.Add(cat);
            }
            return categoryList;
        }
        public static Dynamic.ComponentTemplate BuildComponentTemplate(TComm.ComponentTemplate tcmComponentTemplate, BuildManager manager)
        {
            Dynamic.ComponentTemplate ct = new Dynamic.ComponentTemplate();
            ct.Title = tcmComponentTemplate.Title;
            ct.Id = tcmComponentTemplate.Id.ToString();
            ct.OutputFormat = tcmComponentTemplate.OutputFormat;
            ct.RevisionDate = tcmComponentTemplate.RevisionDate;
            if (tcmComponentTemplate.Metadata != null && tcmComponentTemplate.MetadataSchema != null)
            {
                ct.MetadataFields = new Dynamic.FieldSet();
                TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmComponentTemplate.Metadata, tcmComponentTemplate.MetadataSchema);
                ct.MetadataFields = manager.BuildFields(tcmMetadataFields); 
            }
            else
            {
                ct.MetadataFields = null;
            }


            if (!manager.BuildProperties.OmitContextPublications)
                ct.Publication = manager.BuildPublication(tcmComponentTemplate.ContextRepository);

            if (!manager.BuildProperties.OmitOwningPublications)
                ct.OwningPublication = manager.BuildPublication(tcmComponentTemplate.OwningRepository);

            if (!manager.BuildProperties.OmitFolders)
                ct.Folder = manager.BuildOrganizationalItem((TCM.Folder)tcmComponentTemplate.OrganizationalItem);

            return ct;
        }
 /// <summary>
 /// Map the conditions from a Component Presentaton to DD4T conditions
 /// </summary>
 public static List<Dynamic.Condition> MapTargetGroupConditions(IList<Tcm.TargetGroupCondition> componentPresentationConditions, BuildManager buildManager)
 {
     var mappedConditions = new List<Dynamic.Condition>();
     foreach (var componentPresentationCondition in componentPresentationConditions)
     {
         mappedConditions.AddRange(MapConditions(componentPresentationCondition.TargetGroup.Conditions, buildManager));
     }
     return mappedConditions;
 }
        public static Dynamic.ComponentPresentation BuildComponentPresentation(TCM.ComponentPresentation tcmComponentPresentation, Engine engine, int linkLevels, bool resolveWidthAndHeight, BuildManager manager)
        {
            Dynamic.ComponentPresentation cp = new Dynamic.ComponentPresentation();

            if (tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable)
            {
                // call render but ignore the output - render ensures componentlinking will be setup as normal.
                // don't bother with page flags because the end result is dynamically published so it needs to run with DCP settings
                engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);

                // ignore the rendered CP, because it is already available in the broker
                // instead, we will render a very simple version without any links
                cp.Component = manager.BuildComponent(tcmComponentPresentation.Component, 0, false,false); // linkLevels = 0 means: only summarize the component
                cp.IsDynamic = true;
            }
            else
            {
                // render the component presentation using its own CT
                // but first, set a parameter in the context so that the CT will know it is beng called
                // from a DynamicDelivery page template
                if (engine.PublishingContext.RenderContext != null && !engine.PublishingContext.RenderContext.ContextVariables.Contains(BasePageTemplate.VariableNameCalledFromDynamicDelivery))
                {
                    engine.PublishingContext.RenderContext.ContextVariables.Add(BasePageTemplate.VariableNameCalledFromDynamicDelivery, BasePageTemplate.VariableValueCalledFromDynamicDelivery);
                }

                string renderedContent = engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);
                engine.PublishingContext.RenderContext.ContextVariables.Remove(BasePageTemplate.VariableNameCalledFromDynamicDelivery);

                renderedContent = TridionUtils.StripTcdlTags(renderedContent);

                cp.IsDynamic = false;
                TextReader tr = new StringReader(renderedContent);
                if (serializer == null)
                {
                    serializer = new ComponentSerializer();
                    //serializer = new XmlSerializerFactory().CreateSerializer(typeof(Dynamic.Component));
                }
                try
                {
                    cp.Component = (Dynamic.Component)serializer.Deserialize(tr);
                }
                catch (Exception e)
                {
                    TemplatingLogger.GetLogger(typeof(ComponentPresentationBuilder)).Error("exception while deserializing into CP: " + e.Message);                    
                    // the component presentation could not be deserialized, this probably not a Dynamic Delivery template
                    // just store the output as 'RenderedContent' on the CP
                    cp.RenderedContent = renderedContent;
                    // because the CT was not a DD4T CT, we will generate the DD4T XML code here
                    cp.Component = manager.BuildComponent(tcmComponentPresentation.Component);
                }
            }
            cp.ComponentTemplate = manager.BuildComponentTemplate(tcmComponentPresentation.ComponentTemplate);
            return cp;
        }
예제 #8
0
        public static Dynamic.Page BuildPage(TCM.Page tcmPage, Engine engine, BuildManager manager, int linkLevels, bool resolveWidthAndHeight,bool publishEmptyFields)
        {
            Dynamic.Page p = new Dynamic.Page
                                 {
                                     Title = tcmPage.Title,
                                     Id = tcmPage.Id.ToString(),
                                     Filename = tcmPage.FileName,
                                     PageTemplate = manager.BuildPageTemplate(tcmPage.PageTemplate),
                                     Schema = manager.BuildSchema(tcmPage.MetadataSchema),
                                     Version = tcmPage.Version,
                                     RevisionDate = tcmPage.RevisionDate,
                                     MetadataFields = new Dynamic.FieldSet()
                                 };
            if (linkLevels > 0)
            {
                try
                {
                    if (tcmPage.Metadata != null && tcmPage.MetadataSchema != null)
                    {
                        var tcmMetadataFields = new Tridion.ContentManager.ContentManagement.Fields.ItemFields(tcmPage.Metadata, tcmPage.MetadataSchema);
                        p.MetadataFields = manager.BuildFields(tcmMetadataFields);
                    }
                }
                catch (Exception)
                {
                    // fail silently if there is no metadata schema
                }
            }

            p.ComponentPresentations = new List<Dynamic.ComponentPresentation>();
            foreach (TCM.ComponentPresentation cp in tcmPage.ComponentPresentations)
            {
                Dynamic.ComponentPresentation dynCp = manager.BuildComponentPresentation(cp, engine, linkLevels - 1, resolveWidthAndHeight);
                p.ComponentPresentations.Add(dynCp);
            }
            p.StructureGroup = manager.BuildOrganizationalItem((TCM.StructureGroup)tcmPage.OrganizationalItem);

            if (!manager.BuildProperties.OmitContextPublications)
            {
                p.Publication = manager.BuildPublication(tcmPage.ContextRepository);
            }
            if (!manager.BuildProperties.OmitOwningPublications)
            {
                p.OwningPublication = manager.BuildPublication(tcmPage.OwningRepository);
            }
            if (!manager.BuildProperties.OmitCategories)
            {
                p.Categories = manager.BuildCategories(tcmPage);
            }
            manager.AddXpathToFields(p.MetadataFields, "Metadata");
            return p;
        }
        public static Dynamic.ComponentPresentation BuildComponentPresentation(TCM.ComponentPresentation tcmComponentPresentation, Engine engine, BuildManager manager)
        {
            TemplatingLogger logger = TemplatingLogger.GetLogger(typeof(ComponentPresentationBuilder));
            Dynamic.ComponentPresentation cp = new Dynamic.ComponentPresentation();

            logger.Debug(string.Format(">BuildCP {0} ({1})", tcmComponentPresentation.ComponentTemplate.Title, tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable));
            if (tcmComponentPresentation.ComponentTemplate.IsRepositoryPublishable)
            {
                // call render but ignore the output - render ensures componentlinking will be setup as normal.
                // don't bother with page flags because the end result is dynamically published so it needs to run with DCP settings
                engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);

                // ignore the rendered CP, because it is already available in the broker
                // instead, we will render a very simple version without any links
                cp.Component = manager.BuildComponent(tcmComponentPresentation.Component, 0); // linkLevel = 0 means: only summarize the component
                cp.IsDynamic = true;
            }
            else
            {
                // render the component presentation using its own CT
                // but first, set a parameter in the context so that the CT will know it is beng called
                // from a DynamicDelivery page template
                if (engine.PublishingContext.RenderContext != null && !engine.PublishingContext.RenderContext.ContextVariables.Contains(BasePageTemplate.VariableNameCalledFromDynamicDelivery))
                {
                    engine.PublishingContext.RenderContext.ContextVariables.Add(BasePageTemplate.VariableNameCalledFromDynamicDelivery, BasePageTemplate.VariableValueCalledFromDynamicDelivery);
                }

                string renderedContent = engine.RenderComponentPresentation(tcmComponentPresentation.Component.Id, tcmComponentPresentation.ComponentTemplate.Id);
                renderedContent = TridionUtils.StripTcdlTags(renderedContent);
     
                try
                {
                    // we cannot be sure the component template uses the same serializer service as the page template
                    // so we will call a factory which can detect the correct service based on the content
                    ISerializerService serializerService = SerializerServiceFactory.FindSerializerServiceForContent(renderedContent);
                    cp = serializerService.Deserialize<Dynamic.ComponentPresentation>(renderedContent);
                }
                catch (Exception e)
                {
                    log.Error("exception while deserializing into CP", e);
                    // the component presentation could not be deserialized, this probably not a Dynamic Delivery template
                    // just store the output as 'RenderedContent' on the CP
                    cp.RenderedContent = renderedContent;
                    // because the CT was not a DD4T CT, we will generate the DD4T XML code here
                    cp.Component = manager.BuildComponent(tcmComponentPresentation.Component);
                }
                cp.IsDynamic = false;
            }
            cp.ComponentTemplate = manager.BuildComponentTemplate(tcmComponentPresentation.ComponentTemplate);
            return cp;
        }
 /// <summary>
 /// Build a DD4T Target group from a AM Target Group
 /// </summary>
 public static Dynamic.TargetGroup BuildTargetGroup(Tridion.ContentManager.AudienceManagement.TargetGroup targetGroup, BuildManager buildManager)
 {
     var tg = new Dynamic.TargetGroup
     {
         Conditions = MapConditions(targetGroup.Conditions, buildManager),
         Description = targetGroup.Description,
         Id = targetGroup.Id,
         OwningPublication = PublicationBuilder.BuildPublication(targetGroup.OwningRepository),
         Publication = PublicationBuilder.BuildPublication(targetGroup.ContextRepository),
         PublicationId = targetGroup.ContextRepository.Id,
         Title = targetGroup.Title
     };
     return tg;
 }
		public static Dynamic.ComponentTemplate BuildComponentTemplate(TComm.ComponentTemplate tcmComponentTemplate, BuildManager manager) {
			Dynamic.ComponentTemplate ct = new Dynamic.ComponentTemplate();
			ct.Title = tcmComponentTemplate.Title;
			ct.Id = tcmComponentTemplate.Id.ToString();
			ct.OutputFormat = tcmComponentTemplate.OutputFormat;
            ct.RevisionDate = tcmComponentTemplate.RevisionDate;
         if (tcmComponentTemplate.Metadata != null && tcmComponentTemplate.MetadataSchema != null)
         {
             ct.MetadataFields = new Dynamic.FieldSet();
            TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmComponentTemplate.Metadata, tcmComponentTemplate.MetadataSchema);
            ct.MetadataFields = manager.BuildFields(tcmMetadataFields, 0, false,false); // never follow links to components from component templates, never resolve binary widht/height
         }
         else
         {
            ct.MetadataFields = null;
         }
         ct.Folder = manager.BuildOrganizationalItem((TCM.Folder)tcmComponentTemplate.OrganizationalItem);
         ct.Publication = manager.BuildPublication(tcmComponentTemplate.ContextRepository);
			return ct;
		}
 private static List<Condition> MapConditions(IList<Tridion.ContentManager.AudienceManagement.Condition> conditions, BuildManager buildManager)
 {
     var mappedConditions = new List<Dynamic.Condition>();
     foreach (var condition in conditions)
     {
         if (condition is TrackingKeyCondition)
         {
             mappedConditions.Add(MapTrackingKeyCondition((TrackingKeyCondition)condition, buildManager));
         }
         else if (condition is Tcm.TargetGroupCondition)
         {
             mappedConditions.Add(MapTargetGroupCondition((Tcm.TargetGroupCondition)condition, buildManager));
         }
         else if (condition is Tcm.CustomerCharacteristicCondition)
         {
             mappedConditions.Add(MapCustomerCharacteristicCondition((Tcm.CustomerCharacteristicCondition)condition));
         }
         else
         {
             log.Warning("Condition of type: " + condition.GetType().FullName + " was not supported by the mapping code.");
         }
     }
     return mappedConditions;
 }
       public static void AddFields(Dynamic.FieldSet fields, TCM.Fields.ItemFields tcmItemFields, int linkLevels, bool resolveWidthAndHeight, bool publishEmptyFields, Dynamic.MergeAction mergeAction, BuildManager manager)
       {
           GeneralUtils.TimedLog(string.Format("add fields: found {0} fields",tcmItemFields.Count));
           

           foreach (TCM.Fields.ItemField tcmItemField in tcmItemFields)
           {
               GeneralUtils.TimedLog("add fields: found " + tcmItemField.Name);
               try
               {
                   if (fields.ContainsKey(tcmItemField.Name))
                   {
                       GeneralUtils.TimedLog("field exists already, with " + fields[tcmItemField.Name].Values.Count + " values");
                       if (mergeAction.Equals(Dynamic.MergeAction.Skip) || (mergeAction.Equals(Dynamic.MergeAction.MergeMultiValueSkipSingleValue) && tcmItemField.Definition.MaxOccurs == 1))
                       {
                           GeneralUtils.TimedLog(string.Format("skipping field (merge action {0}, maxoccurs {1}", mergeAction.ToString(), tcmItemField.Definition.MaxOccurs));
                           continue;
                       }
                       Dynamic.Field f = manager.BuildField(tcmItemField, linkLevels, resolveWidthAndHeight,publishEmptyFields);
                       if (mergeAction.Equals(Dynamic.MergeAction.Replace) || (mergeAction.Equals(Dynamic.MergeAction.MergeMultiValueReplaceSingleValue) && tcmItemField.Definition.MaxOccurs == 1))
                       {
                           GeneralUtils.TimedLog(string.Format("replacing field (merge action {0}, maxoccurs {1}", mergeAction.ToString(), tcmItemField.Definition.MaxOccurs));
                           fields.Remove(f.Name);
                           fields.Add(f.Name, f);
                       }
                       else
                       {
                           IField existingField = fields[f.Name];
                           switch (existingField.FieldType)
                           {

                               case FieldType.ComponentLink:
                               case FieldType.MultiMediaLink:
                                   foreach (Component linkedComponent in f.LinkedComponentValues)
                                   {
                                       bool valueExists = false;
                                       foreach (Component existingLinkedComponent in existingField.LinkedComponentValues)
                                       {
                                           if (linkedComponent.Id.Equals(existingLinkedComponent.Id))
                                           {
                                               // this value already exists
                                               valueExists = true;
                                               break;
                                           }
                                       }
                                       if (!valueExists)
                                       {
                                           existingField.LinkedComponentValues.Add(linkedComponent);
                                       }
                                   }
                                   break;
                               case FieldType.Date:
                                   foreach (DateTime dateTime in f.DateTimeValues)
                                   {
                                       bool valueExists = false;
                                       foreach (DateTime existingDateTime in existingField.DateTimeValues)
                                       {
                                           if (dateTime.Equals(existingDateTime))
                                           {
                                               // this value already exists
                                               valueExists = true;
                                               break;
                                           }
                                       }
                                       if (!valueExists)
                                       {
                                           existingField.DateTimeValues.Add(dateTime);
                                       }
                                   }
                                   break;
                               case FieldType.Number:
                                   foreach (int nr in f.NumericValues)
                                   {
                                       bool valueExists = false;
                                       foreach (int existingNr in existingField.NumericValues)
                                       {
                                           if (nr == existingNr)
                                           {
                                               // this value already exists
                                               valueExists = true;
                                               break;
                                           }
                                       }
                                       if (!valueExists)
                                       {
                                           existingField.NumericValues.Add(nr);
                                       }
                                   }
                                   break;
                               default:
                                   foreach (string val in f.Values)
                                   {
                                       bool valueExists = false;
                                       foreach (string existingVal in existingField.Values)
                                       {
                                           if (val.Equals(existingVal))
                                           {
                                               // this value already exists
                                               valueExists = true;
                                               break;
                                           }
                                       }
                                       GeneralUtils.TimedLog(string.Format("found value {0}, valueExists: {1}", val, valueExists));
                                       if (!valueExists)
                                       {
                                           existingField.Values.Add(val);
                                       }
                                   }
                                   break;
                           }
                       }
                   }
                   else
                   {
                       Dynamic.Field f = manager.BuildField(tcmItemField, linkLevels, resolveWidthAndHeight,publishEmptyFields);
                       fields.Add(f.Name, f);
                   }
               }
               catch (FieldHasNoValueException)
               {
                   // fail silently, field is not added to the list
               }
               catch (FieldTypeNotDefinedException)
               {
                   // fail silently, field is not added to the list
               }
           }
       }
예제 #14
0
        public static Dynamic.Field BuildField(TCM.Fields.ItemField tcmItemField, int currentLinkLevel, BuildManager manager)
        {
            Dynamic.Field f = new Dynamic.Field();

            if (tcmItemField == null && manager.BuildProperties.PublishEmptyFields)
            {
                f.Values.Add("");
                return f;
            }
            else if (tcmItemField == null && !manager.BuildProperties.PublishEmptyFields)
            {
                throw new FieldHasNoValueException();
            }
            f.Name = tcmItemField.Name;
            if (tcmItemField is TCM.Fields.XhtmlField)
            {
                TCM.Fields.XhtmlField sField = (TCM.Fields.XhtmlField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(manager.PublishBinariesInRichTextField(v));
                    }
                }
                f.FieldType = FieldType.Xhtml;
                return f;
            }
            if (tcmItemField is TCM.Fields.MultiLineTextField)
            {
                TCM.Fields.TextField sField = (TCM.Fields.MultiLineTextField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(v);
                    }
                }
                f.FieldType = FieldType.MultiLineText;
                return f;
            }
            if (tcmItemField is TCM.Fields.TextField)
            {
                TCM.Fields.TextField sField = (TCM.Fields.TextField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(v);
                    }
                }
                f.FieldType = FieldType.Text;
                return f;
            }
            if (tcmItemField is TCM.Fields.KeywordField)
            {
                TCM.Fields.KeywordField sField = (TCM.Fields.KeywordField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    // add keyword values
                    f.Keywords = new List<Keyword>();
                    // we will wrap each linked component in a ContentModel component
                    foreach (TCM.Keyword kw in sField.Values)
                    {
                        f.Keywords.Add(manager.BuildKeyword(kw));
                    }
                    if (!manager.BuildProperties.OmitValueLists)
                    {
                        f.Values = new List<string>();
                        foreach (TCM.Keyword kw in sField.Values)
                        {
                            f.Values.Add(kw.Title);
                        }
                    }

                    KeywordFieldDefinition fieldDef = (KeywordFieldDefinition)sField.Definition;
                    f.CategoryId = fieldDef.Category.Id;
                    f.CategoryName = fieldDef.Category.Title;
                }
                f.FieldType = FieldType.Keyword;
                return f;
            }
            if (tcmItemField is TCM.Fields.NumberField)
            {
                TCM.Fields.NumberField sField = (TCM.Fields.NumberField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    f.NumericValues = (List<double>)sField.Values;
                    if (!manager.BuildProperties.OmitValueLists)
                    {
                        f.Values = new List<string>();
                        foreach (double d in f.NumericValues)
                        {
                            f.Values.Add(Convert.ToString(d));
                        }
                    }
                }
                f.FieldType = FieldType.Number;
                return f;
            }
            if (tcmItemField is TCM.Fields.DateField)
            {
                TCM.Fields.DateField sField = (TCM.Fields.DateField)tcmItemField;

                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    f.DateTimeValues = (List<DateTime>)sField.Values;
                    if (!manager.BuildProperties.OmitValueLists)
                    {
                        f.Values = new List<string>();
                        foreach (DateTime dt in f.DateTimeValues)
                        {
                            f.Values.Add(Convert.ToString(dt));
                        }
                    }
                }
                f.FieldType = FieldType.Date;
                return f;
            }
            if (tcmItemField is TCM.Fields.MultimediaLinkField)
            {
                TCM.Fields.MultimediaLinkField sField = (TCM.Fields.MultimediaLinkField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add(tcmItemField.Name);
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    // we will wrap each linked component in a ContentModel component
                    f.LinkedComponentValues = new List<Dynamic.Component>();
                    int nextLinkLevel = currentLinkLevel - 1;
                    if (MustFollowField(sField, manager))
                    {
                        log.Debug(string.Format("found component link field named {0} with global followLinksPerField property set to false OR followLink set to true for this field", sField.Name));
                    }
                    else
                    {
                        log.Debug(string.Format("found component link field named {0} with followLink set to false for this field", sField.Name));
                        nextLinkLevel = 0;
                    }
                    foreach (TCM.Component comp in sField.Values)
                    {
                        f.LinkedComponentValues.Add(manager.BuildComponent(comp, nextLinkLevel));
                    }
                    if (!manager.BuildProperties.OmitValueLists)
                    {
                        f.Values = new List<string>();
                        foreach (Dynamic.Component c in f.LinkedComponentValues)
                        {
                            f.Values.Add(c.Id);
                        }
                    }
                }
                f.FieldType = FieldType.MultiMediaLink;
                return f;
            }
            if (tcmItemField is TCM.Fields.ComponentLinkField)
            {
                TCM.Fields.ComponentLinkField sField = (TCM.Fields.ComponentLinkField)tcmItemField;
                if (sField.Values.Count == 0 && manager.BuildProperties.PublishEmptyFields)
                {
                    f.Values.Add(tcmItemField.Name);
                }
                else if (sField.Values.Count == 0 && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    // we will wrap each linked component in a ContentModel component
                    f.LinkedComponentValues = new List<Dynamic.Component>();
                    int nextLinkLevel = currentLinkLevel - 1;
                    if (MustFollowField(sField, manager))
                    {
                        log.Debug(string.Format("found component link field named {0} with global followLinksPerField property set to false OR followLink set to true for this field", sField.Name));
                    }
                    else
                    {
                        log.Debug(string.Format("found component link field named {0} with followLink set to false for this field", sField.Name));
                        nextLinkLevel = 0;
                    }

                    foreach (TCM.Component comp in sField.Values)
                    {
                        f.LinkedComponentValues.Add(manager.BuildComponent(comp, nextLinkLevel));
                    }


                    if (!manager.BuildProperties.OmitValueLists)
                    {
                        f.Values = new List<string>();
                        foreach (Dynamic.Component c in f.LinkedComponentValues)
                        {
                            f.Values.Add(c.Id);
                        }
                    }
                }
                f.FieldType = FieldType.ComponentLink;
                return f;
            }

            if (tcmItemField is TCM.Fields.EmbeddedSchemaField)
            {

                TCM.Fields.EmbeddedSchemaField sField = (TCM.Fields.EmbeddedSchemaField)tcmItemField;
                f.FieldType = FieldType.Embedded;
                f.EmbeddedValues = new List<Dynamic.FieldSet>();
                bool hasValues = CheckIfEmbeddedFieldHasValues(sField);
                if (!hasValues && manager.BuildProperties.PublishEmptyFields)
                {
                    Dynamic.FieldSet fields = new FieldSet();
                    Dynamic.Field fe = new Dynamic.Field();
                    f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema);
                    EmbeddedSchemaFieldDefinition linksFieldDefinition = sField.Definition as EmbeddedSchemaFieldDefinition;
                    ItemFields newItemField = new ItemFields(linksFieldDefinition.EmbeddedSchema);

                    for (int i = 0; i < newItemField.Count; i++)
                    {

                        if (newItemField[i] is TCM.Fields.EmbeddedSchemaField)
                        {
                            TCM.Fields.EmbeddedSchemaField innerField = (TCM.Fields.EmbeddedSchemaField)newItemField[i];
                            if (innerField.Values.Count == 0)
                            {
                                Dynamic.FieldSet fieldsinner = new FieldSet();
                                Dynamic.Field fin = new Dynamic.Field();
                                fe.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)innerField.Definition).EmbeddedSchema);
                                EmbeddedSchemaFieldDefinition inlinksFieldDefinition = innerField.Definition as EmbeddedSchemaFieldDefinition;
                                ItemFields newinItemField = new ItemFields(inlinksFieldDefinition.EmbeddedSchema);
                                for (int n = 0; n < newinItemField.Count; n++)
                                {
                                    fin.Name = newItemField[n].Name;
                                    fieldsinner.Add(newinItemField[n].Name, fin);
                                }
                                fe.EmbeddedValues.Add(fieldsinner);
                                fe.Values.Add("");
                            }
                            fe.Name = newItemField[i].Name;
                            fields.Add(newItemField[i].Name, fe);

                        }
                        else
                        {
                            Dynamic.Field fein = manager.BuildField(newItemField[i], currentLinkLevel);
                            fein.Values.Clear();
                            fields.Add(newItemField[i].Name, fein);
                        }
                    }
                    f.EmbeddedValues.Add(fields);
                    f.Values.Add("");
                }
                else if (!hasValues && !manager.BuildProperties.PublishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {

                    // we will wrap each linked component in a ContentModel component
                    f.EmbeddedValues = new List<Dynamic.FieldSet>();
                    f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema);

                    foreach (TCM.Fields.ItemFields embeddedFields in sField.Values)
                    {
                        f.EmbeddedValues.Add(manager.BuildFields(embeddedFields, currentLinkLevel));
                    }
                }

                return f;
            }

            throw new FieldTypeNotDefinedException();
        }
예제 #15
0
 private static bool MustFollowField(TCM.Fields.ComponentLinkField field, BuildManager manager)
 {
     // TODO: check for setting 'followLinksPerField'
     if (!manager.BuildProperties.FollowLinksPerField)
         return true;
     XmlNamespaceManager nsMan = new XmlNamespaceManager(new NameTable());
     nsMan.AddNamespace("dd4t", "http://www.sdltridion.com/2011/DD4TField");
     XmlElement followLink = (XmlElement)field.Definition.ExtensionXml.SelectSingleNode("//dd4t:configuration/dd4t:followlink", nsMan);
     return (followLink != null && followLink.InnerText == "true");
 }
예제 #16
0
 public static Dynamic.Component BuildComponent(TCM.Component tcmComponent, BuildManager manager)
 {
     return BuildComponent(tcmComponent, manager.BuildProperties.LinkLevels, manager);
 }
예제 #17
0
      public static Dynamic.Component BuildComponent(TCM.Component tcmComponent, int currentLinkLevel, BuildManager manager)
      {
          log.Debug(string.Format("start BuildComponent with component {0} ({1}) and link level {2}", tcmComponent.Title, tcmComponent.Id, currentLinkLevel));
          Dynamic.Component c = new Dynamic.Component();
          c.Title = tcmComponent.Title;
          c.Id = tcmComponent.Id.ToString();
          c.RevisionDate = tcmComponent.RevisionDate;

          c.Version = tcmComponent.Version;
          c.Schema = manager.BuildSchema(tcmComponent.Schema);
          
          c.ComponentType = (ComponentType)Enum.Parse(typeof(ComponentType), tcmComponent.ComponentType.ToString());

          if (tcmComponent.ComponentType.Equals(TCM.ComponentType.Multimedia))
          {
              Multimedia multimedia = new Multimedia();
              multimedia.MimeType = tcmComponent.BinaryContent.MultimediaType.MimeType;

              // PLEASE NOTE: this weird way to set the size of the multimedia is needed because of a difference between Tridion 2011 and 2013
              // The property in Tridion's BinaryContent class changed its name AND its type (int FileSize became long Size)
              // This way, we can use preprocessing to choose the right property
              // Thijs Borst and Quirijn Slings, 9 April 2015
#if Legacy
              PropertyInfo prop = tcmComponent.BinaryContent.GetType().GetProperty("FileSize", BindingFlags.Public | BindingFlags.Instance);
              multimedia.Size = Convert.ToInt64(prop.GetValue(tcmComponent.BinaryContent,null));
#else
              PropertyInfo prop = tcmComponent.BinaryContent.GetType().GetProperty("Size", BindingFlags.Public | BindingFlags.Instance);
              multimedia.Size = (long) prop.GetValue(tcmComponent.BinaryContent,null);
#endif
              multimedia.FileName = tcmComponent.BinaryContent.Filename;

              string extension = System.IO.Path.GetExtension(multimedia.FileName);
              if (string.IsNullOrEmpty(extension))
              {
                  multimedia.FileExtension = "";
              }
              else
              {
                  // remove leading dot from extension because microsoft returns this as ".gif"
                  multimedia.FileExtension = extension.Substring(1);
              }

              if (manager.BuildProperties.ResolveWidthAndHeight)
              {
                  try
                  {
                      MemoryStream memstream = new MemoryStream();
                      tcmComponent.BinaryContent.WriteToStream(memstream);
                      Image image = Image.FromStream(memstream);
                      memstream.Close();

                      multimedia.Width = image.Size.Width;
                      multimedia.Height = image.Size.Height;
                  }
                  catch (Exception e)
                  {
                      log.Warning(string.Format("error retrieving width and height of image: is component with ID {0} really an image? Error message: {1}", c.Id, e.Message));
                      multimedia.Width = 0;
                      multimedia.Height = 0;
                  }
              }
              else
              {
                  multimedia.Width = 0;
                  multimedia.Height = 0;
              }
              c.Multimedia = multimedia;
              c.Multimedia.Url = manager.PublishMultimediaComponent(c);
          }
          else
          {
              c.Multimedia = null;
          }
          c.Fields = new Dynamic.FieldSet();
          c.MetadataFields = new Dynamic.FieldSet();
          if (currentLinkLevel > 0)
          {
              if (tcmComponent.Content != null)
              {
                  TCM.Fields.ItemFields tcmFields = new TCM.Fields.ItemFields(tcmComponent.Content, tcmComponent.Schema);
                  c.Fields = manager.BuildFields(tcmFields, currentLinkLevel);
              }
              
              if (tcmComponent.Metadata != null)
              {
                  TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmComponent.Metadata, tcmComponent.MetadataSchema);
                  c.MetadataFields = manager.BuildFields(tcmMetadataFields, currentLinkLevel);
              }
          }
          if (!manager.BuildProperties.OmitContextPublications)
          {
              c.Publication = manager.BuildPublication(tcmComponent.ContextRepository);
          }
          if (!manager.BuildProperties.OmitOwningPublications)
          {
              c.OwningPublication = manager.BuildPublication(tcmComponent.OwningRepository);
          }
          if (!manager.BuildProperties.OmitFolders)
          {
              TCM.Folder folder = (TCM.Folder)tcmComponent.OrganizationalItem;
              c.Folder = manager.BuildOrganizationalItem(folder);
          }
          if (!manager.BuildProperties.OmitCategories)
          {
              c.Categories = manager.BuildCategories(tcmComponent);
          }
          manager.AddXpathToFields(c.Fields, "tcm:Content/custom:" + tcmComponent.Schema.RootElementName); 
          manager.AddXpathToFields(c.MetadataFields, "tcm:Metadata/custom:Metadata");
          return c;
      }
        private static void addFromItemFields(ItemFields tcmFields, Dictionary<string, Dynamic.Category> categories, BuildManager manager)
        {
            foreach (ItemField f in tcmFields)
            {
                if (f is KeywordField)
                {
                    string categoryId = ((KeywordFieldDefinition)f.Definition).Category.Id;
                    Dynamic.Category dc;
                    if (!categories.ContainsKey(categoryId))
                    {
                        // create category since it doesn't exist yet
                        dc = new Dynamic.Category();
                        dc.Id = ((KeywordFieldDefinition)f.Definition).Category.Id;
                        dc.Title = ((KeywordFieldDefinition)f.Definition).Category.Title;
                        dc.Keywords = new List<Dynamic.Keyword>();
                        categories.Add(dc.Id, dc);
                    }
                    else
                    {
                        dc = categories[categoryId];
                    }
                    foreach (Keyword keyword in ((KeywordField)f).Values)
                    {
                        bool alreadyThere = false;
                        foreach (Dynamic.Keyword dk in dc.Keywords)
                        {
                            if (dk.Id.Equals(keyword.Id))
                            {
                                alreadyThere = true;
                                break;
                            }
                        }
                        if (!alreadyThere)
                        {
                            dc.Keywords.Add(manager.BuildKeyword(keyword));
                        }
                    }
                }

                if (f is EmbeddedSchemaField)
                {
                    try
                    {
                        IList<ItemFields> embeddedFieldsCollection = ((EmbeddedSchemaField)f).Values;
                        foreach (ItemFields embeddedFields in embeddedFieldsCollection)
                        {
                            foreach (ItemField embeddedField in embeddedFields)
                            {
                                if (embeddedField is KeywordField)
                                {
                                    GeneralUtils.TimedLog("FOUND EMBEDDED KEYWORD FIELD");
                                    string categoryId = ((KeywordFieldDefinition)embeddedField.Definition).Category.Id;

                                    Dynamic.Category dc;
                                    if (!categories.ContainsKey(categoryId))
                                    {
                                        // create category since it doesn't exist yet
                                        dc = new Dynamic.Category();
                                        dc.Id = ((KeywordFieldDefinition)embeddedField.Definition).Category.Id;
                                        dc.Title = ((KeywordFieldDefinition)embeddedField.Definition).Category.Title;
                                        dc.Keywords = new List<Dynamic.Keyword>();
                                        categories.Add(dc.Id, dc);
                                    }
                                    else
                                    {
                                        dc = categories[categoryId];
                                    }
                                    foreach (Keyword keyword in ((KeywordField)embeddedField).Values)
                                    {
                                        bool alreadyThere = false;
                                        foreach (Dynamic.Keyword dk in dc.Keywords)
                                        {
                                            if (dk.Id.Equals(keyword.Id))
                                            {
                                                alreadyThere = true;
                                                break;
                                            }
                                        }
                                        if (!alreadyThere)
                                        {
                                            dc.Keywords.Add(manager.BuildKeyword(keyword));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        GeneralUtils.TimedLog("ERROR: " + ex.Message);
                    }
                }
            }

        }
      public static Dynamic.Component BuildComponent(TCM.Component tcmComponent, int currentLinkLevel, BuildManager manager)
      {
          log.Debug(string.Format("start BuildComponent with component {0} ({1}) and link level {2}", tcmComponent.Title, tcmComponent.Id, currentLinkLevel));
          Dynamic.Component c = new Dynamic.Component();
          c.Title = tcmComponent.Title;
          c.Id = tcmComponent.Id.ToString();
          c.RevisionDate = tcmComponent.RevisionDate;

          c.Version = tcmComponent.Version;
          c.Schema = manager.BuildSchema(tcmComponent.Schema);
          
          c.ComponentType = (ComponentType)Enum.Parse(typeof(ComponentType), tcmComponent.ComponentType.ToString());

          if (tcmComponent.ComponentType.Equals(TCM.ComponentType.Multimedia))
          {
              Multimedia multimedia = new Multimedia();
              multimedia.MimeType = tcmComponent.BinaryContent.MultimediaType.MimeType;
              multimedia.Size = tcmComponent.BinaryContent.Size;
              multimedia.FileName = tcmComponent.BinaryContent.Filename;

              string extension = System.IO.Path.GetExtension(multimedia.FileName);
              if (string.IsNullOrEmpty(extension))
              {
                  multimedia.FileExtension = "";
              }
              else
              {
                  // remove leading dot from extension because microsoft returns this as ".gif"
                  multimedia.FileExtension = extension.Substring(1);
              }

              if (manager.BuildProperties.ResolveWidthAndHeight)
              {
                  try
                  {
                      MemoryStream memstream = new MemoryStream();
                      tcmComponent.BinaryContent.WriteToStream(memstream);
                      Image image = Image.FromStream(memstream);
                      memstream.Close();

                      multimedia.Width = image.Size.Width;
                      multimedia.Height = image.Size.Height;
                  }
                  catch (Exception e)
                  {
                      log.Warning(string.Format("error retrieving width and height of image: is component with ID {0} really an image? Error message: {1}", c.Id, e.Message));
                      multimedia.Width = 0;
                      multimedia.Height = 0;
                  }
              }
              else
              {
                  multimedia.Width = 0;
                  multimedia.Height = 0;
              }
              c.Multimedia = multimedia;
              c.Multimedia.Url = manager.PublishMultimediaComponent(c);
          }
          else
          {
              c.Multimedia = null;
          }
          c.Fields = new Dynamic.FieldSet();
          c.MetadataFields = new Dynamic.FieldSet();
          if (currentLinkLevel > 0)
          {
              if (tcmComponent.Content != null)
              {
                  TCM.Fields.ItemFields tcmFields = new TCM.Fields.ItemFields(tcmComponent.Content, tcmComponent.Schema);
                  c.Fields = manager.BuildFields(tcmFields, currentLinkLevel);
              }
              
              if (tcmComponent.Metadata != null)
              {
                  TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmComponent.Metadata, tcmComponent.MetadataSchema);
                  c.MetadataFields = manager.BuildFields(tcmMetadataFields, currentLinkLevel);
              }
          }
          if (!manager.BuildProperties.OmitContextPublications)
          {
              c.Publication = manager.BuildPublication(tcmComponent.ContextRepository);
          }
          if (!manager.BuildProperties.OmitOwningPublications)
          {
              c.OwningPublication = manager.BuildPublication(tcmComponent.OwningRepository);
          }
          if (!manager.BuildProperties.OmitFolders)
          {
              TCM.Folder folder = (TCM.Folder)tcmComponent.OrganizationalItem;
              c.Folder = manager.BuildOrganizationalItem(folder);
          }
          if (!manager.BuildProperties.OmitCategories)
          {
              c.Categories = manager.BuildCategories(tcmComponent);
          }
          manager.AddXpathToFields(c.Fields, "tcm:Content/custom:" + tcmComponent.Schema.RootElementName); 
          manager.AddXpathToFields(c.MetadataFields, "tcm:Metadata/custom:Metadata");
          return c;
      }
 private static Dynamic.TargetGroupCondition MapTargetGroupCondition(Tcm.TargetGroupCondition targetGroupCondition, BuildManager buildManager)
 {
     var newCondition = new Dynamic.TargetGroupCondition()
                            {
                                TargetGroup = BuildTargetGroup(targetGroupCondition.TargetGroup, buildManager),
                                Negate = targetGroupCondition.Negate
                            };
     return newCondition;
 }
        public Dynamic.Page GetDynamicPage(BuildManager manager)
        {
            Item item = Package.GetByName(Package.PageName);
            if (item == null)
            {
                Log.Error("no page found (is this a component template?)");
                return null;
            }
            Page tcmPage = (Page)Engine.GetObject(item.GetAsSource().GetValue("ID"));
            int linkLevels;
            if (HasPackageValue(Package, "LinkLevels"))
            {
                linkLevels = Convert.ToInt32(Package.GetValue("LinkLevels"));
            }
            else
            {
                GeneralUtils.TimedLog("no link levels configured, using default level " + this.DefaultLinkLevels);
                linkLevels = this.DefaultLinkLevels;
            }
            bool resolveWidthAndHeight;
            if (HasPackageValue(Package, "ResolveWidthAndHeight"))
            {
                resolveWidthAndHeight = Package.GetValue("ResolveWidthAndHeight").ToLower().Equals("yes");
            }
            else
            {
                GeneralUtils.TimedLog("no ResolveWidthAndHeight configured, using default value " + this.DefaultResolveWidthAndHeight);
                resolveWidthAndHeight = this.DefaultResolveWidthAndHeight;
            }
            bool publishEmptyFields;
            if (HasPackageValue(Package, "PublishEmptyFields"))
            {
                publishEmptyFields = Package.GetValue("PublishEmptyFields").ToLower().Equals("yes");

            }
            else
            {
                GeneralUtils.TimedLog("no PublishEmptyFields configured, using default value " + this.DefaultResolveWidthAndHeight);
                publishEmptyFields = this.DefaultPublishEmptyFields;
            }

            Log.Debug("found page with title " + tcmPage.Title + " and id " + tcmPage.Id);
            Log.Debug("constructing dynamic page, links are followed to level " + linkLevels + ", width and height are " + (resolveWidthAndHeight ? "" : "not ") + "resolved");
            Dynamic.Page page = manager.BuildPage(tcmPage, Engine, linkLevels, resolveWidthAndHeight,publishEmptyFields);
            return page;
        }
      public static Dynamic.Component BuildComponent(TCM.Component tcmComponent, int linkLevels, bool resolveWidthAndHeight, bool publishEmptyFields, BuildManager manager)
      {
          GeneralUtils.TimedLog("start BuildComponent");
          Dynamic.Component c = new Dynamic.Component();
          c.Title = tcmComponent.Title;
          c.Id = tcmComponent.Id.ToString();
          c.RevisionDate = tcmComponent.RevisionDate;
          GeneralUtils.TimedLog("component title = " + c.Title);

          c.Version = tcmComponent.Version;
          GeneralUtils.TimedLog("start building schema");
          c.Schema = manager.BuildSchema(tcmComponent.Schema);
          GeneralUtils.TimedLog("finished building schema");
          
          c.ComponentType = (ComponentType)Enum.Parse(typeof(ComponentType), tcmComponent.ComponentType.ToString());

          if (tcmComponent.ComponentType.Equals(TCM.ComponentType.Multimedia))
          {
              GeneralUtils.TimedLog("start building multimedia");
              Multimedia multimedia = new Multimedia();
              multimedia.MimeType = tcmComponent.BinaryContent.MultimediaType.MimeType;
              multimedia.Size = tcmComponent.BinaryContent.FileSize;
              multimedia.FileName = tcmComponent.BinaryContent.Filename;
              // remove leading dot from extension because microsoft returns this as ".gif"
              string extension = System.IO.Path.GetExtension(multimedia.FileName);
              if (string.IsNullOrEmpty(extension))
                  multimedia.FileExtension = "";
              else
                  multimedia.FileExtension = extension.Substring(1);

              if (resolveWidthAndHeight)
              {
                  try
                  {
                      MemoryStream memstream = new MemoryStream();
                      tcmComponent.BinaryContent.WriteToStream(memstream);
                      Image image = Image.FromStream(memstream);
                      memstream.Close();

                      multimedia.Width = image.Size.Width;
                      multimedia.Height = image.Size.Height;
                  }
                  catch (Exception e)
                  {
                      log.Warning("error retrieving width and height of image: " + e.Message);
                      multimedia.Width = 0;
                      multimedia.Height = 0;
                  }
              }
              else
              {
                  multimedia.Width = 0;
                  multimedia.Height = 0;
              }
              c.Multimedia = multimedia;
              GeneralUtils.TimedLog("finished building multimedia");
          }
          else
          {
              c.Multimedia = null;
          }
          c.Fields = new Dynamic.FieldSet();
          c.MetadataFields = new Dynamic.FieldSet();
          if (linkLevels > 0)
          {
              if (tcmComponent.Content != null)
              {
                  GeneralUtils.TimedLog("start retrieving tcm fields");
                  TCM.Fields.ItemFields tcmFields = new TCM.Fields.ItemFields(tcmComponent.Content, tcmComponent.Schema);
                  log.Debug("TCM fields" +tcmFields.ToXml());
                  GeneralUtils.TimedLog("finished retrieving tcm fields");
                  GeneralUtils.TimedLog("start building fields");
                  c.Fields = manager.BuildFields(tcmFields, linkLevels, resolveWidthAndHeight,publishEmptyFields);
                  GeneralUtils.TimedLog("finished building fields");
              }
              
              if (tcmComponent.Metadata != null)
              {
                  GeneralUtils.TimedLog("start retrieving tcm metadata fields");
                  TCM.Fields.ItemFields tcmMetadataFields = new TCM.Fields.ItemFields(tcmComponent.Metadata, tcmComponent.MetadataSchema);
                  GeneralUtils.TimedLog("finished retrieving tcm metadata fields");
                  GeneralUtils.TimedLog("start building metadata fields");
                  c.MetadataFields = manager.BuildFields(tcmMetadataFields, linkLevels, resolveWidthAndHeight,publishEmptyFields);
                  GeneralUtils.TimedLog("finished building metadata fields");
              }
          }
          c.Publication = manager.BuildPublication(tcmComponent.ContextRepository);
          c.OwningPublication = manager.BuildPublication(tcmComponent.OwningRepository);
          TCM.Folder folder = (TCM.Folder)tcmComponent.OrganizationalItem;
          c.Folder = manager.BuildOrganizationalItem(folder);
          c.Categories = manager.BuildCategories(tcmComponent);

          manager.AddXpathToFields(c.Fields, "tcm:Content/custom:" + tcmComponent.Schema.RootElementName); // TODO: check if the first part of the XPath is really the root element name, or simply always 'Content'
          manager.AddXpathToFields(c.MetadataFields, "tcm:Metadata/custom:Metadata");
          return c;
      }
        private Dynamic.Component GetDynamicComponent(BuildManager manager)
        {
            GeneralUtils.TimedLog("start getting component from package");
            Item item = Package.GetByName(Package.ComponentName);
            GeneralUtils.TimedLog("finished getting component from package");
            if (item == null)
            {
                Log.Error("no component found (is this a page template?)");
                return null;
            }
            Component tcmComponent = (Component)Engine.GetObject(item.GetAsSource().GetValue("ID"));
            int linkLevels;
            if (HasPackageValue(Package, "LinkLevels"))
            {
                linkLevels = Convert.ToInt32(Package.GetValue("LinkLevels"));
            }
            else
            {
                GeneralUtils.TimedLog("no link levels configured, using default level " + this.DefaultLinkLevels);
                linkLevels = this.DefaultLinkLevels;
            }
            bool resolveWidthAndHeight;
            if (HasPackageValue(Package, "ResolveWidthAndHeight"))
            {
                resolveWidthAndHeight = Package.GetValue("ResolveWidthAndHeight").ToLower().Equals("yes");
            }
            else
            {
                GeneralUtils.TimedLog("no ResolveWidthAndHeight configured, using default value " + this.DefaultResolveWidthAndHeight);
                resolveWidthAndHeight = this.DefaultResolveWidthAndHeight;
            }
            bool publishEmptyFields;
            if (HasPackageValue(Package, "PublishEmptyFields"))
            {
                publishEmptyFields = Package.GetValue("PublishEmptyFields").ToLower().Equals("yes");

            }
            else
            {
                GeneralUtils.TimedLog("no PublishEmptyFields configured, using default value " + this.DefaultResolveWidthAndHeight);
                publishEmptyFields = this.DefaultPublishEmptyFields;
            }

            GeneralUtils.TimedLog("found component with title " + tcmComponent.Title + " and id " + tcmComponent.Id);
            GeneralUtils.TimedLog("constructing dynamic component, links are followed to level " + linkLevels + ", width and height are " + (resolveWidthAndHeight ? "" : "not ") + "resolved");

            GeneralUtils.TimedLog("start building dynamic component");
            Dynamic.Component component = manager.BuildComponent(tcmComponent, linkLevels, resolveWidthAndHeight,publishEmptyFields);
            GeneralUtils.TimedLog("finished building dynamic component");
            return component;
        }
 private static KeywordCondition MapTrackingKeyCondition(TrackingKeyCondition trackingKeyCondition, BuildManager buildManager)
 {
     var newCondition = new KeywordCondition
                            {
                                Keyword = KeywordBuilder.BuildKeyword(trackingKeyCondition.Keyword, buildManager),
                                Operator = (NumericalConditionOperator)trackingKeyCondition.Operator,
                                Negate = true,
                                Value = trackingKeyCondition.Value
                            };
     return newCondition;
 }
        public static Dynamic.Field BuildField(TCM.Fields.ItemField tcmItemField, int linkLevels, bool resolveWidthAndHeight, bool publishEmptyFields, BuildManager manager)
        {
            Dynamic.Field f = new Dynamic.Field();

            if (tcmItemField == null&&publishEmptyFields)
            {
                GeneralUtils.TimedLog("item field is null");
                //throw new FieldHasNoValueException();
                f.Values.Add("");
                return f;                
            }
            else if (tcmItemField == null && !publishEmptyFields)
            {
                throw new FieldHasNoValueException();
            }
            f.Name = tcmItemField.Name;
            if (tcmItemField is TCM.Fields.XhtmlField)
            {
                TCM.Fields.XhtmlField sField = (TCM.Fields.XhtmlField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(v);
                    }                    
                }
                f.FieldType = FieldType.Xhtml;
                return f;
            }
            if (tcmItemField is TCM.Fields.MultiLineTextField)
            {
                TCM.Fields.TextField sField = (TCM.Fields.MultiLineTextField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                  //  throw new FieldHasNoValueException();
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(v);
                    }
                }
                f.FieldType = FieldType.MultiLineText;
                return f;
            }
            if (tcmItemField is TCM.Fields.TextField)
            {
                TCM.Fields.TextField sField = (TCM.Fields.TextField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                  //  throw new FieldHasNoValueException();
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    foreach (string v in sField.Values)
                    {
                        f.Values.Add(v);
                    }
                }
                f.FieldType = FieldType.Text;
                return f;
            }
            if (tcmItemField is TCM.Fields.KeywordField)
            {
                TCM.Fields.KeywordField sField = (TCM.Fields.KeywordField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                //    throw new FieldHasNoValueException();
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    // add keyword values
                    f.Keywords = new List<Keyword>();
                    // we will wrap each linked component in a ContentModel component
                    f.Values = new List<string>();
                    foreach (TCM.Keyword kw in sField.Values)
                    {
                        // todo: add binary to package, and add BinaryUrl property to the component
                        f.Values.Add(kw.Title);
                        f.Keywords.Add(manager.BuildKeyword(kw));
                    }
                    
                    KeywordFieldDefinition fieldDef = (KeywordFieldDefinition)sField.Definition;
                    f.CategoryId = fieldDef.Category.Id;
                    f.CategoryName = fieldDef.Category.Title;
                }
                f.FieldType = FieldType.Keyword;
                return f;
            }
            if (tcmItemField is TCM.Fields.NumberField)
            {
                TCM.Fields.NumberField sField = (TCM.Fields.NumberField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));

                //if (sField.Values.Count == 0)
                  //  throw new FieldHasNoValueException();
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                 else if (sField.Values.Count == 0 && !publishEmptyFields)
                 {
                     throw new FieldHasNoValueException();
                 }
                 else
                 {
                     f.NumericValues = (List<double>)sField.Values;
                     f.Values = new List<string>();
                     foreach (double d in f.NumericValues)
                     {
                         f.Values.Add(Convert.ToString(d));
                     }
                 }
                f.FieldType = FieldType.Number;
                return f;
            }
            if (tcmItemField is TCM.Fields.DateField)
            {
                TCM.Fields.DateField sField = (TCM.Fields.DateField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                //  throw new FieldHasNoValueException();

                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    //throw new FieldHasNoValueException();
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {

                    f.DateTimeValues = (List<DateTime>)sField.Values;
                    f.Values = new List<string>();
                    foreach (DateTime dt in f.DateTimeValues)
                    {
                        f.Values.Add(Convert.ToString(dt));
                    }
                }
                f.FieldType = FieldType.Date;
                return f;
            }
            if (tcmItemField is TCM.Fields.MultimediaLinkField)
            {
                TCM.Fields.MultimediaLinkField sField = (TCM.Fields.MultimediaLinkField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    f.Values.Add(tcmItemField.Name);
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {

                    // we will wrap each linked component in a ContentModel component
                    f.LinkedComponentValues = new List<Dynamic.Component>();
                    foreach (TCM.Component comp in sField.Values)
                    {
                        // todo: add binary to package, and add BinaryUrl property to the component
                        f.LinkedComponentValues.Add(manager.BuildComponent(comp, linkLevels - 1, resolveWidthAndHeight, publishEmptyFields));
                    }
                    f.Values = new List<string>();
                    foreach (Dynamic.Component c in f.LinkedComponentValues)
                    {
                        f.Values.Add(c.Id);
                    }
                }
                f.FieldType = FieldType.MultiMediaLink;
                return f;
            }
            if (tcmItemField is TCM.Fields.ComponentLinkField)
            {
                TCM.Fields.ComponentLinkField sField = (TCM.Fields.ComponentLinkField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                  //  throw new FieldHasNoValueException();
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    f.Values.Add(tcmItemField.Name);
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {
                    // we will wrap each linked component in a ContentModel component
                    f.LinkedComponentValues = new List<Dynamic.Component>();
                    foreach (TCM.Component comp in sField.Values)
                    {
                        f.LinkedComponentValues.Add(manager.BuildComponent(comp, linkLevels - 1, resolveWidthAndHeight, publishEmptyFields));
                    }
                    f.Values = new List<string>();
                    foreach (Dynamic.Component c in f.LinkedComponentValues)
                    {
                        f.Values.Add(c.Id);
                    }
                }
                f.FieldType = FieldType.ComponentLink;
                return f;
            }

            if (tcmItemField is TCM.Fields.EmbeddedSchemaField)
            {
                
                TCM.Fields.EmbeddedSchemaField sField = (TCM.Fields.EmbeddedSchemaField)tcmItemField;
                GeneralUtils.TimedLog(string.Format("item field {0} has {1} values", tcmItemField.Name, sField.Values.Count));
                //if (sField.Values.Count == 0)
                  //throw new FieldHasNoValueException();
                f.FieldType = FieldType.Embedded;
                f.EmbeddedValues = new List<Dynamic.FieldSet>();
                
                if (sField.Values.Count == 0 && publishEmptyFields)
                {
                    Dynamic.FieldSet fields = new FieldSet();
                    Dynamic.Field fe = new Dynamic.Field();
                    f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema);
                    EmbeddedSchemaFieldDefinition linksFieldDefinition = sField.Definition as EmbeddedSchemaFieldDefinition;
                    ItemFields newItemField = new ItemFields(linksFieldDefinition.EmbeddedSchema);
                    
                    for (int i = 0; i < newItemField.Count; i++)
                    {

                        if (newItemField[i] is TCM.Fields.EmbeddedSchemaField)
                        {
                            TCM.Fields.EmbeddedSchemaField innerField = (TCM.Fields.EmbeddedSchemaField)newItemField[i];
                            if (innerField.Values.Count == 0)
                            {
                                Dynamic.FieldSet fieldsinner = new FieldSet();
                                Dynamic.Field fin = new Dynamic.Field();
                                fe.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)innerField.Definition).EmbeddedSchema);
                                EmbeddedSchemaFieldDefinition inlinksFieldDefinition = innerField.Definition as EmbeddedSchemaFieldDefinition;
                                ItemFields newinItemField = new ItemFields(inlinksFieldDefinition.EmbeddedSchema);
                                for (int n = 0; n < newinItemField.Count; n++)
                                {
                                    fin.Name = newItemField[n].Name;
                                    fieldsinner.Add(newinItemField[n].Name, fin);
                                }
                                fe.EmbeddedValues.Add(fieldsinner);
                                fe.Values.Add("");
                            }
                            fe.Name = newItemField[i].Name;
                            fields.Add(newItemField[i].Name, fe);

                        }
                        else
                        {
                            Dynamic.Field fein = manager.BuildField(newItemField[i], linkLevels, resolveWidthAndHeight, publishEmptyFields);
                            fein.Values.Clear();
                            fields.Add(newItemField[i].Name, fein);
                           
                        }                       
                                                
                    }
                    f.EmbeddedValues.Add(fields);                    
                    f.Values.Add("");
                }
                else if (sField.Values.Count == 0 && !publishEmptyFields)
                {
                    throw new FieldHasNoValueException();
                }
                else
                {

                    // we will wrap each linked component in a ContentModel component
                    f.EmbeddedValues = new List<Dynamic.FieldSet>();
                    f.EmbeddedSchema = manager.BuildSchema(((EmbeddedSchemaFieldDefinition)sField.Definition).EmbeddedSchema);
                    
                    foreach (TCM.Fields.ItemFields embeddedFields in sField.Values)
                    {
                        f.EmbeddedValues.Add(manager.BuildFields(embeddedFields, linkLevels, resolveWidthAndHeight, publishEmptyFields));
                    }
                }
                
                return f;
            }

            throw new FieldTypeNotDefinedException();
        }
 public static Dynamic.Page BuildPage(TCM.Page tcmPage, Engine engine, BuildManager manager)
 {
     return BuildPage(tcmPage, engine, manager, 1, false,false);
 }
  public static Dynamic.FieldSet BuildFields(TCM.Fields.ItemFields tcmItemFields, int linkLevels, bool resolveWidthAndHeight, bool publishEmptyFields, BuildManager manager)
 {
    Dynamic.FieldSet fields = new FieldSet();
    AddFields(fields, tcmItemFields, linkLevels, resolveWidthAndHeight,publishEmptyFields, Dynamic.MergeAction.Replace, manager);
    return fields;
 }
      public static Dynamic.Component BuildComponent(TCM.Component tcmComponent, BuildManager manager)
      {
          return BuildComponent(tcmComponent, 1, false,false, manager);
		}