/// <summary>
        /// For Publish and UnPublish, remove all items from the website structure Publication from the list.
        /// Website structure Publication URI is read from the config file.
        /// </summary>
        /// <param name="item">Item to be resolved (e.g. a page, structure group, template)</param>
        /// <param name="instruction">Resolve instruction</param>
        /// <param name="context">Publish context</param>
        /// <param name="resolvedItems">List of items that are currently to be rendered and published (added by previous resolvers in the chain)</param>
        public void Resolve(IdentifiableObject item, ResolveInstruction instruction, PublishContext context, Tridion.Collections.ISet<ResolvedItem> resolvedItems)
        {
            List<ResolvedItem> itemsToRemove = new List<ResolvedItem>();
            StringBuilder infoMessage = new StringBuilder();
            infoMessage.AppendLine(string.Format("Removed the following items from a {0} Transaction to {1}:", instruction.Purpose, context.PublicationTarget.Title));

            // check for items from website structure publication (these do not need to be published or unpublished) 
            foreach (ResolvedItem resolvedItem in resolvedItems)
            {
                // mark all items from website structure publication for removal
                if (resolvedItem.Item.Id.PublicationId == _websiteStructurePublicationUri.ItemId)
                {
                    itemsToRemove.Add(resolvedItem);
                }
            }

            // remove all items that we need to discard
            foreach (ResolvedItem itemToRemove in itemsToRemove)
            {
                infoMessage.AppendLine(string.Format("{0}: {1} ({2})", itemToRemove.Item.Id.ItemType, itemToRemove.Item.Title, itemToRemove.Item.Id));
                resolvedItems.Remove(itemToRemove);
            }
            if (itemsToRemove.Count > 0)
            {
                // log info mesage about which items have been removed (optionally this can be logged as a warning to stand out in the logfile)
                Logger.Write(infoMessage.ToString(), "ChildPublicationsOnlyResolver", LoggingCategory.General, TraceEventType.Information);
            }
        }
Ejemplo n.º 2
0
 public override void Process(PublishContext context)
 {
     try
     {
         StringBuilder sb = new StringBuilder($"<tr><td>Created</td><td>{context.Statistics.Created}</td></tr>");
         sb.Append($"<tr><td>Deleted</td><td>{context.Statistics.Deleted}</td></tr>");
         sb.Append($"<tr><td>Skipped</td><td>{context.Statistics.Skipped}</td></tr>");
         sb.Append($"<tr><td>Updated</td><td>{context.Statistics.Updated}</td></tr>");
         string statistics = $"<table><th>Type</th><th>Items Processed</th>{sb}</table>";
         string publishInfo =
             $"<table><th>Source</th><th>Target</th><tr><td>{context.PublishOptions.SourceDatabase.Name}</td><td>{context.PublishOptions.TargetDatabase.Name}</td></tr></table>";
         if (context.PublishOptions.RootItem != null)
             AuditLogger.Current.Log(context.PublishOptions.RootItem, "5", $"{publishInfo}{statistics}");
         else
             AuditLogger.Current.Log(new ItemAuditEntry("5", "", "" )
             {
                 Database = context.PublishOptions.SourceDatabase.Name,
                 Note = $"{publishInfo}{statistics}",
                 User = context.User.Name,
                 Role = context.User.Roles.Select(x => x.Name).ToList(),
                 Id = ID.Null,
                 TimeStamp = DateTime.Now,
                 Path = context.PublishOptions.RootItem != null ? context.PublishOptions.RootItem.Paths.FullPath : "full site"
             });
     }
     catch (Exception ex)
     {
         Log.Error("problem auditing publish", ex, this);
     }
 }
Ejemplo n.º 3
0
 private static PublishItemContext CreateItemContext(PublishingCandidate entry, PublishContext context)
 {
     Assert.ArgumentNotNull(entry, "entry");
     var context2 = PublishManager.CreatePublishItemContext(entry.ItemId, entry.PublishOptions);
     context2.Job = context.Job;
     context2.User = context.User;
     context2.PublishContext = context;
     return context2;
 }
Ejemplo n.º 4
0
        protected virtual void ProcessEntries(IEnumerable<PublishingCandidate> entries, PublishContext context, int depth)
        {
            var level = depth - 5;
            if (level < 1)
            {
                level = 1;
            }

            Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = level }, candidate => this.ProcessCandidate(candidate, context, depth));
        }
        protected virtual void ProcessEntries(IEnumerable<PublishingCandidate> entries, PublishContext context, int depth)
        {
            var level = depth - 5;
            if (level < 1)
            {
                level = 1;
            }

            entries.ForEach(candidate => this.ProcessCandidate(candidate, context, depth));
        }
