private bool DeleteIfLatest(string id, DateTimeOffset deleteThroughVersion, VersionedItem startingItem)
        {
            bool          deleted      = false;
            string        previousETag = null;
            VersionedItem currentItem;

            for (currentItem = startingItem;
                 !deleted && currentItem != null && currentItem.Version <= deleteThroughVersion;
                 currentItem = ReadMetadata(id, deleted))
            {
                string currentETag = currentItem.ETag;

                // Prevent an infinite loop if _innerStore erroneously returns false from TryDelete when a retry won't
                // help. (The inner store should throw rather than return false in that case.)
                if (currentETag == previousETag)
                {
                    throw new InvalidOperationException("The operation stopped making progress.");
                }

                previousETag = currentETag;
                deleted      = _innerStore.TryDelete(id, currentETag);
            }

            // Compare the condition of the loop above. The caller's version is the latest if we return for any reason
            // other than that a newer version now exists.
            // If we succesfully deleted the item or someone else did, the caller's version is the latest.
            return(deleted || currentItem == null);
        }
        private bool PersistIfLatest(string id, DateTimeOffset targetVersion, IDictionary <string, string> otherMetadata,
                                     string text, VersionedItem startingItem)
        {
            if (targetVersion == DateTimeOffset.MinValue)
            {
                // DateTimeOffset.MinValue is a sentinal value used by the implementation, so it can't be used as a
                // targetVersion.
                throw new ArgumentException("targetVersion must be greater than DateTimeOffset.MinValue.",
                                            "targetVersion");
            }

            IDictionary <string, string> combinedMetadata = Combine(otherMetadata, targetVersion);
            bool          persisted             = false;
            string        previousETag          = null;
            int           createAttempt         = 0;
            const int     MaximumCreateAttempts = 10;
            VersionedItem currentItem;

            for (currentItem = startingItem;
                 !persisted && GetVersion(currentItem) < targetVersion;
                 currentItem = ReadMetadata(id, persisted))
            {
                if (currentItem == null)
                {
                    if (createAttempt++ >= MaximumCreateAttempts)
                    {
                        // Prevent an infinite loop if _innerStore erroneously returns false from TryCreate when a retry
                        // won't help. (The inner store should throw rather than return false in that case.)
                        // Note that there's no reliable, immediate way to distinguish this error from the unlikely but
                        // possible case of a series of decreasily old items that keep getting created and then deleted.
                        throw new InvalidOperationException(
                                  "The operation gave up due to repeated failed creation attempts.");
                    }

                    previousETag = null;
                    persisted    = _innerStore.TryCreate(id, combinedMetadata, text);
                }
                else
                {
                    createAttempt = 0;
                    string currentETag = currentItem.ETag;

                    // Prevent an infinite loop if _innerStore erroneously returns false from TryUpdate when a retry
                    // won't help. (The inner store should throw rather than return false in that case.)
                    if (currentETag == previousETag)
                    {
                        throw new InvalidOperationException("The operation stopped making progress.");
                    }

                    previousETag = currentETag;
                    persisted    = _innerStore.TryUpdate(id, currentETag, combinedMetadata, text);
                }
            }

            // Compare the condition of the loop above. The caller's version is the latest if we return for any reason
            // other than that a newer version now exists.
            // If we succesfully updated the item to the target version or someone else did, the caller's version is the
            // latest.
            return(persisted || GetVersion(currentItem) == targetVersion);
        }
        public bool UpdateOrCreateIfLatest(string id, DateTimeOffset targetVersion,
                                           IDictionary <string, string> otherMetadata, string text)
        {
            VersionedItem startingItem = ReadMetadata(id);

            return(PersistIfLatest(id, targetVersion, otherMetadata, text, startingItem));
        }
        /// <summary>
        /// Removes a test items created during the test.
        /// </summary>
        /// <remarks>
        /// This never throws an exception, so it can safely be used in a finally statement (without hiding the original exception).
        /// </remarks>
        protected void Remove(IdentifiableObject item)
        {
            if (item == null)
            {
                return;
            }
            VersionedItem versionedItem = item as VersionedItem;

            if (versionedItem != null & versionedItem.IsLocked)
            {
                try
                {
                    versionedItem.UndoCheckOut();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to undo check out {0}: {1}", item, ex.Message);
                }
            }
            try
            {
                versionedItem.Delete();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to delete {0}: {1}", item, ex.Message);
            }
        }
        private static DateTimeOffset GetVersion(VersionedItem item)
        {
            if (item == null)
            {
                return(DateTimeOffset.MinValue);
            }

            return(item.Version);
        }
