Exemplo n.º 1
0
        public virtual ISourceItem DeserializeItem(ISerializedItem serializedItem, bool ignoreMissingTemplateFields)
        {
            Assert.ArgumentNotNull(serializedItem, "serializedItem");

            var typed = serializedItem as SitecoreSerializedItem;

            if (typed == null)
            {
                throw new ArgumentException("Serialized item must be a SitecoreSerializedItem", "serializedItem");
            }

            try
            {
                var options = new LoadOptions {
                    DisableEvents = true, ForceUpdate = true, UseNewID = false
                };

                return(new SitecoreSourceItem(ItemSynchronization.PasteSyncItem(typed.InnerItem, options, true)));
            }
            catch (ParentItemNotFoundException ex)
            {
                string error = "Cannot load item from path '{0}'. Probable reason: parent item with ID '{1}' not found.".FormatWith(serializedItem.ProviderId, ex.ParentID);

                throw new DeserializationException(error, ex);
            }
            catch (ParentForMovedItemNotFoundException ex2)
            {
                string error = "Item from path '{0}' cannot be moved to appropriate location. Possible reason: parent item with ID '{1}' not found.".FormatWith(serializedItem.ProviderId, ex2.ParentID);

                throw new DeserializationException(error, ex2);
            }
        }
        public virtual ISourceItem Deserialize(ISerializedItem serializedItem, bool ignoreMissingTemplateFields)
        {
            if (ignoreMissingTemplateFields)
            {
                throw new NotSupportedException("The Sitecore serialization engine does not support ignoring missing fields.");
            }

            try
            {
                var options = new LoadOptions {
                    DisableEvents = true, ForceUpdate = true, UseNewID = false
                };

                return(new SitecoreSourceItem(ItemSynchronization.PasteSyncItem(((SitecoreSerializedItem)serializedItem).InnerItem, options, true)));
            }
            catch (ParentItemNotFoundException ex)
            {
                string error = "Cannot load item from path '{0}'. Probable reason: parent item with ID '{1}' not found.".FormatWith(serializedItem.ProviderId, ex.ParentID);

                throw new DeserializationException(error, ex);
            }
            catch (ParentForMovedItemNotFoundException ex2)
            {
                string error = "Item from path '{0}' cannot be moved to appropriate location. Possible reason: parent item with ID '{1}' not found.".FormatWith(serializedItem.ProviderId, ex2.ParentID);

                throw new DeserializationException(error, ex2);
            }
        }
Exemplo n.º 3
0
 private static Item CreateNewItem(Item parent, LoadOptions loadOptions, SyncItem syncItem, Sitecore.ItemWebApi.Context context)
 {
     Item itm = null;
     Assert.ArgumentNotNull(parent, "parent");
     Assert.ArgumentNotNull(loadOptions, "loadOptions");
     Assert.ArgumentNotNull(syncItem, "syncItem");
     try
     {
         itm = ItemSynchronization.PasteSyncItem(syncItem, loadOptions, true);
         if (itm != null)
         {
             if (Common.Functions.IsMediaItem(context) && context.HttpContext != null && context.HttpContext.Request.Files != null)
             {
                 MediaItem mediaItem = Common.Functions.UpdateMediaItem(itm, context.HttpContext);
                 if (mediaItem != null)
                 {
                     itm = mediaItem.InnerItem;
                 }
             }
         }
     }
     catch(Exception ex)
     {
         throw ex;
     }
     return itm;
 }
