private static SyncVersion ReadVersion(Tokenizer reader)
        {
            SyncVersion syncVersion = new SyncVersion();
            SyncVersion result;

            try
            {
                Dictionary <string, string> dictionary = ReadHeaders(reader);
                syncVersion.Language = dictionary["language"];
                syncVersion.Version  = dictionary["version"];
                syncVersion.Revision = dictionary["revision"];
                reader.NextLine();
                while (reader.Line == "----field----")
                {
                    SyncField syncField = SyncField.ReadField(reader);
                    if (syncField != null)
                    {
                        syncVersion.Fields.Add(syncField);
                    }
                }
                result = syncVersion;
            }
            catch (Exception innerException)
            {
                throw new Exception(string.Format("Failed to load version {0} for language {1}", syncVersion.Version, syncVersion.Language), innerException);
            }
            return(result);
        }
Beispiel #2
0
 public FieldData(SyncField handler, object target, object oldValue, object index)
 {
     this.handler  = handler;
     this.target   = target;
     this.oldValue = oldValue;
     this.index    = index;
 }
        public void Process(DsItemLoadingArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            DsDbTemplate template = args.DsDbItem as DsDbTemplate;

            Assert.ArgumentNotNull(template, "Item was not a DsDbTemplate, which is required here");

            foreach (SyncItem descendantItem in template.File
                     .DeserializeAll(
                         template.SyncItem,
                         Deserializer.GetSerializationFolder(template.SerializationFolderName),
                         3)
                     .Where(i => ID.IsID(i.TemplateID) && ID.Parse(i.TemplateID) == TemplateIDs.TemplateField))
            {
                SyncField isSharedField = descendantItem.SharedFields.FirstOrDefault(f => "Shared".Equals(f.FieldName));
                SyncField typeField     = descendantItem.SharedFields.FirstOrDefault(f => "Type".Equals(f.FieldName));

                bool isShared = isSharedField != null && "1".Equals(isSharedField.FieldValue);

                template.Fields.Add(new DbField(descendantItem.Name, ID.Parse(descendantItem.ID))
                {
                    Shared = isShared,
                    Type   = typeField != null ? typeField.FieldValue : string.Empty
                });
            }
        }
 public virtual void UpdatedChangedFieldValue(Item item, SyncField field, string oldValue)
 {
     if(item.Fields[field.FieldID].Shared)
         _logger.Debug("* [U] {0}".FormatWith(field.FieldName));
     else
         _logger.Debug("* [U] {0}#{1}: {2}".FormatWith(item.Language.Name, item.Version.Number, field.FieldName));
 }
        public TemplatesResolver(
            string serializationPath,
            string[] includePaths,
            string db = "master")
        {
            Assert.ArgumentNotNullOrEmpty(serializationPath, "serializationPath");
            DirectoryInfo serializationFolder = new DirectoryInfo(serializationPath);

            Assert.IsTrue(serializationFolder.Exists, string.Format("Path '{0}' does not exist", serializationPath));

            List <SyncItem> syncItems = GetAllItems(serializationFolder, db, includePaths);

            Templates = syncItems
                        .Where(s => s.TemplateID == TemplateIDs.Template.ToString())
                        .Select(t => new TemplateItem(t, syncItems))
                        .ToList();

            Dictionary <string, TemplateItem> templateLookup = Templates.ToDictionary(t => t.SyncItem.ID, t => t);

            // resolve inheritance hierarchy
            foreach (TemplateItem templateItem in Templates)
            {
                SyncField baseTemplates = templateItem.SyncItem.SharedFields
                                          .FirstOrDefault(f => f.FieldID == FieldIDs.BaseTemplate.ToString());
                if (baseTemplates != null && !string.IsNullOrWhiteSpace(baseTemplates.FieldValue))
                {
                    ID[] baseTemplateIds             = ID.ParseArray(baseTemplates.FieldValue);
                    var  baseTemplateIdsInCurrentSet = baseTemplateIds
                                                       .Where(b => templateLookup.Keys.Contains(b.ToString()));
                    templateItem.BaseTemplates.AddRange(baseTemplateIdsInCurrentSet
                                                        .Select(b => templateLookup[b.ToString()]));

                    // resolve base templates outside of resolving set
                    foreach (ID baseTemplateId in baseTemplateIds
                             .Where(b => !templateItem.BaseTemplates.Any(bt => bt.SyncItem.ID == b.ToString())))
                    {
                        string baseTemplateFilePath = baseTemplateId.FindFilePath(serializationFolder);
                        if (string.IsNullOrWhiteSpace(baseTemplateFilePath))
                        {
                            continue;
                        }
                        FileInfo baseTemplateFile = new FileInfo(baseTemplateFilePath);
                        if (!baseTemplateFile.Exists)
                        {
                            continue;
                        }
                        SyncItem baseTemplateSyncItem = SyncItem.ReadItem(new Tokenizer(baseTemplateFile.OpenText()));
                        if (baseTemplateSyncItem == null)
                        {
                            continue;
                        }
                        if (!templateItem.BaseTemplates.Any(b => b.SyncItem.ID == baseTemplateSyncItem.ID))
                        {
                            templateItem.BaseTemplates.Add(new TemplateItem(baseTemplateSyncItem, new List <SyncItem>()));
                        }
                    }
                }
            }
        }
