/// <summary>
        /// Determine if current item should be excluded from publishing or not.
        /// If it should be excluded, the current pipeline is aborted.
        /// Override this method for any custom implementation logic.
        /// </summary>
        /// <param name="context">context of the item being published</param>
        protected virtual void ProcessPublishItem(PublishItemContext context)
        {
            try
            {
                Assert.ArgumentNotNull((object)context, "context");
                Assert.ArgumentNotNull((object)context.PublishOptions, "context.PublishOptions");

                if (context.VersionToPublish == null)
                {
                    // Case 1: handled case where deleted items also should get excluded from publishing
                    // Case 2: handled case where shared fields of an item should be excluded from publishing
                    if (context.Action == PublishAction.DeleteTargetItem && context.PublishOptions != null)
                    {
                        Item deletedItem = context.PublishOptions.TargetDatabase.GetItem(context.ItemId);
                        if (deletedItem == null)
                            return;

                        context.VersionToPublish = deletedItem;
                    }
                    else if (context.Action == PublishAction.PublishSharedFields && context.PublishOptions != null)
                    {
                        Item sharedItem = context.PublishOptions.SourceDatabase.GetItem(context.ItemId);
                        if (sharedItem == null)
                            return;

                        context.VersionToPublish = sharedItem;
                    }
                    else
                        return;
                }

                PublishingLog.Debug(string.Format("Sitecore.PublishExclusions : SkipExcludedItems processing item - '{0}'", context.VersionToPublish.Paths.Path));

                // Check if item comes under any one of exluded nodes and also not under included nodes then abort pipeline.
                if (PublishExclusionsContext.Current.IsExcludedForCurrentPublish(context))
                {
                    PublishingLog.Debug(string.Format("Sitecore.PublishExclusions : SkipExcludedItems skipping item - '{0}'", context.VersionToPublish.Paths.Path));

                    string explanation = string.Format(ExplanationTextFormat, context.VersionToPublish.Paths.Path);
                    context.Result = new PublishItemResult(PublishOperation.Skipped, PublishChildAction.Skip, explanation, PublishExclusionsContext.Current.ReturnItemsToPublishQueue);
                    context.AbortPipeline();
                }

                //if publish action item is shared fields and version to publish has been manually set to an item then set it back to null
                if (context.Action == PublishAction.PublishSharedFields && context.VersionToPublish != null)
                    context.VersionToPublish = null;
            }
            catch (Exception ex)
            {
                PublishingLog.Error("Sitecore.PublishExclusions : SkipExcludedItems publish item processor - error in skipping excluded items", ex);
            }
        }