Exemplo n.º 4
0
        /// <summary>
        /// This function Serialize Sitecore.Data.Items.Item into string.
        /// Though here string is been originated from the TextWriter class.
        /// </summary>
        /// <param name="itm">Sitecore.Data.Items.Item</param>
        /// <returns>string representation of Sitecore.Data.Items.Item </returns>
        public static string SerializeIteminString(Item itm)
        {
            string data = null;

            if (itm == null)
            {
                return(data);
            }
            using (new SecurityDisabler())
            {
                Stream ss = null; TextWriter tw = null;
                try
                {
                    ss = new MemoryStream();
                    tw = new System.IO.StreamWriter(ss);
                    try
                    {
                        //Here I am using Sitecore Default Item Synchronization though i have method created in this class using which you
                        //you can do yourself also.
                        ItemSynchronization.WriteItem(itm, tw);
                        //Flushing the Memory is essential otherwise you are risking reading empty stream or partial data loss
                        tw.Flush();
                        ss.Flush();
                    }
                    catch (System.Exception ex)
                    {
                        Log.WriteError(ex.Message, ex);
                    }
                    //ss.Position = 0;
                    ss.Seek(0, SeekOrigin.Begin);
                    using (StreamReader sr = new StreamReader(ss))
                    {
                        data = sr.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteError(ex.Message, ex);
                }
                finally
                {
                    try
                    {
                        if (tw != null)
                        {
                            tw.Dispose();
                        }
                        if (ss != null)
                        {
                            ss.Close(); ss.Dispose();
                        }
                    }
                    catch { }
                }
            }
            return(data);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Moves the descendant items of a serialized parent after it has been moved or renamed.
        /// </summary>
        /// <param name="oldReference">Reference to the original path pre-move/rename</param>
        /// <param name="newItem">The newly renamed or moved parent item</param>
        /// <param name="sourceItem">The source item representing the renamed/moved item. NOTE that the path of this item is incorrect a lot of the time so we ignore it.</param>
        /// <param name="renaming">True for moving renamed children, false for moving moved children. For renames, the children already have correct new paths; for moves we have to recalculate it.</param>
        /// <remarks>
        /// This method basically gets all descendants of the source item that was moved/renamed, generates an appropriate new serialized item for it, and _if the new child item is in the predicate_ we
        /// serialize it to its new location. Finally, we delete the old children directory if it existed.
        ///
        /// Doing it this way allows handling crazy cases like moving trees of items between included and excluded locations - or even moves or renames causing SOME of the children to be ignored. Wild.
        /// </remarks>
        protected virtual void MoveDescendants(ISerializedReference oldReference, ISerializedItem newItem, ISourceItem sourceItem, bool renaming)
        {
            // remove the extension from the new item's provider ID
            string newItemReferencePath = SerializationPathUtility.GetReferenceDirectoryPath(newItem);

            // if the paths were the same, no moving occurs (this can happen when saving templates, which spuriously can report "renamed" when they are not actually any such thing)
            if (oldReference.ProviderId.Equals(newItemReferencePath, StringComparison.Ordinal))
            {
                return;
            }

            // this is for renaming an item that differs only by case from the original. Because NTFS is case-insensitive the 'new parent' exists
            // already, but it will use the old name. Not quite what we want. So we need to manually rename the folder.
            if (oldReference.ProviderId.Equals(newItemReferencePath, StringComparison.OrdinalIgnoreCase) && Directory.Exists(oldReference.ProviderId))
            {
                Directory.Move(oldReference.ProviderId, oldReference.ProviderId + "_tempunicorn");
                Directory.Move(oldReference.ProviderId + "_tempunicorn", newItemReferencePath);
            }

            var descendantItems = GetDescendants(sourceItem).Cast <SitecoreSourceItem>();

            // Go through descendant source items and serialize all that are included by the predicate
            foreach (var descendant in descendantItems)
            {
                var syncItem = ItemSynchronization.BuildSyncItem(descendant.InnerItem);

                // the newPhysicalPath will point to the OLD physical path pre-move (but for renames we actually get the new path already).
                // For moves, we re-root the path to point to the new parent item's base path to fix that before we write to disk
                string newItemPath = (renaming) ? descendant.ItemPath : descendant.ItemPath.Replace(oldReference.ItemPath, newItem.ItemPath);

                var newPhysicalPath = SerializationPathUtility.GetSerializedItemPath(_rootPath, syncItem.DatabaseName, newItemPath);

                var newSerializedItem = new SitecoreSerializedItem(syncItem, newPhysicalPath, this);

                if (!_predicate.Includes(newSerializedItem).IsIncluded)
                {
                    continue;                                                                     // if the moved child location is outside the predicate, do not re-serialize
                }
                UpdateSerializedItem(newSerializedItem);
            }

            // remove the old children folder if it exists - as long as the original name was not a case insensitive version of this item
            if (Directory.Exists(oldReference.ProviderId) && !oldReference.ProviderId.Equals(newItemReferencePath, StringComparison.OrdinalIgnoreCase))
            {
                Directory.Delete(oldReference.ProviderId, true);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// This function Serialize Sitecore.Data.Items.Item into byte array.
 /// Though here string is been originated from the TextWriter wrapped in Stream class.
 /// </summary>
 /// <param name="itm">byte[]</param>
 /// <returns>string representation of byte[] </returns>
 public static byte[] SerializeItem(Item itm)
 {
     byte[] data = null;
     if (itm == null)
     {
         return(data);
     }
     using (new SecurityDisabler())
     {
         Stream ss = null; TextWriter tw = null;
         try
         {
             ss = new MemoryStream();
             tw = new System.IO.StreamWriter(ss);
             try
             {
                 ItemSynchronization.WriteItem(itm, tw);
             }
             catch (System.Exception ex)
             {
                 Log.WriteError(ex.Message, ex);
             }
             data = new byte[ss.Length];
             ss.Read(data, 0, data.Length);
         }
         catch (Exception ex)
         {
             Log.WriteError(ex.Message, ex);
         }
         finally
         {
             try
             {
                 if (tw != null)
                 {
                     tw.Dispose();
                 }
                 if (ss != null)
                 {
                     ss.Close(); ss.Dispose();
                 }
             }
             catch { }
         }
     }
     return(data);
 }
Exemplo n.º 7
0
        public void DumpItem(object[] param)
        {
            var path = string.Format("{0}//ItemSync//{1}{2}{3}{4}{5}{6}{7}", Settings.SerializationFolder, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
            var searchStringModel = ExtractSearchQuery(param[0].ToString());
            var tempItem          = Factory.GetDatabase(param[2].ToString()).GetItem(param[1].ToString());
            int hitsCount;
            var listOfItems = tempItem.Search(searchStringModel, out hitsCount).ToList();

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            foreach (var sitecoreItem in listOfItems)
            {
                var item = sitecoreItem.GetItem();
                Assert.ArgumentNotNullOrEmpty(path, "path");
                Assert.ArgumentNotNull(item, "item");
                var itemPath = string.Format("{0}//{1}", path, item.Paths.FullPath);
                using (new SecurityDisabler())
                {
                    if (!Directory.Exists(itemPath))
                    {
                        Directory.CreateDirectory(itemPath);
                    }

                    using (var file = new StreamWriter(string.Format("{0}.item", itemPath.Replace("//", "\\")), true))
                    {
                        TextWriter writer = file;
                        try
                        {
                            ItemSynchronization.WriteItem(item, writer);
                        }
                        catch (Exception exception)
                        {
                            Log.Error(exception.Message, item);
                        }
                        finally
                        {
                            writer.Close();
                        }

                        writer.Close();
                    }
                }
            }
        }
Exemplo n.º 8
0
        public virtual void MoveSerializedItem(ISourceItem sourceItem, ISourceItem newParentItem)
        {
            Assert.ArgumentNotNull(sourceItem, "sourceItem");
            Assert.ArgumentNotNull(newParentItem, "newParentItem");

            var sitecoreSource = sourceItem as SitecoreSourceItem;
            var sitecoreParent = newParentItem as SitecoreSourceItem;

            if (sitecoreParent == null)
            {
                throw new ArgumentException("newParentItem must be a SitecoreSourceItem", "newParentItem");
            }
            if (sitecoreSource == null)
            {
                throw new ArgumentException("sourceItem must be a SitecoreSourceItem", "sourceItem");
            }

            var oldRootDirectory = new SitecoreSerializedReference(SerializationPathUtility.GetSerializedReferencePath(_rootPath, sourceItem), this);
            var oldRootItemPath  = new SitecoreSerializedReference(SerializationPathUtility.GetReferenceItemPath(oldRootDirectory), this);

            var newRootItemPath       = newParentItem.ItemPath + "/" + sourceItem.Name;
            var newRootSerializedPath = SerializationPathUtility.GetSerializedItemPath(_rootPath, newParentItem.DatabaseName, newRootItemPath);

            var syncItem = ItemSynchronization.BuildSyncItem(sitecoreSource.InnerItem);

            // update the path and parent IDs to the new location
            syncItem.ParentID = newParentItem.Id.ToString();
            syncItem.ItemPath = newRootItemPath;

            // if this occurs we're "moving" an item to the same location it started from. Which means we shouldn't do anything.
            if (oldRootDirectory.ItemPath.Equals(syncItem.ItemPath))
            {
                return;
            }

            var serializedNewItem = new SitecoreSerializedItem(syncItem, newRootSerializedPath, this);

            // write the moved sync item to its new destination
            UpdateSerializedItem(serializedNewItem);

            // move any children to the new destination (and fix their paths)
            MoveDescendants(oldRootDirectory, serializedNewItem, sourceItem, false);

            // remove the serialized item in the old location
            DeleteSerializedItem(oldRootItemPath);
        }
Exemplo n.º 9
0
        public virtual ISerializedItem SerializeItem(ISourceItem item)
        {
            Assert.ArgumentNotNull(item, "item");

            var sitecoreSourceItem = item as SitecoreSourceItem;

            var sitecoreItem = sitecoreSourceItem != null ? sitecoreSourceItem.InnerItem : Factory.GetDatabase(item.DatabaseName).GetItem(item.Id);

            Assert.IsNotNull(sitecoreItem, "Item to serialize did not exist!");

            var serializedPath = SerializationPathUtility.GetSerializedItemPath(_rootPath, item);

            var serializedItem = new SitecoreSerializedItem(ItemSynchronization.BuildSyncItem(sitecoreItem), serializedPath, this);

            UpdateSerializedItem(serializedItem);

            return(serializedItem);
        }
Exemplo n.º 10
0
        public override bool CopyItem(ItemDefinition source, ItemDefinition destination, string copyName, ID copyId, CallContext context)
        {
            Assert.ArgumentNotNull(source, "source");
            Assert.ArgumentNotNull(destination, "destination");
            Assert.ArgumentNotNullOrEmpty(copyName, "copyName");
            Assert.ArgumentNotNull(copyId, "copyId");

            // we use the Database API instead of our own so we can get a source item from any data provider
            var existingItem = Database.GetItem(source.ID);

            Assert.IsNotNull(existingItem, "Could not copy {0} because it did not exist!", source.ID);

            var destinationItem = _database.GetItem(destination.ID);

            Assert.IsNotNull(destinationItem, "Source item to copy {0} was in the Rhino provider but the destination parent {1} was not. Copying from Rhino to other providers is not supported.", source.Name, destination.Name);

            SerializedDatabase.CopyItem(ItemSynchronization.BuildSyncItem(existingItem), destination.ID, copyName, copyId);

            return(true);
        }
Exemplo n.º 11
0
        private void Parse(DirectoryInfo directoryInfo)
        {
            var fileInfos = directoryInfo.GetFiles("*.item");

            foreach (var fileInfo in fileInfos)
            {
                var streamReader = new StreamReader(fileInfo.FullName);

                var syncItem = SyncItem.ReadItem(new Tokenizer(streamReader), true);
                var options  = new LoadOptions {
                    DisableEvents = true, ForceUpdate = true, UseNewID = false
                };

                ItemSynchronization.PasteSyncItem(syncItem, options, true);
            }

            foreach (var info in directoryInfo.GetDirectories())
            {
                Parse(info);
            }
        }
Exemplo n.º 12
0
        public override bool SaveItem(ItemDefinition itemDefinition, ItemChanges changes, CallContext context)
        {
            Assert.ArgumentNotNull(itemDefinition, "itemDefinition");
            Assert.ArgumentNotNull(changes, "changes");

            var existingItem = SerializedDatabase.GetItem(itemDefinition.ID);

            if (existingItem == null)
            {
                return(false);                                  // item was not in this data provider, cede control to the next one
            }
            var savedItem = ItemSynchronization.BuildSyncItem(changes.Item);

            if (changes.Renamed)
            {
                SerializedDatabase.SaveAndRenameItem(savedItem, changes.Properties["name"].OriginalValue.ToString());
            }
            else
            {
                SerializedDatabase.SaveItem(savedItem);
            }

            return(true);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Loads a specific item from disk
        /// </summary>
        private Item DoLoadItem(string path, AdvancedLoadOptions options, out ItemLoadResult loadResult)
        {
            Assert.ArgumentNotNullOrEmpty(path, "path");
            Assert.ArgumentNotNull(options, "options");

            if (File.Exists(path))
            {
                using (TextReader fileReader = new StreamReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    LogLocalized("Loading item from path {0}.", new object[]
                    {
                        PathUtils.UnmapItemPath(path, options.Root)
                    });

                    bool disabledLocally = ItemHandler.DisabledLocally;
                    try
                    {
                        ItemHandler.DisabledLocally = true;
                        Item result = null;
                        try
                        {
                            var serializedItem = SyncItem.ReadItem(new Tokenizer(fileReader));

                            _itemsProcessed++;
                            if (_itemsProcessed % 500 == 0 && _itemsProcessed > 1)
                            {
                                options.Progress.ReportStatus(string.Format("Processed {0} items", _itemsProcessed), MessageType.Debug);
                            }

                            if (options.Preset.Exclude.MatchesTemplate(serializedItem.TemplateName))
                            {
                                options.Progress.ReportStatus(string.Format("[SKIPPED] {0}:{1} because the preset excluded its template name, but the item was on disk", serializedItem.DatabaseName, serializedItem.ItemPath), MessageType.Warning);

                                loadResult = ItemLoadResult.Skipped;
                                return(null);
                            }

                            if (options.Preset.Exclude.MatchesTemplateId(serializedItem.TemplateID))
                            {
                                options.Progress.ReportStatus(string.Format("[SKIPPED] {0}:{1} because the preset excluded its template ID, but the item was on disk", serializedItem.DatabaseName, serializedItem.ItemPath), MessageType.Warning);

                                loadResult = ItemLoadResult.Skipped;
                                return(null);
                            }

                            if (options.Preset.Exclude.MatchesId(serializedItem.ID))
                            {
                                options.Progress.ReportStatus(string.Format("[SKIPPED] {0}:{1} because the preset excluded it by ID, but the item was on disk", serializedItem.DatabaseName, serializedItem.ItemPath), MessageType.Warning);


                                loadResult = ItemLoadResult.Skipped;
                                return(null);
                            }

                            if (options.Preset.Exclude.MatchesPath(path))
                            {
                                options.Progress.ReportStatus(string.Format("[SKIPPED] {0}:{1} because the preset excluded it by path, but the item was on disk", serializedItem.DatabaseName, serializedItem.ItemPath), MessageType.Warning);

                                loadResult = ItemLoadResult.Skipped;
                                return(null);
                            }

                            var newOptions = new LoadOptions(options);

                            // in some cases we want to force an update for this item only
                            if (!options.ForceUpdate && ShouldForceUpdate(serializedItem, options.Progress))
                            {
                                options.Progress.ReportStatus(string.Format("[FORCED] {0}:{1}", serializedItem.DatabaseName, serializedItem.ItemPath), MessageType.Info);
                                newOptions.ForceUpdate = true;
                            }

                            result = ItemSynchronization.PasteSyncItem(serializedItem, newOptions, true);

                            loadResult = ItemLoadResult.Success;
                        }
                        catch (ParentItemNotFoundException ex)
                        {
                            result     = null;
                            loadResult = ItemLoadResult.Error;
                            string error =
                                "Cannot load item from path '{0}'. Probable reason: parent item with ID '{1}' not found.".FormatWith(
                                    PathUtils.UnmapItemPath(path, options.Root), ex.ParentID);

                            options.Progress.ReportStatus(error, MessageType.Error);

                            LogLocalizedError(error);
                        }
                        catch (ParentForMovedItemNotFoundException ex2)
                        {
                            result     = ex2.Item;
                            loadResult = ItemLoadResult.Error;
                            string error =
                                "Item from path '{0}' cannot be moved to appropriate location. Possible reason: parent item with ID '{1}' not found."
                                .FormatWith(PathUtils.UnmapItemPath(path, options.Root), ex2.ParentID);

                            options.Progress.ReportStatus(error, MessageType.Error);

                            LogLocalizedError(error);
                        }
                        return(result);
                    }
                    finally
                    {
                        ItemHandler.DisabledLocally = disabledLocally;
                    }
                }
            }

            loadResult = ItemLoadResult.Error;

            return(null);
        }
Exemplo n.º 14
0
        protected override string BuildPackage()
        {
            var commands = new List <ICommand>();

            foreach (var item in Items)
            {
                var syncItem = ItemSynchronization.BuildSyncItem(item);

                var contentDataItem = new ContentDataItem(string.Empty, item.Paths.ParentPath, item.Name, syncItem);

                var command = new AddItemCommand(contentDataItem);

                commands.Add(command);
            }

            var rootPath = FileUtil.MapPath("/");

            foreach (var fileName in Files)
            {
                if (FileUtil.IsFolder(fileName))
                {
                    foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories))
                    {
                        var fileInfo = new FileInfo(file);
                        if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            continue;
                        }

                        if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System)
                        {
                            continue;
                        }

                        var fileItem = new FileSystemDataItem(rootPath, Path.GetDirectoryName(file), Path.GetFileName(file));
                        var command  = new AddFileCommand(fileItem);
                        commands.Add(command);
                    }
                }
                else
                {
                    var fileItem = new FileSystemDataItem(rootPath, Path.GetDirectoryName(fileName), Path.GetFileName(fileName));
                    var command  = new AddFileCommand(fileItem);
                    commands.Add(command);
                }
            }

            var diff = new DiffInfo(commands)
            {
                Author    = Author,
                PostStep  = PostStep,
                Publisher = Publisher,
                Readme    = Readme,
                Version   = Version,
                Title     = PackageName
            };

            var directoryName = Path.GetDirectoryName(FileName) ?? string.Empty;

            directoryName = directoryName.Replace("\\", "/");
            var folderPath = FileUtil.MapPath(directoryName);

            diff.Serialize(folderPath);

            var packageFileName = FileUtil.UnmapPath(folderPath, false) + "/" + DiffInfo.OutputFileName;

            PackageGenerator.GeneratePackage(diff, packageFileName);

            return(packageFileName);
        }
 /// <summary>
 /// An item is being checked in.
 /// </summary>
 public override void ItemCheckingIn(SPItemEventProperties properties)
 {
     base.ItemCheckingIn(properties);
     ItemSynchronization.SendData(properties.AfterUrl);
 }