Ejemplo n.º 6
0
 public override void Process(PublishContext context)
 {
     Assert.ArgumentNotNull(context, "context");
     Log.Info(GetType().FullName + ": Adding items to publish queue - START", this);
     _sourceDatabase = context.PublishOptions.SourceDatabase;
     IEnumerable<ID> itemIDs = GetRelatedItemIDs(context.PublishOptions);
     IEnumerable<PublishingCandidate> publishingCandidates = itemIDs.Select(itemId => new PublishingCandidate(itemId, context.PublishOptions)).ToArray();
     context.Queue.Add(publishingCandidates);
     Log.Info(GetType().FullName + ": Adding items to publish queue - END", this);
 }
Ejemplo n.º 7
0
        protected virtual void ProcessEntries(IEnumerable<PublishingCandidate> entries, PublishContext context, int depth)
        {
            //foreach (PublishingCandidate candidate in entries)
            //{
            //    ProcessCandidate(candidate, context);
            //}
            int level = depth - 5;
            if (level < 1) level = 1;

            Parallel.ForEach(entries, new ParallelOptions { MaxDegreeOfParallelism = level }, candidate => ProcessCandidate(candidate, context, depth));
        }
Ejemplo n.º 8
0
 private static void UpdateJobStatus(PublishContext context)
 {
     var job = context.Job;
     if (job.IsNotNull())
     {
         job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items created: "), context.Statistics.Created));
         job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items deleted: "), context.Statistics.Deleted));
         job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items updated: "), context.Statistics.Updated));
         job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items skipped: "), context.Statistics.Skipped));
     }
 }