示例#6
0
        /// <summary>
        /// Returns the Tcm id including the version if its a <see cref="T:Tridion.ContentManager.ContentManagement.VersionedItem" />
        /// </summary>
        /// <param name="identifiableObject"><see cref="T:Tridion.ContentManager.IdentifiableObject" /></param>
        /// <returns>Tcm id including version or Tcm id</returns>
        public static String VersionedItemId(this IdentifiableObject identifiableObject)
        {
            VersionedItem versionedItem = identifiableObject as VersionedItem;

            if (versionedItem != null && versionedItem.Id.IsVersionless)
            {
                return(String.Format("{0}-v{1}", versionedItem.Id.ToString(), versionedItem.Version));
            }

            return(identifiableObject.Id.ToString());
        }
        /// <summary>
        /// Gets the approved version of the item being rendered for the current target.
        /// </summary>
        /// <param name="item">The item in question.</param>
        /// <param name="target">The target you're publishing to.</param>
        /// <returns>Either the same version or a later version if in workflow and its approval status is high enough for this target</returns>
        private VersionedItem GetApprovedVersionForTarget(VersionedItem item, PublicationTarget target)
        {
            bool isPreview = false;

            if (!item.LockType.HasFlag(LockType.InWorkflow))
            {
                return(item);
            }
            if (target == null)
            {
                isPreview = true;
            }
            if (!isPreview && target.Id == TcmUri.UriNull)
            {
                isPreview = true;
            }
            if (item is Page)
            {
                Page pageInWorkflow =
                    (Page)_engine.GetObject(new TcmUri(item.Id.ItemId, item.Id.ItemType, item.Id.PublicationId, 0));
                if (isPreview)
                {
                    return(pageInWorkflow);
                }
                int targetApprovalStatus;
                if (target.MinApprovalStatus == null)
                {
                    targetApprovalStatus = 0;
                }
                else
                {
                    targetApprovalStatus = target.MinApprovalStatus.Position;
                }

                return(pageInWorkflow.ApprovalStatus.Position >= targetApprovalStatus
                               ? pageInWorkflow
                               : item);
            }
            if (item is Component)
            {
                Component componentInWorkflow =
                    (Component)_engine.GetObject(new TcmUri(item.Id.ItemId, item.Id.ItemType, item.Id.PublicationId, 0));
                if (isPreview)
                {
                    return(componentInWorkflow);
                }
                return(componentInWorkflow.ApprovalStatus.Position >= target.MinApprovalStatus.Position
                           ? componentInWorkflow
                           : item);
            }
            return(item);
        }