Beispiel #6
0
        public static SyncVersion SetFieldValue(this SyncVersion syncVersion, IFieldInfo fieldInfo, string value)
        {
            SyncField field      = syncVersion.Fields.FirstOrDefault(f => f.FieldID == fieldInfo.FieldId);
            var       fieldIndex = syncVersion.Fields.IndexOf(field);

            syncVersion.Fields[fieldIndex].FieldValue = value;
            return(syncVersion);
        }
        private void InitializeTemplates(List <SyncItem> syncItems, DirectoryInfo serializationFolder)
        {
            this.Templates = syncItems
                             .Where(s => s.TemplateID == TemplateIDs.Template.ToString())
                             .Select(t => new TemplateItem(t, syncItems))
                             .ToList();

            Dictionary <string, TemplateItem> templateLookup = this.Templates.ToDictionary(t => t.SyncItem.ID, t => t);

            // resolve inheritance hierarchy
            foreach (TemplateItem templateItem in this.Templates)
            {
                SyncField baseTemplates = templateItem.SyncItem.SharedFields
                                          .FirstOrDefault(f => f.FieldID == FieldIDs.BaseTemplate.ToString());
                if (baseTemplates != null && !string.IsNullOrWhiteSpace(baseTemplates.FieldValue))
                {
                    ID[] baseTemplateIds = baseTemplates.FieldValue
                                           .Split(new[] { '|', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                                           .Where(ID.IsID)
                                           .Select(ID.Parse)
                                           .ToArray();
                    var baseTemplateIdsInCurrentSet = baseTemplateIds
                                                      .Where(b => templateLookup.Keys.Contains(b.ToString()));
                    templateItem.BaseTemplates.AddRange(baseTemplateIdsInCurrentSet
                                                        .Select(b => templateLookup[b.ToString()]));

                    // resolve base templates outside of resolving set
                    if (serializationFolder != null)
                    {
                        foreach (ID baseTemplateId in baseTemplateIds
                                 .Where(b => !templateItem.BaseTemplates.Any(bt => bt.SyncItem.ID == b.ToString())))
                        {
                            string baseTemplateFilePath = baseTemplateId.FindFilePath(serializationFolder);
                            if (string.IsNullOrWhiteSpace(baseTemplateFilePath))
                            {
                                continue;
                            }
                            FileInfo baseTemplateFile = new FileInfo(baseTemplateFilePath);
                            if (!baseTemplateFile.Exists)
                            {
                                continue;
                            }
                            SyncItem baseTemplateSyncItem =
                                SyncItem.ReadItem(new Tokenizer(baseTemplateFile.OpenText()));
                            if (baseTemplateSyncItem == null)
                            {
                                continue;
                            }
                            if (!templateItem.BaseTemplates.Any(b => b.SyncItem.ID == baseTemplateSyncItem.ID))
                            {
                                templateItem.BaseTemplates.Add(new TemplateItem(baseTemplateSyncItem,
                                                                                new List <SyncItem>()));
                            }
                        }
                    }
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Returns the shared field value, based on the field name.
        /// </summary>
        /// <param name="name">Name of the field</param>
        /// <param name="defaultValue">If provided, will fallback to this value if no field value is available</param>
        /// <returns>The field value</returns>
        public string GetSharedFieldValue(string name, string defaultValue = null)
        {
            SyncField typeField = SyncItem.SharedFields
                                  .FirstOrDefault(f => name.Equals(f.FieldName));

            return(typeField != null && !string.IsNullOrWhiteSpace(typeField.FieldValue)
                       ? typeField.FieldValue
                       : defaultValue);
        }
Beispiel #9
0
        /// <summary>
        /// Returns the field value in the first version it can find, based on the field name.
        /// </summary>
        /// <param name="name">Name of the field</param>
        /// <param name="defaultValue">If provided, will fallback to this value if no field value is available</param>
        /// <returns>The field value</returns>
        public string GetFieldValue(string name, string defaultValue = null)
        {
            SyncField typeField = SyncItem.Versions.SelectMany(v => v.Fields)
                                  .FirstOrDefault(f => name.Equals(f.FieldName));

            return(typeField != null && !string.IsNullOrWhiteSpace(typeField.FieldValue)
                       ? typeField.FieldValue
                       : defaultValue);
        }
 public static SyncItem AddSharedField(this SyncItem syncItem, SyncField syncField)
 {
     List<SyncField> syncFields = syncItem.SharedFields.ToList();
     foreach (SyncField f in syncFields)
     {
         syncItem.AddSharedField(f.FieldID, f.FieldName, f.FieldKey, f.FieldValue, f.FieldValue != null);
     }
     return syncItem;
 }
        public static SyncItem AddSharedField(this SyncItem syncItem, SyncField syncField)
        {
            List <SyncField> syncFields = syncItem.SharedFields.ToList();

            foreach (SyncField f in syncFields)
            {
                syncItem.AddSharedField(f.FieldID, f.FieldName, f.FieldKey, f.FieldValue, f.FieldValue != null);
            }
            return(syncItem);
        }
Beispiel #12
0
 public static void SerializeField(TextWriter writer, SyncField syncField)
 {
     WriteSplitter("field", writer);
     WriteHeader("field", syncField.FieldID, writer);
     WriteHeader("name", syncField.FieldName, writer);
     WriteHeader("key", syncField.FieldKey, writer);
     WriteHeader("content-length", syncField.FieldValue.Length, writer);
     WriteNewLine(writer);
     WriteText(syncField.FieldValue, writer);
 }
Beispiel #13
0
 public virtual void UpdatedChangedFieldValue(Item item, SyncField field, string oldValue)
 {
     if (item.Fields[field.FieldID].Shared)
     {
         _logger.Debug("* [U] {0}".FormatWith(field.FieldName));
     }
     else
     {
         _logger.Debug("* [U] {0}#{1}: {2}".FormatWith(item.Language.Name, item.Version.Number, field.FieldName));
     }
 }
Beispiel #14
0
        /// <summary>
        /// Inserts field value into item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="field">The field.</param>
        /// <param name="ignoreMissingTemplateFields">Whether to ignore fields in the serialized item that do not exist on the Sitecore template</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.FieldIsMissingFromTemplateException"/>
        protected virtual void PasteSyncField(Item item, SyncField field, bool ignoreMissingTemplateFields, bool creatingNewItem)
        {
            if (!_fieldPredicate.Includes(field.FieldID).IsIncluded)
            {
                _logger.SkippedPastingIgnoredField(item, field);
                return;
            }

            Template template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);

            if (template.GetField(field.FieldID) == null)
            {
                item.Database.Engines.TemplateEngine.Reset();
                template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            }

            if (template.GetField(field.FieldID) == null)
            {
                if (!ignoreMissingTemplateFields)
                {
#if SITECORE_7
                    throw new FieldIsMissingFromTemplateException("Field '" + field.FieldName + "' (" + field.FieldID + ") does not exist in template '" + template.Name + "'", FileUtil.MakePath(item.Template.InnerItem.Database.Name, item.Template.InnerItem.Paths.FullPath), FileUtil.MakePath(item.Database.Name, item.Paths.FullPath), item.ID);
#else
                    throw new Exception("Field '" + field.FieldName + "' (" + field.FieldID + ") does not exist in template '" + template.Name + "'");
#endif
                }

                _logger.SkippedMissingTemplateField(item, field);
                return;
            }

            Field itemField = item.Fields[ID.Parse(field.FieldID)];
            if (itemField.IsBlobField && !ID.IsID(field.FieldValue))
            {
                byte[] buffer = System.Convert.FromBase64String(field.FieldValue);
                itemField.SetBlobStream(new MemoryStream(buffer, false));

                if (!creatingNewItem)
                {
                    _logger.WroteBlobStream(item, field);
                }
            }
            else if (!field.FieldValue.Equals(itemField.Value))
            {
                var oldValue = itemField.Value;
                itemField.SetValue(field.FieldValue, true);
                if (!creatingNewItem)
                {
                    _logger.UpdatedChangedFieldValue(item, field, oldValue);
                }
            }
        }
Beispiel #15
0
        public static ID GetSitecoreId(this SyncField item)
        {
            Assert.ArgumentNotNull(item, "item");

            ID result;

            if (!ID.TryParse(item.FieldID, out result))
            {
                throw new ArgumentOutOfRangeException("item", "SyncField did not have a parseable FieldID!");
            }

            return(result);
        }
        public static SyncItem SetFieldValue(this SyncItem syncItem, FileTemplateFields fieldId, string value)
        {
            int fieldIndex = syncItem.SharedFields.ToList().FindIndex(field => field.FieldID == fieldId.FieldId);
            if (fieldIndex < 0)
            {
                SyncField filed = new SyncField
                {
                    FieldID = fieldId.FieldId,
                    FieldName = fieldId.Name,
                    FieldKey = fieldId.Key,
                    FieldValue = value
                };
                syncItem.SharedFields.Add(filed);
            }
            else
            {
                syncItem.SharedFields[fieldIndex].FieldValue = value;
            }

            return syncItem;
        }
        public static SyncItem SetFieldValue(this SyncItem syncItem, FileTemplateFields fieldId, string value)
        {
            int fieldIndex = syncItem.SharedFields.ToList().FindIndex(field => field.FieldID == fieldId.FieldId);

            if (fieldIndex < 0)
            {
                SyncField filed = new SyncField
                {
                    FieldID    = fieldId.FieldId,
                    FieldName  = fieldId.Name,
                    FieldKey   = fieldId.Key,
                    FieldValue = value
                };
                syncItem.SharedFields.Add(filed);
            }
            else
            {
                syncItem.SharedFields[fieldIndex].FieldValue = value;
            }

            return(syncItem);
        }
Beispiel #18
0
 public virtual void WroteBlobStream(Item item, SyncField field)
 {
 }
Beispiel #19
0
 public virtual void SkippedMissingTemplateField(Item item, SyncField field)
 {
     _logger.Warn("* Skipped field {0} because it did not exist on template {1}.".FormatWith(field.FieldName, item.TemplateName));
 }
 public virtual void WroteBlobStream(Item item, SyncField field)
 {
 }
        private static SyncField ReadField(Tokenizer reader)
        {
            var field = new SyncField();
            var dictionary = SerializationUtils.ReadHeaders(reader);
            field.FieldID = dictionary["field"];
            field.FieldName = dictionary["name"];
            field.FieldKey = dictionary["key"];

            var readLines = new List<string>();

            while (true)
            {
                var line = reader.NextLine();

                if (EofFound(line) || FieldStartFound(line)) break;

                readLines.Add(line);
            }

            if (((reader.Line == null) || reader.Line.EndsWith("----", StringComparison.InvariantCulture)) || (reader.Line.Length == 0))
            {
                if (readLines.All(x => x == ""))
                {
                    field.FieldValue = "";
                }
                else
                {
                    var builder = new StringBuilder();

                    for (var index = 0; index < readLines.Count; index++)
                    {
                        var readLine = readLines[index];
                        if (index == readLines.Count - 1)
                        {
                            builder.Append(readLine); 
                        }
                        else
                        {
                            builder.AppendLine(readLine);                             
                        }
                    }

                    field.FieldValue = builder.ToString();
                }

                return field;
            }

            throw new Exception(
                string.Format(
                        "Length of field content does not match the content-length attribute. Field name: {0}, field id: {1}", 
                        field.FieldName, field.FieldID));
        }
 public virtual void SkippedMissingTemplateField(Item item, SyncField field)
 {
     _logger.Warn("* Skipped field {0} because it did not exist on template {1}.".FormatWith(field.FieldName, item.TemplateName));
 }
Beispiel #23
0
 public SyncFieldWrapper(SyncField field)
 {
     _field = field;
 }
Beispiel #24
0
 public BufferData(SyncField field, object actualValue, object toSend)
 {
     this.field       = field;
     this.actualValue = actualValue;
     this.toSend      = toSend;
 }
Beispiel #25
0
 public virtual void SkippedPastingIgnoredField(Item item, SyncField field)
 {
 }
        /// <summary>
        /// Inserts field value into item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="field">The field.</param>
        /// <param name="ignoreMissingTemplateFields">Whether to ignore fields in the serialized item that do not exist on the Sitecore template</param>
        /// <param name="creatingNewItem">Whether the item under update is new or not (controls logging verbosity)</param>
        /// <exception cref="T:Sitecore.Data.Serialization.Exceptions.FieldIsMissingFromTemplateException"/>
        protected virtual void PasteSyncField(Item item, SyncField field, bool ignoreMissingTemplateFields, bool creatingNewItem)
        {
            if (!_fieldPredicate.Includes(field.FieldID).IsIncluded)
            {
                _logger.SkippedPastingIgnoredField(item, field);
                return;
            }

            Template template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            if (template.GetField(field.FieldID) == null)
            {
                item.Database.Engines.TemplateEngine.Reset();
                template = AssertTemplate(item.Database, item.TemplateID, item.Paths.Path);
            }

            if (template.GetField(field.FieldID) == null)
            {
                if (!ignoreMissingTemplateFields)
                {
            #if SITECORE_7
                    throw new FieldIsMissingFromTemplateException("Field '" + field.FieldName + "' (" + field.FieldID + ") does not exist in template '" + template.Name + "'", FileUtil.MakePath(item.Template.InnerItem.Database.Name, item.Template.InnerItem.Paths.FullPath), FileUtil.MakePath(item.Database.Name, item.Paths.FullPath), item.ID);
            #else
                    throw new Exception("Field '" + field.FieldName + "' (" + field.FieldID + ") does not exist in template '" + template.Name + "'");
            #endif
                }

                _logger.SkippedMissingTemplateField(item, field);
                return;
            }

            Field itemField = item.Fields[ID.Parse(field.FieldID)];
            if (itemField.IsBlobField && !ID.IsID(field.FieldValue))
            {
                byte[] buffer = System.Convert.FromBase64String(field.FieldValue);
                itemField.SetBlobStream(new MemoryStream(buffer, false));

                if (!creatingNewItem)
                    _logger.WroteBlobStream(item, field);
            }
            else if (!field.FieldValue.Equals(itemField.Value))
            {
                var oldValue = itemField.Value;
                itemField.SetValue(field.FieldValue, true);
                if (!creatingNewItem)
                    _logger.UpdatedChangedFieldValue(item, field, oldValue);
            }
        }
Beispiel #27
0
 private void OnInputFieldChanged(SyncField <string> msg)
 {
     metagen_comp.StartTask(async() => await client.Send(msg.Value));
 }
        private static SyncItem ReadItem(Tokenizer reader, bool assertVersion)
        {
            SyncItem syncItem = null;

            while (reader.Line != null && reader.Line.Length == 0)
            {
                reader.NextLine();
            }
            if (reader.Line == null || reader.Line != "----item----")
            {
                throw new Exception("Format error: serialized stream does not start with ----item----");
            }
            syncItem = new SyncItem();
            Dictionary <string, string> dictionary = ReadHeaders(reader);

            syncItem.ID = dictionary["id"];
            int num;

            if (assertVersion && !string.IsNullOrEmpty(dictionary["version"]) && int.TryParse(dictionary["version"], out num) && SyncItem.FormatVersion < num)
            {
                throw new Exception(string.Concat(new object[]
                {
                    "The file was generated using a newer version of Serialization. (",
                    SyncItem.FormatVersion,
                    " < ",
                    num,
                    ")"
                }));
            }
            syncItem.ItemPath = dictionary["path"];
            SyncItem result;

            try
            {
                syncItem.DatabaseName = dictionary["database"];
                syncItem.ParentID     = dictionary["parent"];
                syncItem.Name         = dictionary["name"];
                syncItem.BranchId     = dictionary["master"];
                syncItem.TemplateID   = dictionary["template"];
                syncItem.TemplateName = dictionary["templatekey"];
                reader.NextLine();
                while (reader.Line == "----field----")
                {
                    SyncField syncField = SyncField.ReadField(reader);
                    if (syncField != null)
                    {
                        syncItem.SharedFields.Add(syncField);
                    }
                }
                while (reader.Line == "----version----")
                {
                    SyncVersion syncVersion = ReadVersion(reader);
                    if (syncVersion != null)
                    {
                        syncItem.Versions.Add(syncVersion);
                    }
                }
                result = syncItem;
            }
            catch (Exception innerException)
            {
                throw new Exception("Error reading item: " + syncItem.ItemPath, innerException);
            }
            return(result);
        }
 public SyncFieldWrapper(SyncField field)
 {
     _field = field;
 }
 public virtual void SkippedPastingIgnoredField(Item item, SyncField field)
 {
 }