Ejemplo n.º 2
0
        public void PreCalculatePublishOperation(object sender, EventArgs args)
        {
            PublishItemContext argContext = ((ItemProcessingEventArgs)args).Context;
            ID itemId = argContext.ItemId;

            var publishItemTracking = Sitecore.Context.Items[PublishItemTracking.Name] as PublishItemTracking;

            if (publishItemTracking != null)
            {
                Item sourceItem      = Factory.GetDatabase(publishItemTracking.SourceDB).GetItem(itemId);
                Item destinationItem = Factory.GetDatabase(publishItemTracking.DestinationDB).GetItem(itemId);
                PublishOperation.PublishOperationEnum operation =
                    destinationItem == null
                        ? PublishOperation.PublishOperationEnum.Create
                        :
                    (sourceItem == null || sourceItem.Publishing.NeverPublish)
                            ?
                    PublishOperation.PublishOperationEnum.Delete
                            :
                    PublishOperation.PublishOperationEnum.Update;

                if (argContext.PublishContext.CustomData[itemId.ToString()] == null)
                {
                    argContext.PublishContext.CustomData.Add(itemId.ToString(), operation);
                }
                else
                {
                    argContext.PublishContext.CustomData[itemId.ToString()] = operation;
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Clear IsSharepointItem field for published items and enable SharepointProvider.
        /// </summary>
        /// <param name="args">The args   .</param>
        public void Clear(PublishItemContext args)
        {
            Assert.ArgumentNotNull((object)args, nameof(args));
            if (args.VersionToPublish != null)
            {
                Item targetItem = args.PublishHelper.GetTargetItem(args.VersionToPublish.ID);
                if (targetItem != null && targetItem.Fields.FirstOrDefault <Field>((Func <Field, bool>)(field => field.ID == Sitecore.Sharepoint.Common.FieldIDs.IsIntegrationItem)) != null)
                {
                    using (new EditContext(targetItem, false, false))
                        new CheckboxField(targetItem.Fields[Sitecore.Sharepoint.Common.FieldIDs.IsIntegrationItem]).Checked = false;
                }
            }
            if (args.CustomData["SharepointDisabler"] == null)
            {
                return;
            }
            IntegrationDisabler integrationDisabler = args.CustomData["SharepointDisabler"] as IntegrationDisabler;

            if (integrationDisabler == null)
            {
                return;
            }
            args.CustomData["SharepointDisabler"] = (object)null;
            integrationDisabler.Dispose();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Clear IsSharepointItem field for published items and enable SharepointProvider.
        /// </summary>
        /// <param name="args">The args   .</param>
        public void Clear([NotNull] PublishItemContext args)
        {
            Assert.ArgumentNotNull(args, "args");

            if (args.VersionToPublish != null)
            {
                var item = args.PublishHelper.GetTargetItem(args.VersionToPublish.ID);
                if (item != null && item.Fields.FirstOrDefault(field => field.ID == SharepointFieldIDs.IsIntegrationItem) != null)
                {
                    using (new EditContext(item))
                    {
                        new CheckboxField(item.Fields[SharepointFieldIDs.IsIntegrationItem]).Checked = false;
                    }
                }
            }

            if (args.CustomData["SharepointDisabler"] != null)
            {
                var disabler = args.CustomData["SharepointDisabler"] as IntegrationDisabler;
                if (disabler != null)
                {
                    args.CustomData["SharepointDisabler"] = null;
                    disabler.Dispose();
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Determine if current item should be excluded from publishing or not.
        /// If it should be excluded, the current pipeline is aborted.
        /// Override this method for any custom implementation logic.
        /// </summary>
        /// <param name="context">context of the item being published</param>
        protected virtual void ProcessPublishItem(PublishItemContext context)
        {
            try
            {
                Assert.ArgumentNotNull((object)context, "context");
                Assert.ArgumentNotNull((object)context.PublishOptions, "context.PublishOptions");

                if (context.VersionToPublish == null)
                {
                    // Case 1: handled case where deleted items also should get excluded from publishing
                    // Case 2: handled case where shared fields of an item should be excluded from publishing
                    if (context.Action == PublishAction.DeleteTargetItem && context.PublishOptions != null)
                    {
                        Item deletedItem = context.PublishOptions.TargetDatabase.GetItem(context.ItemId);
                        if (deletedItem == null)
                        {
                            return;
                        }

                        context.VersionToPublish = deletedItem;
                    }
                    else if (context.Action == PublishAction.PublishSharedFields && context.PublishOptions != null)
                    {
                        Item sharedItem = context.PublishOptions.SourceDatabase.GetItem(context.ItemId);
                        if (sharedItem == null)
                        {
                            return;
                        }

                        context.VersionToPublish = sharedItem;
                    }
                    else
                    {
                        return;
                    }
                }

                PublishingLog.Debug(string.Format("Sitecore.PublishExclusions : SkipExcludedItems processing item - '{0}'", context.VersionToPublish.Paths.Path));

                // Check if item comes under any one of exluded nodes and also not under included nodes then abort pipeline.
                if (PublishExclusionsContext.Current.IsExcludedForCurrentPublish(context))
                {
                    PublishingLog.Debug(string.Format("Sitecore.PublishExclusions : SkipExcludedItems skipping item - '{0}'", context.VersionToPublish.Paths.Path));

                    string explanation = string.Format(ExplanationTextFormat, context.VersionToPublish.Paths.Path);
                    context.Result = new PublishItemResult(PublishOperation.Skipped, PublishChildAction.Skip, explanation, PublishExclusionsContext.Current.ReturnItemsToPublishQueue);
                    context.AbortPipeline();
                }

                //if publish action item is shared fields and version to publish has been manually set to an item then set it back to null
                if (context.Action == PublishAction.PublishSharedFields && context.VersionToPublish != null)
                {
                    context.VersionToPublish = null;
                }
            }
            catch (Exception ex)
            {
                PublishingLog.Error("Sitecore.PublishExclusions : SkipExcludedItems publish item processor - error in skipping excluded items", ex);
            }
        }
Ejemplo n.º 6
0
        protected override List <Item> GetItemReferences(PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, nameof(context));
            var objList = new List <Item>();

            if (context.PublishOptions.Mode != PublishMode.SingleItem)
            {
                return(objList);
            }
            switch (context.Action)
            {
            case PublishAction.PublishSharedFields:
                var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
                if (sourceItem == null)
                {
                    return(objList);
                }
                objList.AddRange(this.GetReferences(sourceItem, true, new HashSet <ID>()));
                break;

            case PublishAction.PublishVersion:
                var versionToPublish = context.VersionToPublish;
                if (versionToPublish == null)
                {
                    return(objList);
                }
                objList.AddRange(this.GetReferences(versionToPublish, false, new HashSet <ID>()));
                break;

            default:
                return(objList);
            }
            return(objList);
        }
Ejemplo n.º 7
0
        public override void Process(PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, "context");
            List <Item> itemReferences = GetItemReferences(context); // this line calls the method from your custom class

            RegisterReferences(itemReferences, context);             // this line registers the references to the related items.
        }
Ejemplo n.º 8
0
        public override void Process(PublishItemContext context)
        {
            if (context == null || context.Aborted)
            {
                return;
            }

            // Only run if SPRK is enabled in config
            if (!_enabled)
            {
                return;
            }

            string itemID    = context.ItemId.ToString();
            string mode      = context.PublishOptions.Mode.ToString();
            string operation = context.Result.Operation.ToString();
            string user      = context.User.Name;
            string sourceDB  = context.PublishOptions.SourceDatabase.Name;
            string targetDB  = context.PublishOptions.TargetDatabase.Name;
            string datetime  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string logEntry = $"{itemID}|{mode}|{operation}|{user}|{sourceDB}|{targetDB}|{datetime}{Environment.NewLine}";

            try
            {
                string filePath = Path.Combine(_logFolder, String.Format("{0}.{1}.txt", _logFilePrefix, DateTime.Today.ToString("yyyyMMdd")));
                filePath = FileUtil.MapPath(filePath);

                File.AppendAllText(filePath, logEntry);
            }
            catch (Exception exc)
            {
                Sitecore.Diagnostics.Log.Error($"[SPRK] Exception logging publish for item ID {itemID}. Exception: {exc.ToString()}", this);
            }
        }
        /// <summary>
        /// Processes the specified args.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Process([NotNull] PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            UpdateContextStatistics(context);
            UpdateJobStatistics(context);
            TraceInformation(context);
        }
Ejemplo n.º 10
0
        public override void Process(PublishItemContext publishItemContext)
        {
            Assert.ArgumentNotNull(publishItemContext, "publishItemContext");
            Assert.ArgumentNotNull(
                publishItemContext.Result,
                "publishItemContext.Result");

            // if publishing did not touch this item in the target database
            // then there is no need to track this item. If caches need
            // to be cleared completely, there is no need to track any items.
            if (publishItemContext.Result.Operation == PublishOperation.Skipped ||
                publishItemContext.Action == PublishAction.None ||
                ClearSiteOutputCaches.OutputCacheClearingOptions.ClearAllOutputCachesCompletely)
            {
                return;
            }

            // output caches may need to be cleared or scavenged
            ClearSiteOutputCaches.OutputCacheClearingOptions.PublishedSomething
                = true;

            // the item that was published
            Item item = publishItemContext.PublishOptions.SourceDatabase.GetItem(
                publishItemContext.ItemId);

            // the item must have been deleted so we can't get information about it;
            // all caches need to be completely cleared.
            if (item == null)
            {
                Log.Info(this + " : " + publishItemContext.ItemId + " does not exist : set ClearAllOutputCachesCompletely and return", this);
                ClearSiteOutputCaches.OutputCacheClearingOptions.ClearAllOutputCachesCompletely
                    = true;
                return;
            }

            // the sites for which the item is relevant.
            string[] siteNames = this.GetSiteNamesForItem(item);

            // if no sites are relevant, assume all sites are relevant.
            if (siteNames == null || siteNames.Length < 1)
            {
                Log.Info(this + " : no sites for " + item.Paths.FullPath + " : set ClearAllOutputCaches and return", this);
                ClearSiteOutputCaches.OutputCacheClearingOptions.ClearAllOutputCachesCompletely
                    = true;
                return;
            }

            // ClearCacheForSite() will prevent the same entry from appearing twice
            foreach (string siteName in siteNames)
            {
                Log.Info(this + " : site for " + item.Paths.FullPath + " : " + siteName, this);
                ClearSiteOutputCaches.OutputCacheClearingOptions.ClearCacheForSite(
                    siteName);
            }
        }
        protected virtual Dictionary <ID, bool> GetAdvancedPublishingSettings(PublishItemContext context)
        {
            var deepRelatedTemplates = new Dictionary <ID, bool>();

            var db = context.VersionToPublish?.Database;

            if (db != null)
            {
                var langaugeCode = Sitecore.Configuration.Settings.GetSetting("AdvancedPublishingOptions.GlobalSettings.LanguageIsoCode");

                Language lang;

                if (Language.TryParse(langaugeCode, out lang))
                {
                    using (new LanguageSwitcher(lang))
                    {
                        var publishingDataFolderItemId = Sitecore.Configuration.Settings.GetSetting("AdvancedPublishingOptions.GlobalSettings.ItemId");
                        var publishingDataFolder       = db.GetItem(publishingDataFolderItemId);

                        if (publishingDataFolder != null)
                        {
                            if (publishingDataFolder != null)
                            {
                                var deepRelatedSettingsItems = publishingDataFolder.Children.Where(it => it.InheritsFrom(DeepRelatedItemDataItem.TemplateId))
                                                               .Select(it => new DeepRelatedItemDataItem(it));

                                deepRelatedTemplates = (from i in deepRelatedSettingsItems
                                                        // Ignore invalid template selections
                                                        where i.TemplateField.TargetID != (ID)null
                                                        where i.TemplateField.TargetID.Guid != Guid.Empty
                                                        group i by i.TemplateField.TargetID into iGroup
                                                        select new
                                {
                                    ItemID = iGroup.Key,
                                    // If the same template exists more than once, any Checked will apply
                                    Checked = iGroup.Any(ig => ig.SubitemsField.Checked)
                                }).ToDictionary(i => i.ItemID, i => i.Checked);
                            }
                        }
                        else
                        {
                            Sitecore.Diagnostics.Log.Error("AdvancedPublishingOptions: Global settings item could not be found", this);
                        }
                    }
                }
                else
                {
                    Sitecore.Diagnostics.Log.Error("AdvancedPublishingOptions: AdvancedPublishingOptions.GlobalSettings.LanguageIsoCode could not be parsed", this);
                }
            }

            return(deepRelatedTemplates);
        }
Ejemplo n.º 12
0
        public override void Process(PublishItemContext context)
        {
            if (context == null || context.Aborted)
            {
                return;
            }

            try
            {
                if (context.PublishContext.CustomData.ContainsKey("SPRKEnabled"))
                {
                    int?logKey = (int?)context.PublishContext.CustomData["SPRKKey"];
                    if (!logKey.HasValue)
                    {
                        Sitecore.Diagnostics.Log.Error($"[SPRK] 'SPRKKey' key not found in PublishContext.CustomData. Cannot log publishing for item ID {context.ItemId.ToString()}.", this);
                        return;
                    }

                    try
                    {
                        _logger.AddToLog(
                            logKey.Value,
                            context.ItemId.ToString(),
                            context.PublishOptions.Mode.ToString(),
                            context.Result.Operation.ToString(),
                            context.User.Name,
                            context.PublishOptions.SourceDatabase.Name,
                            context.PublishOptions.TargetDatabase.Name,
                            DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                            );
                    }
                    catch (Exception exc)
                    {
                        Sitecore.Diagnostics.Log.Error($"[SPRK] Exception logging publish for item ID {context.ItemId.ToString()}. Exception: {exc.ToString()}", this);
                    }

                    try
                    {
                        _logger.HandleLogFlush(logKey.Value);
                    }
                    catch (Exception exc)
                    {
                        Sitecore.Diagnostics.Log.Error($"[SPRK] Exception during log flush: {exc.ToString()}", this);
                    }
                }
            }
            catch (Exception exc)
            {
                Sitecore.Diagnostics.Log.Error($"[SPRK] Exception during PublishLoggerProcessor.Process() method. Exception: {exc.ToString()}", this);
            }
        }
        public override void Process(PublishItemContext context)
        {
            if (context == null)
            {
                return;
            }

            if (context.Aborted)
            {
                return;
            }

            var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);

            if (sourceItem == null)
            {
                return;
            }

            if (!sourceItem.Paths.IsContentItem)
            {
                return;
            }
            sourceItem.Fields.ReadAll();

            var validators = ValidationHelpers.GetValidatorCollection(sourceItem);

            if (validators == null)
            {
                return;
            }
            var invalidFields = ValidationHelpers.AreFieldsValid(validators).Select(i => sourceItem.Database.GetItem(i).Name).ToList();

            if (!invalidFields.Any())
            {
                return;
            }
            if (invalidFields.Any())
            {
                Log.Info(string.Format(
                             "{0}: Item '{1}' in '{4}' will not be publised to database '{2}' because '{3}' field values are not valid",
                             GetType().Name,
                             AuditFormatter.FormatItem(sourceItem),
                             context.PublishContext.PublishOptions.TargetDatabase,
                             string.Join(", ", invalidFields), sourceItem.Language.Name),
                         this);
            }

            context.Action = PublishAction.Skip;
        }
Ejemplo n.º 14
0
        public override void Process(PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            if (!SuccessfulPublishState(context))
                return;

            Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
            if (sourceItem.Fields[FieldNames.Refreshed] == null)
                return;

            var args = new RefreshItemArgs();
            args.Item = sourceItem;
            CorePipeline.Run(PipelineNames.RefreshItem, args);
        }
Ejemplo n.º 15
0
        public void PostCalculatePublishOperation(object sender, EventArgs args)
        {
            PublishItemContext argContext = ((ItemProcessedEventArgs)args).Context;

            var publishItemTracking = Sitecore.Context.Items[PublishItemTracking.Name] as PublishItemTracking;

            if (publishItemTracking != null)
            {
                ID     itemId    = argContext.ItemId;
                object operation = argContext.PublishContext.CustomData[itemId.ToString()];
                if (operation != null)
                {
                    var  createUpdateOrDeleteOperation = (PublishOperation.PublishOperationEnum)operation;
                    Item item = Factory.GetDatabase(publishItemTracking.DestinationDB).GetItem(itemId);

                    if (createUpdateOrDeleteOperation == PublishOperation.PublishOperationEnum.Create)
                    {
                        Item parent = item?.Parent;
                        if (parent != null)
                        {
                            foreach (Item child in parent.Children)
                            {
                                if (!publishItemTracking.PublishedItems.ContainsKey(child.ID.Guid))
                                {
                                    publishItemTracking.PublishedItems.Add(child.ID.Guid,
                                                                           createUpdateOrDeleteOperation);
                                }
                                else
                                {
                                    publishItemTracking.PublishedItems[child.ID.Guid] = createUpdateOrDeleteOperation;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!publishItemTracking.PublishedItems.ContainsKey(itemId.Guid))
                        {
                            publishItemTracking.PublishedItems.Add(itemId.Guid, createUpdateOrDeleteOperation);
                        }
                        else
                        {
                            publishItemTracking.PublishedItems[itemId.Guid] = createUpdateOrDeleteOperation;
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        protected void OnItemPublished(object sender, EventArgs args)
        {
            Assert.IsTrue(args != null, "args != null");
            if (args != null && args is ItemProcessedEventArgs && AuditItemPublished)
            {
                using (new SecurityDisabler())
                {
                    PublishItemContext context = (args as ItemProcessedEventArgs).Context;

                    if (context.Result.Operation == PublishOperation.Skipped)
                    {
                        try
                        {
                            // If we skipped publishing this item, we only care about logging why if we deliberately tried to republish this item...
                            if (!context.PublishOptions.CompareRevisions && context.PublishOptions.RootItem.ID == context.ItemId)
                            {
                                if (context.PublishHelper.SourceItemExists(context.ItemId))
                                {
                                    Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
                                    Log(string.Format("PUBLISH [{0}]: {1}", context.Result.Operation, AuditFormatter.FormatItem(sourceItem)));
                                }
                                else
                                {
                                    Log(string.Format("PUBLISH [{0}]: {1}", context.Result.Operation, context.ItemId));
                                }
                                Log(string.Format("** {0}", context.Result.Explanation));
                            }
                        }
                        catch (Exception)
                        {
                            // We don't need to log - we were skipping this item from getting published anyway
                        }
                    }
                    else
                    {
                        if (context.PublishHelper.SourceItemExists(context.ItemId))
                        {
                            Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
                            Log(string.Format("PUBLISH [{0}]: {1}", context.Result.Operation, AuditFormatter.FormatItem(sourceItem)));
                        }
                        else
                        {
                            Log(string.Format("PUBLISH [{0}]: {1}, msg: {2}", context.Result.Operation, context.ItemId, context.Result.Explanation));
                        }
                    }
                }
            }
        }
Ejemplo n.º 17
0
        private bool SuccessfulPublishState(PublishItemContext context)
        {
            if (context == null || context.Result == null)
                return false;

            if (context.Result.Operation != PublishOperation.Created &&
                context.Result.Operation != PublishOperation.Updated)
                return false;

            if (context.Action != PublishAction.PublishVersion)
                return false;

            if (context.VersionToPublish == null)
                return false;

            return true;
        }
        public override void Process(PublishItemContext context)
        {
            var settingsItem = Constants.SettingsItem;

            if (settingsItem[Templates.DeploymentMode.Fields.DeploymentModeOn].ToString().Equals("1") && settingsItem[Templates.DeploymentMode.Fields.PreventPublishing.PreventPublishingOn].ToString().Equals("1"))
            {
                //Check if Admin is allowed to publish
                var allowAdmin = settingsItem[Templates.DeploymentMode.Fields.PreventPublishing.AllowAdminToPublish].ToString().Equals("1");
                //Check if current user is Administrator
                var isAdmin = User.Current.IsAdministrator;

                if (allowAdmin == false || (allowAdmin && isAdmin == false))
                {
                    throw new Exception("Not Allowed. Your Admin has prevented publishing during deployment");
                }
            }
        }
        public override void Process(PublishItemContext context)
        {
            Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);

            if (sourceItem != null)
            {
                // Check whether any item found in target DB with same name and path of item being published.
                Item targetItem = context.PublishOptions.TargetDatabase.GetItem(sourceItem.Paths.Path);

                if (targetItem != null && targetItem.ID != sourceItem.ID)
                {
                    // If found.. delete item from target database.
                    context.PublishHelper.DeleteTargetItem(targetItem.ID);
                    Log.Info("Deleted duplicate item: " + targetItem.Paths.Path, this);
                }
            }
        }
Ejemplo n.º 20
0
        public override void Process(PublishItemContext context)
        {
            Sitecore.Data.ID itmID = context.ItemId;

            Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");

            Item item = masterDB.GetItem(itmID);

            if (item == null)
            {
                return;
            }



            //string spName = "dbo.AddToPublishLog";
            //String ConnectionString = Sitecore.Configuration.Settings.GetConnectionString("custom");
            //if (!String.IsNullOrWhiteSpace(ConnectionString))
            //{
            //    using (SqlConnection connection = new SqlConnection(ConnectionString))
            //    {
            //        using (SqlCommand command = new SqlCommand(spName, connection))
            //        {
            //            command.CommandType = CommandType.StoredProcedure;

            //            command.Parameters.Add(new SqlParameter("@Site", Sitecore.Context.Site.Name.ToString()));
            //            command.Parameters.Add(new SqlParameter("@ItemID", item.ID.ToString()));

            //            Item produdctGp = GetProductGroup(item);
            //            command.Parameters.Add(new SqlParameter("@ProductGroupItemID", produdctGp == null ? string.Empty : produdctGp.ID.ToString()));

            //            Item productCat = GetProductCategory(item);
            //            command.Parameters.Add(new SqlParameter("@ProductCategoryItemID", productCat == null ? string.Empty : productCat.ID.ToString()));
            //            command.Parameters.Add(new SqlParameter("@Language", String.Empty));
            //            command.Parameters.Add(new SqlParameter("@Mode", String.Empty));
            //            command.Parameters.Add(new SqlParameter("@RepublishAll", String.Empty));
            //            command.Parameters.Add(new SqlParameter("@SourceDatabase", String.Empty));
            //            command.Parameters.Add(new SqlParameter("@TargetDatabase", String.Empty));
            //            command.Parameters.Add(new SqlParameter("@RequestedBy", String.Empty));

            //            connection.Open();
            //            command.ExecuteNonQuery();
            //        }
            //    }
            //}
        }
        public override void Process(PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, "context");
            Item item = context.PublishHelper.GetSourceItem(context.ItemId);

            if (item != null &&
                !PublishingHelper.CanPublishItem(item, Sitecore.Context.User))
            {
                string msg = String.Format(
                    "{0} does not have permission to publish {1}",
                    Sitecore.Context.User.Name,
                    item.Paths.FullPath);
                context.AbortPipeline(
                    PublishOperation.Skipped,
                    PublishChildAction.Allow,
                    Translate.Text(msg));
            }
        }
        /// <summary>
        /// Gets the list of item references.
        /// </summary>
        /// <param name="context">The publish item context.</param>
        /// <returns>
        /// The list of item references.
        /// </returns>
        protected override List <Item> GetItemReferences(PublishItemContext context)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNull(context, "context");

            var         deepRelatedTemplates = GetAdvancedPublishingSettings(context);
            List <Item> items = new List <Item>();

            if (context.PublishOptions.Mode != PublishMode.SingleItem)
            {
                return(items);
            }
            switch (context.Action)
            {
            case PublishAction.PublishSharedFields:
            {
                var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
                if (sourceItem == null)
                {
                    return(items);
                }
                //added custom parameter deepRelatedTemplates
                items.AddRange(this.GetReferences(sourceItem, true, deepRelatedTemplates: deepRelatedTemplates));
                break;
            }

            case PublishAction.PublishVersion:
            {
                Item versionToPublish = context.VersionToPublish;
                if (versionToPublish == null)
                {
                    return(items);
                }
                //added custom parameter deepRelatedTemplates
                items.AddRange(this.GetReferences(versionToPublish, false, deepRelatedTemplates: deepRelatedTemplates));
                break;
            }

            default:
            {
                return(items);
            }
            }
            return(items);
        }
        /// <summary>
        /// Updates the publish context.
        /// </summary>
        /// <param name="context">The context.</param>
        void UpdateContextStatistics([NotNull] PublishItemContext context)
        {
            Debug.ArgumentNotNull(context, "context");

            PublishItemResult result         = context.Result;
            PublishContext    publishContext = context.PublishContext;

            if (result == null || publishContext == null)
            {
                return;
            }

            switch (result.Operation)
            {
            case PublishOperation.None:
            case PublishOperation.Skipped:
                lock (publishContext)
                {
                    publishContext.Statistics.Skipped++;
                }
                break;

            case PublishOperation.Created:
                lock (publishContext)
                {
                    publishContext.Statistics.Created++;
                }
                break;

            case PublishOperation.Updated:
                lock (publishContext)
                {
                    publishContext.Statistics.Updated++;
                }
                break;

            case PublishOperation.Deleted:
                lock (publishContext)
                {
                    publishContext.Statistics.Deleted++;
                }
                break;
            }
        }
Ejemplo n.º 24
0
        public override void Process(PublishItemContext context)
        {
            var item = context.PublishHelper.GetSourceItem(context.ItemId);

            if (item != null && item.ID != ItemIDs.MediaLibraryRoot &&
                item.TemplateID != TemplateIDs.MediaFolder &&
                item.Paths.IsMediaItem)
            {
                string mediaPath = item.Paths.MediaPath;
                if (context.Action == PublishAction.DeleteTargetItem)
                {
                    DeleteMediaFile(mediaPath);
                }
                else
                {
                    MediaStream mediaStream = MediaManager.GetMedia(item).GetStream();
                    UploadMediaFile(mediaPath, mediaStream.Stream);
                }
            }
        }
        /// <summary>
        /// Traces the information.
        /// </summary>
        /// <param name="context">The context.</param>
        void TraceInformation([NotNull] PublishItemContext context)
        {
            Debug.ArgumentNotNull(context, "context");

            if (!TraceToLog)
            {
                return;
            }

            PublishItemResult result = context.Result;
            Item item = context.PublishHelper.GetItemToPublish(context.ItemId);

            string itemName      = (item != null ? item.Name : "(null)");
            string itemOperation = (result != null ? result.Operation.ToString() : "(null)");
            string childAction   = (result != null ? result.ChildAction.ToString() : "(null)");
            string explanation   = (result != null && result.Explanation.Length > 0 ? result.Explanation : "(none)");

            Log.Info("##Publish Item:         " + itemName + " - " + context.ItemId, this);
            Log.Info("##Publish Operation:    " + itemOperation, this);
            Log.Info("##Publish Child Action: " + childAction, this);
            Log.Info("##Explanation:          " + explanation, this);
        }
Ejemplo n.º 26
0
        protected override List <Item> GetItemReferences(PublishItemContext context)
        {
            var referenceList = new List <Item>();

            //this is the item being published
            var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);

            //this should never be true, but why not
            if (sourceItem == null || sourceItem.Empty)
            {
                return(referenceList);
            }

            //better way of doing this is via Decorator Pattern, otherwise you
            //will constantly be recompiling this file with new logic for each
            //template
            switch (sourceItem.TemplateID.ToString())
            {
            case (ProductTemplateId):
                Log.Info("product publishing detected", this);
                var crossSellItems = GetCrossSellsForProduct(sourceItem);
                if (crossSellItems != null && crossSellItems.Any())
                {
                    referenceList.AddRange(crossSellItems);
                }
                break;
            }

            Log.Info(string.Format("GETITEMREFERENCES: referenceList has {0} items", referenceList.Count()), this);

            //only necessary if we want to see the GUIDs in our log file
            foreach (var item in referenceList.Where(item => item != null && !item.Empty))
            {
                Log.Info(string.Format("GETITEMREFERENCES: Item ID - {0}", item.ID), this);
            }

            return(referenceList);
        }
        /// <summary>
        /// Updates the job statistics.
        /// </summary>
        /// <param name="context">The context.</param>
        void UpdateJobStatistics([NotNull] PublishItemContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            PublishItemResult result = context.Result;

            if (result == null || result.Operation == PublishOperation.None)
            {
                return;
            }

            Job job = context.Job;

            if (job == null)
            {
                return;
            }

            lock (job)
            {
                job.Status.Processed++;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Determines if the current item that is being published is excluded from publish for the publishing target and publish mode
        /// </summary>
        /// <param name="context">current item's publish context</param>
        /// <returns>true if item is excluded from current publish, else false</returns>
        public virtual bool IsExcludedForCurrentPublish(PublishItemContext context)
        {
            Assert.ArgumentNotNull((object)context, "context");
            Assert.ArgumentNotNull((object)context.VersionToPublish, "context.VersionToPublish");
            Assert.ArgumentNotNull((object)context.PublishOptions, "context.PublishOptions");
            Assert.ArgumentNotNull((object)context.PublishOptions.PublishingTargets, "context.PublishOptions.PublishingTargets");
            Assert.ArgumentNotNull((object)context.PublishOptions.PublishingTargets[0], "context.PublishOptions.PublishingTargets[0]");

            string itemPath = FormatItemPath(context.VersionToPublish.Paths.Path);

            PublishExclusion exclusion = Repository.PublishExclusions
                                         .Where(pe => pe.PublishingTargetID == context.PublishOptions.PublishingTargets[0])
                                         .Where(pe => pe.PublishModes.Contains(context.PublishOptions.Mode))
                                         .Where(pe => pe.ExcludedNodes.Exists(p => itemPath.StartsWith(p, StringComparison.OrdinalIgnoreCase)) &&
                                                !pe.ExclusionOverrides.Exists(p => itemPath.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
                                         .FirstOrDefault();

            if (exclusion != null)
            {
                return(true);
            }

            return(false);
        }
        public void ItemProcessed(object sender, EventArgs args)
        {
            ItemProcessedEventArgs itemProcessedEventArgs = args as ItemProcessedEventArgs;
            PublishItemContext     context = itemProcessedEventArgs != null ? itemProcessedEventArgs.Context : null;

            if (context != null)
            {
                var publishingItem = context.VersionToPublish;

                if (publishingItem != null)
                {
                    var gcId = publishingItem["GC Content Id"];

                    if (!String.IsNullOrEmpty(gcId))
                    {
                        var settings = ServiceFactory.Settings;

                        var        gcItemService = new ItemsService(settings);
                        ItemEntity gcItem        = gcItemService.GetSingleItem(gcId);
                        if (gcItem != null)
                        {
                            var gcProjectService   = new ProjectsService(settings);
                            var allProjectStatuses = gcProjectService.GetAllStatuses(gcItem.Data.ProjectId.ToString());
                            if (allProjectStatuses != null && allProjectStatuses.Data.Any())
                            {
                                var targetStatus = allProjectStatuses.Data.FirstOrDefault(s => s.Name.ToLower() == settings.StatusAfterPublish.ToLower());
                                if (targetStatus != null)
                                {
                                    gcItemService.ChangeItemStatus(gcId, targetStatus.Id);
                                }
                            }
                        }
                    }
                }
            }
        }
 public override void Process(PublishItemContext context)
 {
     AuditLogger.Current.Log(context.VersionToPublish, "6",
                             $"<table><th>Field</th><th>Source</th><th>Target</th><tr><td>Location</td><td>{context.PublishOptions.SourceDatabase.Name}</td><td>{context.PublishOptions.TargetDatabase.Name}</td></tr></table>");
 }
        /// <summary>
        /// Determines if the current item that is being published is excluded from publish for the publishing target and publish mode
        /// </summary>
        /// <param name="context">current item's publish context</param>
        /// <returns>true if item is excluded from current publish, else false</returns>
        public virtual bool IsExcludedForCurrentPublish(PublishItemContext context)
        {
            Assert.ArgumentNotNull((object)context, "context");
            Assert.ArgumentNotNull((object)context.VersionToPublish, "context.VersionToPublish");
            Assert.ArgumentNotNull((object)context.PublishOptions, "context.PublishOptions");
            Assert.ArgumentNotNull((object)context.PublishOptions.PublishingTargets, "context.PublishOptions.PublishingTargets");
            Assert.ArgumentNotNull((object)context.PublishOptions.PublishingTargets[0], "context.PublishOptions.PublishingTargets[0]");

            string itemPath = FormatItemPath(context.VersionToPublish.Paths.Path);

            PublishExclusion exclusion = Repository.PublishExclusions
                                            .Where(pe => pe.PublishingTargetID == context.PublishOptions.PublishingTargets[0])
                                            .Where(pe => pe.PublishModes.Contains(context.PublishOptions.Mode))
                                            .Where(pe => pe.ExcludedNodes.Exists(p => itemPath.StartsWith(p, StringComparison.OrdinalIgnoreCase)) &&
                                                !pe.ExclusionOverrides.Exists(p => itemPath.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
                                            .FirstOrDefault();

            if (exclusion != null)
                return true;

            return false;
        }
Ejemplo n.º 32
0
        public override void Process(PublishItemContext context)
        {
            Logger.Info("CdnPublish started the job");
            //Check the configuration to run the processor or not
            if (this.Enabled.ToLower() != "yes")
            {
                return;
            }
            Assert.ArgumentNotNull((object)context, "context");
            //Get the Context Item
            Item sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);

            //If the source item is null, get the target item (specifically used for deleted item)
            if (sourceItem == null || !sourceItem.Paths.IsMediaItem)
            {
                Item webSourceItem = context.PublishHelper.GetTargetItem(context.ItemId);
                //if (webSourceItem == null || !webSourceItem.Paths.IsMediaItem )
                if (webSourceItem == null || !webSourceItem.Paths.IsMediaItem)
                {
                    return;
                }
                else
                {
                    sourceItem = webSourceItem;
                }
            }

            MediaItem mediaItem      = (MediaItem)sourceItem;
            string    mediaExtension = mediaItem.Extension;
            //Get the Media Stream
            Stream mediaStream = mediaItem.GetMediaStream();

            if (mediaStream == null || mediaStream.Length == 0L)
            {
                return;
            }
            Item currentItem = mediaItem;

            if (string.IsNullOrEmpty(currentItem["Uploaded To Cloud CDN"]) || currentItem["Uploaded To Cloud CDN"] != "1")
            {
                AzureStorageUpload azureStorageUpload = new AzureStorageUpload();
                try
                {
                    //Get Version Information
                    Item versionToPublish = context.VersionToPublish;
                    if (versionToPublish == null)
                    {
                        if (context.PublishHelper.GetTargetItemInLanguage(context.ItemId, sourceItem.Language) != null)
                        {
                            versionToPublish = context.PublishHelper.GetTargetItemInLanguage(context.ItemId, sourceItem.Language);
                        }
                    }

                    if (versionToPublish != null)
                    {
                        //Parameters to upload/replace/delete from on Azure
                        object[] args = new object[] { mediaItem, mediaExtension, versionToPublish.Language.Name };
                        Sitecore.Jobs.JobOptions jobOptions = null;
                        Sitecore.Context.Job.Status.State = JobState.Initializing;
                        if (context.Action == PublishAction.None)
                        {
                            jobOptions = new Sitecore.Jobs.JobOptions(
                                mediaItem.ID.ToString(),                  // identifies the job
                                "CDN Upload",                             // categoriezes jobs
                                Sitecore.Context.Site.Name,               // context site for job
                                azureStorageUpload,                       // object containing method
                                "uploadMediaToAzure",                     // method to invoke
                                args)                                     // arguments to method
                            {
                                AfterLife      = TimeSpan.FromSeconds(5), // keep job data for one hour
                                EnableSecurity = false,                   // run without a security context
                            };
                            Sitecore.Context.Job.Status.State = JobState.Finished;
                            Sitecore.Jobs.Job pub = Sitecore.Jobs.JobManager.Start(jobOptions);
                        }
                        if (context.Action == PublishAction.PublishSharedFields || context.Action == PublishAction.PublishVersion)
                        {
                            jobOptions = new Sitecore.Jobs.JobOptions(mediaItem.ID.ToString(), "CDN Upload", Sitecore.Context.Site.Name, azureStorageUpload, "replaceMediaFromAzure", args)
                            {
                                AfterLife = TimeSpan.FromSeconds(5), EnableSecurity = false,
                            };
                            Sitecore.Context.Job.Status.State = JobState.Finished;
                            Sitecore.Jobs.Job pub = Sitecore.Jobs.JobManager.Start(jobOptions);
                        }
                        //If the publish action is delete target item, get all the language versions of the item and delete it from Azure
                        if (context.Action == PublishAction.DeleteTargetItem)
                        {
                            foreach (Language lang in context.PublishOptions.TargetDatabase.GetLanguages())
                            {
                                mediaItem  = context.PublishHelper.GetTargetItemInLanguage(mediaItem.ID, lang);
                                args       = new object[] { mediaItem, mediaItem.Extension, lang.Name };
                                jobOptions = new Sitecore.Jobs.JobOptions(mediaItem.ID.ToString(), "CDN Upload", Sitecore.Context.Site.Name, azureStorageUpload, "deleteMediaFromAzure", args)
                                {
                                    AfterLife      = TimeSpan.FromSeconds(5),
                                    EnableSecurity = false,
                                };
                                Sitecore.Context.Job.Status.State = JobState.Finished;
                                Sitecore.Jobs.Job pub = Sitecore.Jobs.JobManager.Start(jobOptions);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Exception exception = new Exception(string.Format("CDN Processing failed for {1} ({0} version: {2}). {3}", (object)sourceItem.ID, (object)sourceItem.Name, (object)context.VersionToPublish.Language.Name, (object)ex.Message));
                    Log.Error(exception.Message, exception, (object)this);
                    Logger.Error(exception.Message, exception);
                    Sitecore.Diagnostics.Log.Error(exception.Message, exception, (object)this);
                    context.Job.Status.Failed = true;
                    context.Job.Status.Messages.Add(exception.Message);
                }
                Sitecore.Diagnostics.Log.Info(" CDN synchronization finished ", (object)this);
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Called by publishItem pipeline to determine if item should be excluded from publishing or not
 /// </summary>
 /// <param name="context">context of the item being published</param>
 public override void Process(PublishItemContext context)
 {
     ProcessPublishItem(context);
 }
 /// <summary>
 /// Called by publishItem pipeline to determine if item should be excluded from publishing or not
 /// </summary>
 /// <param name="context">context of the item being published</param>
 public override void Process(PublishItemContext context)
 {
     ProcessPublishItem(context);
 }
 public override void Process(PublishItemContext context)
 {
     AuditLogger.Current.Log(context.VersionToPublish, "6",
         $"<table><th>Field</th><th>Source</th><th>Target</th><tr><td>Location</td><td>{context.PublishOptions.SourceDatabase.Name}</td><td>{context.PublishOptions.TargetDatabase.Name}</td></tr></table>");
 }
Ejemplo n.º 36
0
        public void OnItemProcessed(object sender, EventArgs args)
        {
            PublishItemContext context = args is ItemProcessedEventArgs itemProcessedEventArgs
                ? itemProcessedEventArgs.Context
                : null;

            if (context == null)
            {
                return;
            }

            EnterspeedSitecoreConfiguration configuration = _enterspeedConfigurationService.GetConfiguration();

            if (!configuration.IsEnabled)
            {
                return;
            }

            Language language = context.PublishOptions.Language;

            // Getting the source item first
            Item sourceItem = _itemManager.GetItem(context.ItemId, language, Version.Latest, context.PublishHelper.Options.SourceDatabase);

            if (sourceItem == null)
            {
                return;
            }

            if (!HasAllowedPath(sourceItem))
            {
                return;
            }

            // Handling if the item was deleted or unpublished
            bool itemIsDeleted = context.Action == PublishAction.DeleteTargetItem;

            if (itemIsDeleted)
            {
                HandleContentItem(sourceItem, configuration, true, false);
                HandleRendering(sourceItem, configuration, true, false);
                HandleDictionary(sourceItem, configuration, true, false);

                return;
            }

            // Handling if the item was published
            Item targetItem = _itemManager.GetItem(context.ItemId, language, Version.Latest, context.PublishHelper.Options.TargetDatabase);

            if (targetItem == null || targetItem.Versions.Count == 0)
            {
                return;
            }

            if (!HasAllowedPath(targetItem))
            {
                return;
            }

            HandleContentItem(targetItem, configuration, false, true);
            HandleRendering(targetItem, configuration, false, true);
            HandleDictionary(targetItem, configuration, false, true);
        }