示例#8
0
        /// <summary>
        /// Example of how to generate a cache key for a cache item representing resolved
        /// data that is associated with a VersionedItem. (Example of VersionedItems are: Page,
        /// Component, ComponentTemplate, PageTemplate, etc.).
        /// </summary>
        /// <param name="versionedItem">VersionItem object.</param>
        /// <param name="keyPrefix">Optional cache key prefix.</param>
        /// <param name="publicationTargetRelevant">Should cache key be associated with a PublicationTarget?</param>
        /// <returns>String representing the cache key.</returns>
        private string GenerateCacheKey(VersionedItem versionedItem, string keyPrefix = null,
                                        bool publicationTargetRelevant = false)
        {
            keyPrefix = keyPrefix ?? "versioneditem";
            var objectId  = versionedItem.Id.GetVersionlessUri().ToString();
            var versionId = versionedItem.Version.ToString(CultureInfo.InvariantCulture);

            if (!publicationTargetRelevant)
            {
                return(string.Format("{0}|{1}|{2}", keyPrefix, objectId, versionId));
            }

            var targetId = this.IsPublishing && this.Engine.PublishingContext.PublicationTarget != null
                ? this.Engine.PublishingContext.PublicationTarget.Id.ToString()
                : "preview";

            return(string.Format("{0}|{1}|{2}|{3}", keyPrefix, objectId, versionId, targetId));
        }
        public virtual string GenerateAddItemStatements(VersionedItem item)
        {
            var stringBuilder       = new StringBuilder();
            var itemTableOperations = this.ScriptItemTableOperations(item);

            if (!string.IsNullOrEmpty(itemTableOperations))
            {
                stringBuilder.AppendLine(itemTableOperations);
            }

            var sharedFieldsTableOperations = this.ScriptSharedFieldsTableOperations(item);

            if (!string.IsNullOrEmpty(sharedFieldsTableOperations))
            {
                stringBuilder.AppendLine(sharedFieldsTableOperations);
            }

            return(stringBuilder.ToString());
        }
        private string ScriptVersionedFieldsTableOperations([NotNull] VersionedItem item)
        {
            var stringBuilder = new StringBuilder();

            foreach (var field in item.Fields.Where(f => !f.TemplateField.Shared && !f.TemplateField.Unversioned))
            {
                var key = $"u{item.Database}{item.Uri.Guid.Format()}{field.FieldId.Format()}{item.Language}{item.Version}";
                if (processedItems.ContainsKey(key))
                {
                    continue;
                }

                processedItems[key] = null;
                stringBuilder.AppendLine(
                    "INSERT INTO #VersionedFields (ItemId, FieldId, Language, Version, Value, Created, Updated)");
                stringBuilder.AppendLine(
                    $"    VALUES ('{item.Uri.Guid.Format()}', '{field.FieldId.Format()}', '{item.Language}', '{item.Version}', {FormatValue(field.Value)}, GETUTCDATE(), GETUTCDATE());");
            }
            return(stringBuilder.ToString());
        }
        public override string GenerateAddItemStatements(VersionedItem item)
        {
            var stringBuilder = new StringBuilder(base.GenerateAddItemStatements(item));
            var unversionedFieldsTableOperations = ScriptUnversionedFieldsTableOperations(item);

            if (!string.IsNullOrEmpty(unversionedFieldsTableOperations))
            {
                stringBuilder.AppendLine(unversionedFieldsTableOperations);
            }
            var versionedFieldsTableOperations = ScriptVersionedFieldsTableOperations(item);

            if (!string.IsNullOrEmpty(versionedFieldsTableOperations))
            {
                stringBuilder.AppendLine(versionedFieldsTableOperations);
            }

            stringBuilder.AppendLine("GO");

            return(stringBuilder.ToString());
        }
示例#12
0
        public void WriteItem([NotNull] VersionedItem item)
        {
            var databaseFile = Path.Combine(outputPath, $"{item.Database.DatabaseName}.sql");

            if (!databaseFiles.Contains(databaseFile))
            {
                databaseFiles.Add(databaseFile);

                if (fileSystemProvider.FileExists(databaseFile))
                {
                    fileSystemProvider.DeleteFile(databaseFile);
                }

                var prependStatements = sqlGenerator.GeneratePrependStatements();
                fileSystemProvider.AppendFile(databaseFile, prependStatements);
            }

            var addItemStatements = sqlGenerator.GenerateAddItemStatements(item);

            fileSystemProvider.AppendFile(databaseFile, addItemStatements);
        }