Ejemplo n.º 9
0
 private void ProcessCandidate(PublishingCandidate candidate, PublishContext context, int depth)
 {
     PublishItemResult result = PublishItemPipeline.Run(CreateItemContext(candidate, context));
     if (!SkipReferrers(result, context))
     {
         ProcessEntries(result.ReferredItems, context, depth + 1);
     }
     if (!SkipChildren(result, candidate, context))
     {
         ProcessEntries(candidate.ChildEntries, context, depth + 1);
     }
 }
        private static void UpdateJobStatus(PublishContext context)
        {
            var job = context.Job;

            if (job.IsNotNull())
            {
                job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items created: "), context.Statistics.Created));
                job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items deleted: "), context.Statistics.Deleted));
                job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items updated: "), context.Statistics.Updated));
                job.Status.Messages.Add(string.Format("{0}{1}", Translate.Text("Items skipped: "), context.Statistics.Skipped));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns the additional items to be published from the velir images field
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public List <PublishingCandidate> GetAdditionalPublishingCandidates(PublishContext context)
        {
            List <PublishingCandidate> additionalItems = new List <PublishingCandidate>();

            Item         item     = context.PublishOptions.RootItem;
            TemplateItem template = item.Template;

            foreach (TemplateFieldItem field in template.Fields)
            {
                //verify not a standard/system field
                if (field.InnerItem.IsNotNull() && field.InnerItem.Paths.FullPath.ToLower().StartsWith("/sitecore/templates/system"))
                {
                    continue;
                }

                //get field value
                string fieldValue = item[field.Name];
                if (string.IsNullOrEmpty(fieldValue))
                {
                    continue;
                }

                //split into guid array
                string[] values = fieldValue.Split('|');
                if (values.Length == 0)
                {
                    continue;
                }

                foreach (string fieldValueItemId in values)
                {
                    if (string.IsNullOrEmpty(fieldValueItemId))
                    {
                        continue;
                    }

                    ID additionalItemId;
                    if (!ID.TryParse(fieldValueItemId, out additionalItemId))
                    {
                        continue;
                    }

                    PublishOptions options = new PublishOptions(context.PublishOptions.SourceDatabase,
                                                                context.PublishOptions.TargetDatabase,
                                                                PublishMode.Smart,
                                                                item.Language, context.PublishOptions.PublishDate);
                    PublishingCandidate publishingCandidate = new PublishingCandidate(additionalItemId, options);
                    additionalItems.Add(publishingCandidate);
                }
            }

            return(additionalItems);
        }
Ejemplo n.º 12
0
        public static void AreEqualPublishContext(ServiceSettings settings, string configPath, string deploymentName, string label, string packagePath, string subscriptionId, PublishContext actual)
        {
            AreEqualServiceSettings(settings, actual.ServiceSettings);
            Assert.AreEqual<string>(configPath, actual.ConfigPath);
            Assert.AreEqual<string>(deploymentName, actual.DeploymentName);
            Assert.AreEqual<string>(label, actual.ServiceName);
            Assert.AreEqual<string>(packagePath, actual.PackagePath);
            Assert.AreEqual<string>(subscriptionId, actual.SubscriptionId);

            Assert.IsTrue(File.Exists(actual.ConfigPath));
            Assert.IsTrue(File.Exists(actual.PackagePath));
        }
        public async Task Send(PublishContext <T> context, IPipe <PublishContext <T> > next)
        {
            var activity = StartIfEnabled(_diagnosticSource, $"Publishing Message: {TypeMetadataCache<T>.ShortName}", new { context }, context);

            try
            {
                await next.Send(context).ConfigureAwait(false);
            }
            finally
            {
                StopIfEnabled(_diagnosticSource, activity, new { context });
            }
        }
Ejemplo n.º 14
0
        private async Task DoPublishAsync(PublishContext context)
        {
            var dr = await _kafkaProducer.ProduceAsync(context.Topic, new Message <string, string>
            {
                Key   = context.Key,
                Value = new KafkaMessage(context.Message,
                                         context.Key,
                                         _host,
                                         _app).ToJson()
            });

            Console.WriteLine(dr);
        }
Ejemplo n.º 15
0
            public async Task Send(PublishContext <TMessage> context)
            {
                await Task.WhenAll(_initializers.Select(x => x.Apply(_context, context))).ConfigureAwait(false);

                if (_pipe.IsNotEmpty())
                {
                    await _pipe.Send(context).ConfigureAwait(false);
                }

                if (_sendPipe.IsNotEmpty())
                {
                    await _sendPipe.Send(context).ConfigureAwait(false);
                }
            }
        private static bool SiteUsesPublishTargetDatabase(SiteInfo site, PublishContext context)
        {
            if (string.IsNullOrWhiteSpace(site.Database) || context.PublishOptions.TargetDatabase == null)
            {
                return(true);
            }

            if (site.Database.Equals(context.PublishOptions.TargetDatabase.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                return(true);
            }

            return(false);
        }
        public async Task Send(PublishContext <T> context)
        {
            if (_context.ConversationId.HasValue)
            {
                context.ConversationId = _context.ConversationId;
            }

            if (_context.CorrelationId.HasValue)
            {
                context.InitiatorId = _context.CorrelationId;
            }

            await _pipe.Send(context).ConfigureAwait(false);
        }
        // ReSharper disable once UnusedMember.Global
        public async Task PublishMethodology(
            [QueueTrigger(PublishMethodologyQueue)]
            PublishMethodologyMessage message,
            ExecutionContext executionContext,
            ILogger logger)
        {
            logger.LogInformation($"{executionContext.FunctionName} triggered: {message}");

            var context = new PublishContext(DateTime.UtcNow, false);

            await _contentService.UpdateMethodology(context, message.MethodologyId);

            logger.LogInformation($"{executionContext.FunctionName} completed");
        }
        public override void Process(PublishContext context)
        {
            var candidates = new List<PublishingCandidate>();

            ID candidate;
            do
            {
                if (!ManuallyAddedCandidates.TryDequeue(out candidate)) break;

                candidates.Add(new PublishingCandidate(candidate, context.PublishOptions));
            } while (candidate != (ID)null);

            context.Queue.Add(candidates);
        }
Ejemplo n.º 20
0
        public override void Process(PublishContext context)
        {
            // Only run if SPRK is enabled in config
            if (!_enabled)
            {
                return;
            }

            // Ensure the log folder exists before log output begins
            if (!Directory.Exists(_logFolder))
            {
                Directory.CreateDirectory(_logFolder);
            }
        }
        private void ProcessCandidate(PublishingCandidate candidate, PublishContext context, int depth)
        {
            var result = PublishItemPipeline.Run(CreateItemContext(candidate, context));

            if (!this.SkipReferrers(result, context))
            {
                this.ProcessEntries(result.ReferredItems, context, depth + 1);
            }

            if (!SkipChildren(result, candidate))
            {
                this.ProcessEntries(candidate.ChildEntries, context, depth + 1);
            }
        }
        private bool SiteCacheNeedsCleared(SiteInfo site, PublishContext context)
        {
            if (!site.CacheHtml || site.HtmlCache == null)
            {
                return(false);
            }

            if (!SiteUsesPublishTargetDatabase(site, context))
            {
                return(false);
            }

            return(PublishRootIsUnderSiteRoot(site, context));
        }
Ejemplo n.º 23
0
        public Task Send(PublishContext <T> context)
        {
            if (_context.ConversationId.HasValue)
            {
                context.ConversationId = _context.ConversationId;
            }

            if (_context.CorrelationId.HasValue)
            {
                context.InitiatorId = _context.CorrelationId;
            }

            return(_pipe.Send(context));
        }
        public async Task Send(PublishContext <T> context)
        {
            context.MessageId = MessageId;
            context.SetScheduledEnqueueTime(_scheduledTime);

            if (_pipe != null)
            {
                await _pipe.Send(context).ConfigureAwait(false);
            }

            if (_sendPipe != null)
            {
                await _sendPipe.Send(context).ConfigureAwait(false);
            }
        }
Ejemplo n.º 25
0
        public override void Process(PublishContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            try
            {
                var options = new DefaultJobOptions("Send Teams Notification", "Notifications", Context.Site.Name, this, "Run", new object[] { context });
                JobManager.Start(options);
                PowerShellLog.Info($"Job started: Send Teams Notification");
            }
            catch (Exception ex)
            {
                PowerShellLog.Error($"Error while invoking Send Teams Notification job from Publish pipeline.", ex);
            }
        }
Ejemplo n.º 26
0
        public void TestDeploymentSettingsTestWithDefaultServiceSettings()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            settings.Subscription = "TestSubscription2";
            PublishContext deploySettings = new PublishContext(
                settings,
                packagePath,
                configPath,
                label,
                deploymentName,
                rootPath);

            AzureAssert.AreEqualPublishContext(settings, configPath, deploymentName, label, packagePath, "f62b1e05-af8f-4205-8f98-325079adc155", deploySettings);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Publishes a message to all subscribed consumers for the message type
        /// </summary>
        /// <typeparam name="T">The type of the message</typeparam>
        /// <param name="message">The messages to be published</param>
        /// <param name="contextCallback">The callback to perform operations on the context</param>
        public void Publish <T>(T message, Action <IPublishContext <T> > contextCallback)
            where T : class
        {
            PublishContext <T> context = ContextStorage.CreatePublishContext(message);

            context.SetSourceAddress(Endpoint.Address.Uri);

            contextCallback(context);

            IList <Exception> exceptions = new List <Exception>();

            int publishedCount = 0;

            foreach (var consumer in OutboundPipeline.Enumerate(context))
            {
                try
                {
                    consumer(context);
                    publishedCount++;
                }
                catch (Exception ex)
                {
                    _log.Error(string.Format("'{0}' threw an exception publishing message '{1}'",
                                             consumer.GetType().FullName, message.GetType().FullName), ex);

                    exceptions.Add(ex);
                }
            }

            context.Complete();

            if (publishedCount == 0)
            {
                context.NotifyNoSubscribers();
            }

            _eventChannel.Send(new MessagePublished
            {
                MessageType   = typeof(T),
                ConsumerCount = publishedCount,
                Duration      = context.Duration,
            });

            if (exceptions.Count > 0)
            {
                throw new PublishException(typeof(T), exceptions);
            }
        }
Ejemplo n.º 28
0
        public void TestDeploymentSettingsTestWithDefaultServiceSettings()
        {
            string label          = "MyLabel";
            string deploymentName = service.ServiceName;

            settings.Subscription = "TestSubscription2";
            PublishContext deploySettings = new PublishContext(
                settings,
                packagePath,
                configPath,
                label,
                deploymentName,
                rootPath);

            AzureAssert.AreEqualPublishContext(settings, configPath, deploymentName, label, packagePath, "f62b1e05-af8f-4205-8f98-325079adc155", deploySettings);
        }
Ejemplo n.º 29
0
        public Task PublishFault <T>(PublishContext <T> context, Exception exception) where T : class
        {
            _logger.LogError(exception,
                             "Message publishing has been failed {@context}",
                             new
            {
                MessageId      = context.MessageId,
                ConversationId = context.ConversationId,
                CorrelationId  = context.CorrelationId,
                SentTime       = context.SentTime,
                Message        = context.Message,
                MessageType    = context.Message.GetType()
            });

            return(Task.CompletedTask);
        }
Ejemplo n.º 30
0
        public PublishingRepository(PublishContext ingestContext, IMediaStorage mediaStorage,
                                    IStreamBuilder streamBuilder, IConfiguration config,
                                    IObjectBus <Vocalia.ServiceBus.Types.Publishing.Podcast> podcastBus,
                                    IObjectBus <Vocalia.ServiceBus.Types.Podcast.Podcast> listenBus,
                                    IObjectBus <Timeline> timelineBus
                                    )
        {
            DbContext     = ingestContext;
            MediaStorage  = mediaStorage;
            StreamBuilder = streamBuilder;
            ListenBus     = listenBus;
            Config        = config;

            _ = podcastBus;
            _ = timelineBus;
        }
Ejemplo n.º 31
0
 private bool SkipChildren(PublishItemResult result, PublishingCandidate entry, PublishContext context)
 {
     if (result.ChildAction == PublishChildAction.Skip)
     {
         return true;
     }
     if (result.ChildAction != PublishChildAction.Allow)
     {
         return false;
     }
     if ((entry.PublishOptions.Mode != PublishMode.SingleItem) && (result.Operation == PublishOperation.Created))
     {
         return false;
     }
     return !entry.PublishOptions.Deep;
 }
Ejemplo n.º 32
0
        public async Task Send(PublishContext <T> context)
        {
            _context = context;

            context.SetScheduledEnqueueTime(_scheduledTime);

            if (_pipe.IsNotEmpty())
            {
                await _pipe.Send(context).ConfigureAwait(false);
            }

            if (_sendPipe.IsNotEmpty())
            {
                await _sendPipe.Send(context).ConfigureAwait(false);
            }
        }
Ejemplo n.º 33
0
        public override void Process(PublishContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            if (context.Aborted)
            {
                return;
            }

            if (context.Statistics.Created > 0 || context.Statistics.Updated > 0)
            {
                List <ID>     modifiedItemIDs = context.ProcessedPublishingCandidates.Keys.Select(i => i.ItemId).ToList();
                List <string> modifiedLinks   = FetchModifiedLinks(context, modifiedItemIDs);
                IndexingAPIHelper.SendIndexingRequest(modifiedLinks, "URL_UPDATED");
            }
        }
Ejemplo n.º 34
0
        public Task PrePublish <T>(PublishContext <T> context) where T : class
        {
            _logger.LogInformation(
                "Message is being published {@context}",
                new
            {
                MessageId      = context.MessageId,
                ConversationId = context.ConversationId,
                CorrelationId  = context.CorrelationId,
                SentTime       = context.SentTime,
                Message        = context.Message,
                MessageType    = context.Message.GetType()
            });

            return(Task.CompletedTask);
        }
Ejemplo n.º 35
0
        public override void Process(PublishContext context)
        {
            var watch = new Stopwatch();
            Log.Info("publish process started", this);
            watch.Start();
            Assert.ArgumentNotNull(context, "context");

            foreach (var enumerable in context.Queue)
            {
                this.ProcessEntries(enumerable, context, 0);
            }

            UpdateJobStatus(context);
            watch.Stop();
            Log.Info("publish process completed elapsed: " + watch.Elapsed, this);
        }
Ejemplo n.º 36
0
        public override void Process(PublishContext context)
        {
            Stopwatch watch = new Stopwatch();
            Log.Info("publish process started", this);
            watch.Start();
            Assert.ArgumentNotNull(context, "context");

            //Parallel.ForEach(context.Queue, entries => ProcessEntries(entries, context));
            foreach (IEnumerable<PublishingCandidate> enumerable in context.Queue)
            {
                ProcessEntries(enumerable, context, 0);
            }
            UpdateJobStatus(context);
            watch.Stop();
            Log.Info("publish process completed elapsed: " + watch.Elapsed, this);
        }
        public override void Process(PublishContext context)
        {
            var watch = new Stopwatch();

            Log.Info("publish process started", this);
            watch.Start();
            Assert.ArgumentNotNull(context, "context");

            foreach (var enumerable in context.Queue)
            {
                this.ProcessEntries(enumerable, context, 0);
            }

            UpdateJobStatus(context);
            watch.Stop();
            Log.Info("publish process completed elapsed: " + watch.Elapsed, this);
        }
 public override void Process(PublishContext context)
 {
     Assert.ArgumentNotNull(context, "context");
     using (new Timer("[Publishing] - Clearing Azure CDN"))
     {
         try
         {
             ProcessPublishedItems(context);
         }
         catch (Exception ex)
         {
             PublishingLog.Error("An error during Publish Pipeline Process Queue execution.", ex);
             throw;
         }
     }
     //UpdateJobStatus(context);
 }
Ejemplo n.º 39
0
        public override void Process(PublishContext context)
        {
            foreach (string name in context.PublishOptions.PublishingTargets)
            {
                string path = "/sitecore/system/publishing targets/" + name;
                Sitecore.Data.Items.Item target = context.PublishOptions.SourceDatabase.GetItem(path);
                Sitecore.Diagnostics.Assert.IsNotNull(target, path);
                string command = target["CommandLine"];

                if (String.IsNullOrEmpty(command))
                {
                    return;
                }

                CommandLineTool clt = new CommandLineTool(command);
                clt.Execute(true);
            }
        }
Ejemplo n.º 40
0
            public async Task Send(PublishContext<TMessage> context, IPipe<PublishContext<TMessage>> next)
            {
                var carrier = "send-message-filter";

                if (context.TryGetPayload(out ConsumeContext cc))
                {
                    // should occur on message B and it DOES, all good

                    carrier += ",has-consume-context";

                    if (cc.TryGetPayload(out SomePayload ccsp)) // never occurs, NOT GOOD :(
                        carrier += ",has-some-payload:" + ccsp.Text;
                }

                context.Headers.Set("x-send-message-filter", carrier);

                await next.Send(context);
            }
Ejemplo n.º 41
0
        public async Task Send(PublishContext <TMessage> context, IPipe <PublishContext <TMessage> > next)
        {
            var baseSpan = GlobalTracer.Instance
                           .BuildSpan(DependencyInjection.Instance.ServiceProvider.GetService <IOptions <MassTransitConfiguration> >().Value.PublisherName)
                           .AsChildOf(GlobalTracer.Instance.ActiveSpan);

            using (var scope = baseSpan.StartActive(finishSpanOnDispose: true))
            {
                var span = scope.Span
                           .SetTag(Tags.SpanKind, Tags.SpanKindProducer)
                           .SetTag("MessageId", context.MessageId?.ToString())
                           .SetTag("MessageType", context.Message.GetType().FullName);

                GlobalTracer.Instance.Inject(span.Context, BuiltinFormats.TextMap, new TextMapInjectAdapter(context));

                await next.Send(context);
            }
        }
Ejemplo n.º 42
0
        public void Run(PublishContext publishContext)
        {
            Item scriptItem = Factory.GetDatabase("master").GetItem(publishNotificationScriptID);

            try
            {
                using (ScriptSession scriptSession = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                {
                    scriptSession.SetVariable("publishContext", publishContext);
                    scriptSession.ExecuteScriptPart(scriptItem, true);
                    PowerShellLog.Info($"Job ended: Send Teams Notification");
                }
            }
            catch (Exception ex)
            {
                PowerShellLog.Error($"Error while invoking {scriptItem.Paths.FullPath} script from Send Teams Notification job", ex);
            }
        }
Ejemplo n.º 43
0
        public override void Process(PublishContext context)
        {
            var candidates = new List <PublishingCandidate>();

            ID candidate;

            do
            {
                if (!ManuallyAddedCandidates.TryDequeue(out candidate))
                {
                    break;
                }

                candidates.Add(new PublishingCandidate(candidate, context.PublishOptions));
            } while (candidate != (ID)null);

            context.Queue.Add(candidates);
        }
        /// <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.º 45
0
        public async Task CreateAllByRelease(Guid releaseId, PublishContext context)
        {
            // Delete any existing FastTracks in case of republishing
            await DeleteAllFastTracksByRelease(releaseId);

            var dataBlocks = await _contentDbContext.ReleaseContentBlocks
                             .Include(block => block.ContentBlock)
                             .Where(block => block.ReleaseId == releaseId)
                             .Select(block => block.ContentBlock)
                             .OfType <DataBlock>()
                             .ToListAsync();

            foreach (var dataBlock in dataBlocks)
            {
                // Create one FastTrack per DataBlock
                var fastTrack = await CreateFastTrack(releaseId, dataBlock);
                await Upload(releaseId, fastTrack, context);
            }
        }
Ejemplo n.º 46
0
        public async Task <CachedReleaseViewModel> GetReleaseViewModel(Guid id, PublishContext context)
        {
            var release = _contentDbContext.Releases
                          .Include(r => r.Type)
                          .Include(r => r.Content)
                          .ThenInclude(releaseContentSection => releaseContentSection.ContentSection)
                          .ThenInclude(section => section.Content)
                          .Include(r => r.Publication)
                          .Include(r => r.Updates)
                          .Single(r => r.Id == id);

            var releaseViewModel = _mapper.Map <CachedReleaseViewModel>(release);

            releaseViewModel.DownloadFiles = await GetDownloadFiles(release);

            // If the release isn't live yet set the published date based on what we expect it to be
            releaseViewModel.Published ??= context.Published;

            return(releaseViewModel);
        }
        /// <summary>
        /// Implement the resolver function to control the resolving
        /// </summary>
        /// <param name="item">the item published</param>
        /// <param name="instruction">Resolve Instructiuons</param>
        /// <param name="context">Publish Context</param>
        /// <param name="resolvedItems">Collection of Resolved Items</param>
        public void Resolve(IdentifiableObject item, ResolveInstruction instruction, PublishContext context, Tridion.Collections.ISet<ResolvedItem> resolvedItems)
        {
            // Array of schemas which are supposed to publish independently with out resolved items
            string[] lookupSchemas = { "Schema Title1", "Schema Title2" };

            // If published item is a component and it's type belongs to look up schemas array, start the process
            if (item is Component)
            {
                Component comp1 = (Component)item;
                if (lookupSchemas.Contains(comp1.Schema.Title))
                {
                    // Temp collection of resolved items
                    List<ResolvedItem> tempItems = new List<ResolvedItem>();

                    // Loop through resolved items
                    foreach (var resolvedItem in resolvedItems)
                    {
                        // If the resolved item is the published item
                        // Allow it to be published by adding to temp items collection
                        if (resolvedItem.Item is Component)
                        {
                            Component compResolved = (Component)resolvedItem.Item;
                            if (resolvedItem.Item.Id == item.Id)
                            {
                                tempItems.Add(resolvedItem);
                            }
                        }
                    }

                    // Delete all resolved items
                    resolvedItems.Clear();

                    // Add temp items(needs to be published) to resolvedItems collection
                    foreach (ResolvedItem tempResolvedItem in tempItems)
                    {
                        resolvedItems.Add(tempResolvedItem);
                    }

                }
            }
        }
        //based on an old blog by Alex Shyba
        //http://sitecoreblog.alexshyba.com/get_all_published_items_in_sitecore_6_1_6_2/
        protected virtual void ProcessPublishedItems(PublishContext context)
        {
            ProcessHistoryStorage(context.PublishOptions.TargetDatabase);
            string accessToken = string.Empty;;
            foreach (ID id in cacheQueue)
            {
                Item publishedItem = context.PublishOptions.TargetDatabase.GetItem(id);
                //only work with items that inherit from the AzureCachingInfoTemplate
                if (!publishedItem.InheritsFrom(AzureCDNConstants.AzureCachingInfoTemplateId))
                {
                    continue;
                }
                ReferenceField azureCDNProfileField = publishedItem.Fields["Azure CDN Profile"];
                if(azureCDNProfileField == null || azureCDNProfileField.TargetItem == null) continue;
                Item azureCDNProfile = azureCDNProfileField.TargetItem;
                ReferenceField azureSettingField = azureCDNProfile.Fields["Azure Auth Setting"];
                //If Azure settings field cannot be found, silently ignore
                if(azureSettingField == null || azureSettingField.TargetItem == null) continue;
                if (string.IsNullOrEmpty(accessToken))
                {
                    accessToken = _resourceManager.GetAccessTokenUsingServiceAccount(azureSettingField.TargetItem);
                }
                if (azureCDNProfile.Paths.IsMediaItem)
                {
                    string mediaUrl = StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(azureCDNProfile));
                    urls.Add(mediaUrl);
                }
                else
                {
                    string url = StringUtil.EnsurePrefix('/', LinkManager.GetItemUrl(azureCDNProfile));
                    urls.Add(url);
                }

            }
            Log.Info("*** Total processed: " + cacheQueue.Count, this);

        }
Ejemplo n.º 49
0
 protected virtual bool IsThresholdExceeded(PublishContext context)
 {
     return maxItemsThreshold > 0 && context.Job.Status.Processed > maxItemsThreshold;
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Returns the additional items to be published from the images field
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public List<PublishingCandidate> GetAdditionalPublishingCandidates(PublishContext context)
        {
            List<PublishingCandidate> additionalItems = new List<PublishingCandidate>();

            Item item = context.PublishOptions.RootItem;
            IEnumerable<Item> relatedItems = item.GetRelatedItems();
            foreach (Item relatedItem in relatedItems)
            {
                if (relatedItem.IsNull())
                {
                    continue;
                }

                PublishOptions options = new PublishOptions(context.PublishOptions.SourceDatabase,
                                                                        context.PublishOptions.TargetDatabase,
                                                                        PublishMode.Smart,
                                                                        item.Language, context.PublishOptions.PublishDate);
                PublishingCandidate publishingCandidate = new PublishingCandidate(relatedItem.ID, options);
                additionalItems.Add(publishingCandidate);
            }

            return additionalItems;
        }
Ejemplo n.º 51
0
 protected virtual bool SkipReferrers(PublishItemResult result, PublishContext context)
 {
     return result.ReferredItems.Count == 0;
 }
Ejemplo n.º 52
0
        public void TestDeploymentSettingsTestWithFullServiceSettings()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            ServiceSettings fullSettings = ServiceSettingsTestData.Instance.Data[ServiceSettingsState.Sample1];
            PublishContext deploySettings = new PublishContext(
                fullSettings,
                packagePath,
                configPath,
                label,
                deploymentName,
                rootPath);

            AzureAssert.AreEqualPublishContext(
                fullSettings,
                configPath,
                deploymentName,
                label,
                packagePath,
                "f62b1e05-af8f-4205-8f98-325079adc155",
                deploySettings);
        }
Ejemplo n.º 53
0
        private void PublishMessages(PublishContext[] contexts)
        {
            // Process distribution of all the messages.
            int requeCursor = 0;
            foreach (PublishContext context in contexts)
            {
                lock (context.Registration.Consumers)
                {
                    if (context.Registration.Consumers.Count > 0)
                    {
                        // Distribute message to all subscribed clients.
                        foreach (ClientInfo client in context.Registration.Consumers)
                        {
                            try
                            {
                                client.OperationContext.GetCallbackChannel<IServiceBusServiceCallback>().ProcessMessage(context.Message);
                                Interlocked.Increment(ref client.MessagesConsumed);

                                if (context.Message.Type == MessageType.Queue)
                                    // Queue messages gets delivered to the first client only.
                                    break;
                            }
                            catch
                            {
                                // Disconnect the subscriber if an error is encountered during transmission.
                                try
                                {
                                    if (client.OperationContext.Channel.State == CommunicationState.Opened)
                                        client.OperationContext.Channel.Close();
                                }
                                catch
                                {
                                }
                            }
                        }
                        PublishComplete(context);
                    }
                    else
                    {
                        // No clients are subscribed to the queue or topic.
                        if (context.Message.Type == MessageType.Queue)
                            // Preserve queue messages since their delivery is guaranteed.
                            m_publishQueue.Insert(requeCursor++, context);
                        else
                            // Discard topic messages since their delivery is not guaranteed.
                            PublishComplete(context);
                    }
                }

            }

            // Keep message buffer in check if specified.
            if (m_bufferThreshold > 0 && m_publishQueue.Count > m_bufferThreshold)
            {
                int discardCount = m_publishQueue.Count - m_bufferThreshold;

                m_publishQueue.RemoveRange(0, discardCount);
                Interlocked.Add(ref m_discardedMessages, discardCount);
            }
        }
Ejemplo n.º 54
0
        public void TestDeploymentSettingsTestNullLabelFail()
        {
            string deploymentName = service.ServiceName;

            try
            {
                PublishContext deploySettings = new PublishContext(
                    settings,
                    packagePath,
                    configPath,
                    null,
                    deploymentName,
                    rootPath);
                Assert.Fail("No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(ArgumentException));
                Assert.IsTrue(string.Compare(
                    string.Format(Resources.InvalidOrEmptyArgumentMessage,
                    "serviceName"), ex.Message, true) == 0);
            }
        }
Ejemplo n.º 55
0
        private void PublishComplete(PublishContext context)
        {
            // Save the message for on-demand request of subscribers.
            context.Registration.LatestMessage = context.Message;

            // Update the count for the number of messages processed.
            Interlocked.Increment(ref context.Registration.MessagesProcessed);
        }
Ejemplo n.º 56
0
        public void TestDeploymentSettingsTestDoesNotConfigPathFail()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            string doesNotExistDir = Path.Combine(Directory.GetCurrentDirectory(), "qewindw443298.cscfg");

            try
            {
                PublishContext deploySettings = new PublishContext(
                    settings,
                    packagePath,
                    doesNotExistDir,
                    label,
                    deploymentName,
                    rootPath);
                Assert.Fail("No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(FileNotFoundException));
                Assert.AreEqual<string>(string.Format(Resources.PathDoesNotExistForElement, Resources.ServiceConfiguration, doesNotExistDir), ex.Message);
            }
        }
Ejemplo n.º 57
0
        public void TestDeploymentSettingsTestNullSettingsFail()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;

            try
            {
                PublishContext deploySettings = new PublishContext(
                    null,
                    packagePath,
                    configPath,
                    label,
                    deploymentName,
                    rootPath);
                Assert.Fail("No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(ArgumentException));
                Assert.AreEqual<string>(Resources.InvalidServiceSettingMessage, ex.Message);
            }
        }
        /// <summary>
        /// Returns the additional items to be published from the velir images field
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public List<PublishingCandidate> GetAdditionalPublishingCandidates(PublishContext context)
        {
            List<PublishingCandidate> additionalItems = new List<PublishingCandidate>();

            Item item = context.PublishOptions.RootItem;
            TemplateItem template = item.Template;
            foreach (TemplateFieldItem field in template.Fields)
            {
                //verify not a standard/system field
                if (field.InnerItem.IsNotNull() && field.InnerItem.Paths.FullPath.ToLower().StartsWith("/sitecore/templates/system"))
                {
                    continue;
                }

                //get field value
                string fieldValue = item[field.Name];
                if (string.IsNullOrEmpty(fieldValue))
                {
                    continue;
                }

                //split into guid array
                string[] values = fieldValue.Split('|');
                if (values.Length == 0)
                {
                    continue;
                }

                foreach (string fieldValueItemId in values)
                {
                    if (string.IsNullOrEmpty(fieldValueItemId))
                    {
                        continue;
                    }

                    ID additionalItemId;
                    if (!ID.TryParse(fieldValueItemId, out additionalItemId))
                    {
                        continue;
                    }

                    PublishOptions options = new PublishOptions(context.PublishOptions.SourceDatabase,
                                                                context.PublishOptions.TargetDatabase,
                                                                PublishMode.Smart,
                                                                item.Language, context.PublishOptions.PublishDate);
                    PublishingCandidate publishingCandidate = new PublishingCandidate(additionalItemId, options);
                    additionalItems.Add(publishingCandidate);
                }
            }

            return additionalItems;
        }
        public override void Process(PublishContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            //orginal call to get source items
            List<PublishingCandidate> sourceItems = this.GetSourceItems(context.PublishOptions).ToList();

            //auto publish if enabled, the root item matches the allowable templates
            //verify item is not null and it is a content item
            Item item = context.PublishOptions.RootItem;
            if (item.IsNotNull() && item.Paths.IsContentItem && AutoPublish && AllowableTemplate(item.TemplateID.ToString()))
            {
                List<PublishingCandidate> additionalItems = GetAdditionalPublishingCandidates(context);
                if (additionalItems.Count > 0)
                {
                    try
                    {
                        sourceItems.AddRange(additionalItems);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("FieldSuite - AutoPublishReferenceItems - Error Adding to the Publishing Queue");
                        Logger.Error("FieldSuite - AutoPublishReferenceItems - ItemId:" + item.ID);
                        Logger.Error("FieldSuite - AutoPublishReferenceItems - TemplateId: " + item.TemplateID);
                        Logger.Error("FieldSuite - AutoPublishReferenceItems - Path: " + item.Paths.FullPath);
                        Logger.Error(e.InnerException);
                        Logger.Error(e.Message);
                        return;
                    }
                }
            }

            //add to context
            context.Queue.Add(sourceItems);
        }
Ejemplo n.º 60
0
 public static void AreEqualDeploymentSettings(PublishContext expected, PublishContext actual)
 {
     AreEqualPublishContext(expected.ServiceSettings, expected.ConfigPath, expected.DeploymentName, expected.ServiceName, expected.PackagePath, expected.SubscriptionId, actual);
 }