示例#13
0
        private static void OnItemSavePre(VersionedItem item, SaveEventArgs args, EventPhases phase)
        {
            var title  = item.Title;
            var writer = new FileWriter();
            //var repo = new UserActionRepository(new SnitchDb());
            //var UserRepo = new UserRepository(new SnitchDb());
            var action = new UserAction()
            {
                Status        = item.Revision.ToString(),
                ActionDetails = item.WebDavUrl,
                ActionName    = item.Title,
                ActionTime    = item.RevisionDate
            };

            var item4 = args;
            var check = "";
            var user  = new User()
            {
                Name        = item.Session.User.Title,
                UserName    = item.Session.User.Id,
                UserActions = new List <UserAction>()
                {
                    new UserAction()
                    {
                        ActionDetails = item.WebDavUrl,
                        ActionName    = item.Title,
                        ActionTime    = DateTime.Now
                    }
                }
            };

            //repo.Add(action);
            //UserRepo.Add(user);
            Logger.Write("[OnItemSavePre];", "could not work", LoggingCategory.General);
            writer.WriteAction(user);

            args.ContextVariables.Add(title, DateTime.Now);
        }
        private bool PersistIfLatest(string id, DateTimeOffset targetVersion, IDictionary<string, string> otherMetadata,
            string text, VersionedItem startingItem)
        {
            if (targetVersion == DateTimeOffset.MinValue)
            {
                // DateTimeOffset.MinValue is a sentinal value used by the implementation, so it can't be used as a
                // targetVersion.
                throw new ArgumentException("targetVersion must be greater than DateTimeOffset.MinValue.",
                    "targetVersion");
            }

            IDictionary<string, string> combinedMetadata = Combine(otherMetadata, targetVersion);
            bool persisted = false;
            string previousETag = null;
            int createAttempt = 0;
            const int MaximumCreateAttempts = 10;
            VersionedItem currentItem;

            for (currentItem = startingItem;
                !persisted && GetVersion(currentItem) < targetVersion;
                currentItem = ReadMetadata(id, persisted))
            {
                if (currentItem == null)
                {
                    if (createAttempt++ >= MaximumCreateAttempts)
                    {
                        // Prevent an infinite loop if _innerStore erroneously returns false from TryCreate when a retry
                        // won't help. (The inner store should throw rather than return false in that case.)
                        // Note that there's no reliable, immediate way to distinguish this error from the unlikely but
                        // possible case of a series of decreasily old items that keep getting created and then deleted.
                        throw new InvalidOperationException(
                            "The operation gave up due to repeated failed creation attempts.");
                    }

                    previousETag = null;
                    persisted = _innerStore.TryCreate(id, combinedMetadata, text);
                }
                else
                {
                    createAttempt = 0;
                    string currentETag = currentItem.ETag;

                    // Prevent an infinite loop if _innerStore erroneously returns false from TryUpdate when a retry
                    // won't help. (The inner store should throw rather than return false in that case.)
                    if (currentETag == previousETag)
                    {
                        throw new InvalidOperationException("The operation stopped making progress.");
                    }

                    previousETag = currentETag;
                    persisted = _innerStore.TryUpdate(id, currentETag, combinedMetadata, text);
                }
            }

            // Compare the condition of the loop above. The caller's version is the latest if we return for any reason
            // other than that a newer version now exists.
            // If we succesfully updated the item to the target version or someone else did, the caller's version is the
            // latest.
            return persisted || GetVersion(currentItem) == targetVersion;
        }
示例#15
0
        public void Transform(Engine engine, Package package)
        {
            _log    = TemplatingLogger.GetLogger(GetType());
            _engine = engine;

            string itemName = string.Empty;

            if (package.GetByName(Package.ComponentName) != null)
            {
                itemName = Package.ComponentName;
            }
            if (package.GetByName(Package.PageName) != null)
            {
                itemName = Package.PageName;
            }

            if (string.IsNullOrEmpty(itemName))
            {
                _log.Debug("Could not determine template type, exiting");
                return;
            }

            VersionedItem item = (VersionedItem)engine.GetObject(package.GetByName(itemName));

            if (item.LockType.HasFlag(LockType.InWorkflow))
            {
                CurrentMode   mode = GetCurrentMode();
                VersionedItem w    = item.GetVersion(0);
                switch (mode)
                {
                case CurrentMode.CmePreview:
                case CurrentMode.TemplateBuilder:
                case CurrentMode.SessionPreview:
                    // return workflow object without comparing to Publication Target Minimum Approval Status
                    package.Remove(package.GetByName(itemName));
                    if (itemName.Equals(Package.ComponentName))
                    {
                        package.PushItem(Package.ComponentName, package.CreateTridionItem(ContentType.Component, w));
                    }
                    else if (itemName.Equals(Package.PageName))
                    {
                        package.PushItem(Package.PageName, package.CreateTridionItem(ContentType.Page, w));
                    }
                    break;

                case CurrentMode.Publish:
                    PublicationTarget target        = _engine.PublishingContext.PublicationTarget;
                    ApprovalStatus    targetStatus  = target.MinApprovalStatus;
                    ApprovalStatus    contentStatus = null;
                    if (w is Component)
                    {
                        contentStatus = ((Component)w).ApprovalStatus;
                    }
                    else if (w is Page)
                    {
                        contentStatus = ((Page)w).ApprovalStatus;
                    }
                    if (contentStatus == null)
                    {
                        _log.Debug("Could not determine approval status of content. Exiting.");
                        return;
                    }
                    bool mustUpdate = false;
                    if (targetStatus == null)
                    {
                        mustUpdate = true;
                    }
                    else
                    {
                        if (contentStatus.Position > targetStatus.Position)
                        {
                            mustUpdate = true;
                        }
                    }

                    if (mustUpdate)
                    {
                        package.Remove(package.GetByName(itemName));
                        if (itemName.Equals(Package.ComponentName))
                        {
                            package.PushItem(Package.ComponentName, package.CreateTridionItem(ContentType.Component, w));
                        }
                        else if (itemName.Equals(Package.PageName))
                        {
                            package.PushItem(Package.PageName, package.CreateTridionItem(ContentType.Page, w));
                        }
                    }
                    break;
                }
            }
        }
        public bool DeleteIfLatest(string id, DateTimeOffset deleteThroughVersion)
        {
            VersionedItem startingItem = ReadMetadata(id);

            return(DeleteIfLatest(id, deleteThroughVersion, startingItem));
        }
        private static DateTimeOffset GetVersion(VersionedItem item)
        {
            if (item == null)
            {
                return DateTimeOffset.MinValue;
            }

            return item.Version;
        }
        /// <summary>
        /// Gets the approved version of the item being rendered for the current target.
        /// </summary>
        /// <param name="item">The item in question.</param>
        /// <param name="target">The target you're publishing to.</param>
        /// <returns>Either the same version or a later version if in workflow and its approval status is high enough for this target</returns>
        private VersionedItem GetApprovedVersionForTarget(VersionedItem item, PublicationTarget target)
        {
            bool isPreview = false;
            if (!item.LockType.HasFlag(LockType.InWorkflow))
                return item;
            if (target == null)
            {
                isPreview = true;
            }
            if (!isPreview && target.Id == TcmUri.UriNull)
            {
                isPreview = true;
            }
            if (item is Page)
            {
                Page pageInWorkflow =
                    (Page)_engine.GetObject(new TcmUri(item.Id.ItemId, item.Id.ItemType, item.Id.PublicationId, 0));
                if (isPreview) return pageInWorkflow;
                int targetApprovalStatus;
                if (target.MinApprovalStatus == null)
                    targetApprovalStatus = 0;
                else
                    targetApprovalStatus = target.MinApprovalStatus.Position;

                return pageInWorkflow.ApprovalStatus.Position >= targetApprovalStatus
                               ? pageInWorkflow
                               : item;
            }
            if (item is Component)
            {
                Component componentInWorkflow =
                   (Component)_engine.GetObject(new TcmUri(item.Id.ItemId, item.Id.ItemType, item.Id.PublicationId, 0));
                if (isPreview) return componentInWorkflow;
                return componentInWorkflow.ApprovalStatus.Position >= target.MinApprovalStatus.Position
                           ? componentInWorkflow
                           : item;
            }
            return item;
        }
        private bool DeleteIfLatest(string id, DateTimeOffset deleteThroughVersion, VersionedItem startingItem)
        {
            bool deleted = false;
            string previousETag = null;
            VersionedItem currentItem;

            for (currentItem = startingItem;
                !deleted && currentItem != null && currentItem.Version <= deleteThroughVersion;
                currentItem = ReadMetadata(id, deleted))
            {
                string currentETag = currentItem.ETag;

                // Prevent an infinite loop if _innerStore erroneously returns false from TryDelete when a retry won't
                // help. (The inner store should throw rather than return false in that case.)
                if (currentETag == previousETag)
                {
                    throw new InvalidOperationException("The operation stopped making progress.");
                }

                previousETag = currentETag;
                deleted = _innerStore.TryDelete(id, currentETag);
            }

            // Compare the condition of the loop above. The caller's version is the latest if we return for any reason
            // other than that a newer version now exists.
            // If we succesfully deleted the item or someone else did, the caller's version is the latest.
            return deleted || currentItem == null;
        }