public void Publish(TransportMessage message, PublishOptions publishOptions)
        {
            if (SubscriptionStorage == null)
            {
                throw new InvalidOperationException("Cannot publish on this endpoint - no subscription storage has been configured.");
            }
                
            var eventTypesToPublish = MessageMetadataRegistry.GetMessageMetadata(publishOptions.EventType.FullName)
                .MessageHierarchy
                .Distinct()
                .ToList();

            var subscribers = SubscriptionStorage.GetSubscriberAddressesForMessage(eventTypesToPublish.Select(t => new MessageType(t))).ToList();

            if (!subscribers.Any())
            {
                PipelineExecutor.CurrentContext.Set("NoSubscribersFoundForMessage",true);
                return;
            }

            PipelineExecutor.CurrentContext.Set("SubscribersForEvent", subscribers);

            foreach (var subscriber in subscribers)
            {
                //this is unicast so we give the message a unique ID
                message.ChangeMessageId(CombGuid.Generate().ToString());

                MessageSender.Send(message, new SendOptions(subscriber)
                {
                    ReplyToAddress = publishOptions.ReplyToAddress,
                    EnforceMessagingBestPractices = publishOptions.EnforceMessagingBestPractices,
                    EnlistInReceiveTransaction = publishOptions.EnlistInReceiveTransaction,
                });
            }
        }
 void Publish(IPublishBrokeredMessages publisher, TransportMessage message, PublishOptions options)
 {
     using (var brokeredMessage = message.ToBrokeredMessage(options, config.Settings, config))
     {
         publisher.Publish(brokeredMessage);
     }
 }
        public void IgnoredBestPractices_Should_Return_True_When_Disabled_Best_Practice_Enforcement()
        {
            var options = new PublishOptions();
            
            options.DoNotEnforceBestPractices();

            Assert.IsTrue(options.IgnoredBestPractices());
        }
        public void GetMessageId_Should_Return_Defined_Id()
        {
            const string expectedMessageID = "expected message id";
            var options = new PublishOptions();
            options.SetMessageId(expectedMessageID);

            Assert.AreEqual(expectedMessageID, options.GetMessageId());
        }
        public void GetHeaders_Should_Return_Collection_With_MessageId_Header_Configured()
        {
            var options = new PublishOptions();

            var result = options.GetHeaders();

            Assert.AreEqual(1, result.Count);
            CollectionAssert.Contains(result.Keys, Headers.MessageId);
        }
        public OutgoingPublishContext(OutgoingLogicalMessage message, PublishOptions options, IBehaviorContext parentContext)
            : base(options.MessageId, new Dictionary<string, string>(options.OutgoingHeaders), parentContext)
        {
            Message = message;
            Guard.AgainstNull(nameof(parentContext), parentContext);
            Guard.AgainstNull(nameof(message), message);
            Guard.AgainstNull(nameof(options), options);

            parentContext.Extensions.Merge(options.Context);
        }
        void PublishMessage(TransportMessage message, PublishOptions publishOptions, dynamic channel)
        {
            var eventType = publishOptions.EventType;

            var properties = channel.CreateBasicProperties();

            KafkaTransportMessageExtensions.FillKafkaProperties(message, publishOptions, properties);

            RoutingTopology.Publish(channel, eventType, message, properties);
        }
        public void Publish(TransportMessage message, PublishOptions options)
        {
            var publisher = topology.GetPublisher(config.LocalAddress);

            if (publisher == null) throw new QueueNotFoundException { Queue = config.LocalAddress };

            if (!config.Settings.Get<bool>("Transactions.Enabled") || Transaction.Current == null)
                Publish(publisher, message, options);
            else
                Transaction.Current.EnlistVolatile(new SendResourceManager(() => Publish(publisher, message, options)), EnlistmentOptions.None);
        }
        public async Task Publish_ShouldContainMessageInPublishedMessages()
        {
            var context = new TestableMessageHandlerContext();
            var messageInstance = new TestMessage();
            var publishOptions = new PublishOptions();

            await context.Publish(messageInstance, publishOptions);

            Assert.AreEqual(1, context.PublishedMessages.Length);
            Assert.AreSame(messageInstance, context.PublishedMessages[0].Message);
            Assert.AreSame(publishOptions, context.PublishedMessages[0].Options);
        }
示例#10
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var random = new Random();
        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Sender");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.SendFailedMessagesTo("error");

        endpointConfiguration.UsePersistence<NHibernatePersistence>();
        endpointConfiguration.EnableOutbox();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            var acceptableInput = new List<char> { 'A', 'B' };

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                var uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                if (acceptableInput.Contains(uppercaseKey))
                {
                    var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                    var message = new OrderSubmitted
                    {
                        OrderId = orderId,
                        Value = random.Next(100)
                    };

                    var options = new PublishOptions();
                    options.SetHeader("TenantId", uppercaseKey.ToString());

                    await endpointInstance.Publish(message, options)
                        .ConfigureAwait(false);
                }
                else
                {
                    Console.WriteLine($"[{uppercaseKey}] is not a valid tenant identifier.");
                }
            }
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
示例#11
0
        public async Task PublishAsync(TransportMessage message, PublishOptions options)
        {
            ServiceBusMessageSender sender;
            if (!this.publisherCache.TryGetValue(options.Topic, out sender))
            {
                sender = await this.factory.CreateMessageSenderAsync(options.Destination())
                    .ConfigureAwait(false);
                this.publisherCache.TryAdd(options.Topic, sender);
            }

            await sender.SendAsync(message.ToBrokeredMessage())
                .ConfigureAwait(false);
        }
示例#12
0
        public void Publish()
        {
            //We need the target database
              Database webDb = Sitecore.Configuration.Factory.GetDatabase("web");
              //We need to know the language to publish. Here we use the context language
              Language language = Sitecore.Context.Language;
              //We set the publish date to now
              DateTime publishTime = DateTime.Now;

              //Now we can create the publish options
              Sitecore.Publishing.PublishOptions options = new PublishOptions(masterDb, webDb, PublishMode.SingleItem, language, publishTime);

              //Activate the publishpipeline
              Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(item.ID, options);
        }
        public static BrokeredMessage ToBrokeredMessage(this TransportMessage message, PublishOptions options, ReadOnlySettings settings, Configure config)
        {
            var brokeredMessage = BrokeredMessageBodyConversion.InjectBody(message.Body);

            SetHeaders(message, options, settings, config, brokeredMessage);

            if (message.TimeToBeReceived < TimeSpan.MaxValue)
            {
                brokeredMessage.TimeToLive = message.TimeToBeReceived;
            }

            GuardMessageSize(brokeredMessage);

            return brokeredMessage;
        }
        public void ShouldShallowCloneHeaders()
        {
            var message = new OutgoingLogicalMessage(typeof(object), new object());
            var options = new PublishOptions();
            options.SetHeader("someHeader", "someValue");

            var testee = new OutgoingPublishContext(message, options, new RootContext(null, null, null));
            testee.Headers["someHeader"] = "updatedValue";
            testee.Headers["anotherHeader"] = "anotherValue";

            Assert.AreEqual("someValue", options.OutgoingHeaders["someHeader"]);
            Assert.IsFalse(options.OutgoingHeaders.ContainsKey("anotherHeader"));
            Assert.AreEqual("updatedValue", testee.Headers["someHeader"]);
            Assert.AreEqual("anotherValue", testee.Headers["anotherHeader"]);
        }
示例#15
0
        public async Task Handle(MyMessage message, IMessageHandlerContext context)
        {
            SendOptions sendOptions = new SendOptions();

            sendOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Send(new SomeOtherMessage(), sendOptions);

            ReplyOptions replyOptions = new ReplyOptions();

            replyOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Reply(new SomeOtherMessage(), replyOptions);

            PublishOptions publishOptions = new PublishOptions();

            publishOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Publish(new SomeOtherMessage(), publishOptions);
        }
示例#16
0
        public void When_publishing_should_clone_headers()
        {
            var publishPipeline   = new FakePipeline <IOutgoingPublishContext>();
            var messageOperations = CreateMessageOperations(publishPipeline: publishPipeline);

            var publishOptions = new PublishOptions();

            publishOptions.SetHeader("header1", "header1 value");
            messageOperations.Publish <MyMessage>(new FakeRootContext(), m => { }, publishOptions);
            publishPipeline.ReceivedContext.Headers.Add("header2", "header2 value");
            publishPipeline.ReceivedContext.Headers["header1"] = "updated header1 value";

            var optionsHeaders = publishOptions.GetHeaders();

            Assert.AreEqual(1, optionsHeaders.Count);
            Assert.AreEqual("header1 value", optionsHeaders["header1"]);
        }
示例#17
0
        Task Publish(IBehaviorContext context, Type messageType, object message, PublishOptions options)
        {
            var messageId = options.UserDefinedMessageId ?? CombGuid.Generate().ToString();
            var headers   = new Dictionary <string, string>(options.OutgoingHeaders)
            {
                [Headers.MessageId] = messageId
            };

            var publishContext = new OutgoingPublishContext(
                new OutgoingLogicalMessage(messageType, message),
                messageId,
                headers,
                options.Context,
                context);

            return(publishPipeline.Invoke(publishContext));
        }
示例#18
0
        public void ShouldShallowCloneHeaders()
        {
            var message = new OutgoingLogicalMessage(typeof(object), new object());
            var options = new PublishOptions();

            options.SetHeader("someHeader", "someValue");

            var testee = new OutgoingPublishContext(message, options, new RootContext(null, null, null));

            testee.Headers["someHeader"]    = "updatedValue";
            testee.Headers["anotherHeader"] = "anotherValue";

            Assert.AreEqual("someValue", options.OutgoingHeaders["someHeader"]);
            Assert.IsFalse(options.OutgoingHeaders.ContainsKey("anotherHeader"));
            Assert.AreEqual("updatedValue", testee.Headers["someHeader"]);
            Assert.AreEqual("anotherValue", testee.Headers["anotherHeader"]);
        }
		public static bool PublishQueuedItems(Item triggerItem, Database[] targets, IProgressStatus progress = null)
		{
			if (ManuallyAddedCandidates.Count == 0) return false;

			foreach (var database in targets)
			{
				if (progress != null) progress.ReportStatus("> Publishing {0} synced item{2} in queue to {1}", MessageType.Debug, ManuallyAddedCandidates.Count, database.Name, ManuallyAddedCandidates.Count == 1 ? string.Empty : "s");

				var publishOptions = new PublishOptions(triggerItem.Database, database, PublishMode.SingleItem, triggerItem.Language, DateTime.UtcNow) { RootItem = triggerItem };

				var result = new Publisher(publishOptions).PublishWithResult();

				if (progress != null) progress.ReportStatus("> Published synced items to {0} (New: {1}, Updated: {2}, Deleted: {3} Skipped: {4})", MessageType.Debug, database.Name, result.Statistics.Created, result.Statistics.Updated, result.Statistics.Deleted, result.Statistics.Skipped);
			}

			return true;
		}
        private void CopyPlan(Item item)
        {
            var eventItem = new Entities.EventItem(item);
            var planRoot  = (Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database).GetItem("{963678A4-869C-48AB-915B-D18C6D2AF357}");

            //TODO: Create more unike path
            var copiedPlanItem = eventItem.EventRoot.EngangementPlanItem.CopyTo(planRoot, item.Name);

            eventItem.PlanId = copiedPlanItem.ID.Guid;

            //Set the workflow state on the plan to deploy.
            // TODO: Move this to a deploy button instead!
            IWorkflow workflow = copiedPlanItem.State.GetWorkflow();

            Item workflowCommandItem = ItemUtil.GetContentItem(Guid.Parse("{4044A9C4-B583-4B57-B5FF-2791CB0351DF}"));

            if (workflow == null)
            {
                copiedPlanItem.Database.DataManager.SetWorkflowInfo(copiedPlanItem,
                                                                    new WorkflowInfo(workflowCommandItem.Parent.Parent.ID.ToString(), workflowCommandItem.Parent.ID.ToString()));

                workflow = copiedPlanItem.State.GetWorkflow();
            }

            WorkflowInfo workflowInfo = copiedPlanItem.Database.DataManager.GetWorkflowInfo(copiedPlanItem);

            if (workflowInfo == null || workflowInfo.StateID != workflowCommandItem.Parent.ID.ToString())
            {
                return;
            }

            WorkflowResult workflowResult = workflow.Execute("{4044A9C4-B583-4B57-B5FF-2791CB0351DF}", copiedPlanItem,
                                                             "Executed from Events save event", false, new object());


            PublishOptions options = new PublishOptions(copiedPlanItem.Database, Database.GetDatabase("web"), PublishMode.Smart, copiedPlanItem.Language, DateTime.Now)
            {
                Deep     = true,
                RootItem = copiedPlanItem
            };

            Publisher p = new Publisher(options);

            p.PublishAsync();
        }
        public async Task Should_use_transaction_in_transport_operations()
        {
            var context = await Scenario.Define <MyContext>()
                          .WithEndpoint <AnEndpoint>(c => c.When(async bus =>
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    SendOptions sendOptions;
                    PublishOptions publishOptions;

                    using (var rolledbackTransaction = connection.BeginTransaction())
                    {
                        sendOptions = new SendOptions();
                        sendOptions.UseCustomSqlTransaction(rolledbackTransaction);
                        await bus.Send(new CommandFromRolledbackTransaction(), sendOptions);

                        publishOptions = new PublishOptions();
                        publishOptions.UseCustomSqlTransaction(rolledbackTransaction);
                        await bus.Publish(new EventFromRollbackedTransaction(), publishOptions);

                        rolledbackTransaction.Rollback();
                    }

                    using (var committedTransaction = connection.BeginTransaction())
                    {
                        sendOptions = new SendOptions();
                        sendOptions.UseCustomSqlTransaction(committedTransaction);
                        await bus.Send(new CommandFromCommittedTransaction(), sendOptions);

                        publishOptions = new PublishOptions();
                        publishOptions.UseCustomSqlTransaction(committedTransaction);
                        await bus.Publish(new EventFromCommittedTransaction(), publishOptions);

                        committedTransaction.Commit();
                    }
                }
            }))
                          .Done(c => c.SendFromCommittedTransactionReceived && c.PublishFromCommittedTransactionReceived)
                          .Run(TimeSpan.FromMinutes(1));

            Assert.IsFalse(context.SendFromRolledbackTransactionReceived);
            Assert.IsFalse(context.PublishFromRolledbackTransactionReceived);
        }
示例#22
0
        public async Task PublishAsync <T>(IEnumerable <T> messages, PublishOptions publishOptions = default,
                                           CancellationToken cancellationToken = default) where T : IMessage
        {
            await Semaphore.WaitAsync(cancellationToken);

            try
            {
                var options = SetupExchange(publishOptions);
                messages.ToList().ForEach(message =>
                {
                    Send(message, options);
                });
            }
            finally
            {
                Semaphore.Release();
            }
        }
示例#23
0
        public async Task Build(PublishOptions options)
        {
            await Task.Run(() =>
            {
                var project =
                    ProjectCollection.GlobalProjectCollection.LoadedProjects.FirstOrDefault(
                        x => x.FullPath.ToLower() == options.ProjectFilePath.ToLower()) ??
                    new Project(options.ProjectFilePath);

                project.SetProperty("Configuration", "Release");
                var success = project.Build(new FileLogger());

                if (!success)
                {
                    throw new Exception("build failed. see msbuild.log for more details");
                }
            });
        }
        public override void Process(ImportEntityPipelineArgs args, BaseLog logger)
        {
            var source = args.Item.Database;
            var target = Factory.GetDatabase("web");

            PublishOptions publishOptions = new PublishOptions(source, target, PublishMode.SingleItem, args.Item.Language, DateTime.Now)
            {
                RootItem            = args.Item,
                Deep                = true,
                PublishRelatedItems = true
            };

            var publisher = new Publisher(publishOptions);

            publisher.PublishAsync();

            Log.Info("DEMO CUSTOMIZATION : Published item " + args.Item.Name + " with id: " + args.Item.ID, this);
        }
        public async Task Handle(ProcessClientOutboxMessageCommandV2 message, IMessageHandlerContext context)
        {
            var clientOutboxMessageId = Guid.Parse(context.MessageId);
            var clientOutboxMessage   = await _clientOutboxStorage.GetAsync(clientOutboxMessageId, context.SynchronizedStorageSession);

            var tasks = clientOutboxMessage.TransportOperations.Select(o =>
            {
                var publishOptions = new PublishOptions();

                publishOptions.SetMessageId(o.MessageId.ToString());

                return(context.Publish(o.Message, publishOptions));
            });

            await Task.WhenAll(tasks);

            await _clientOutboxStorage.SetAsDispatchedAsync(clientOutboxMessage.MessageId, context.SynchronizedStorageSession);
        }
示例#26
0
        private List <ManifestFile> GetManifestFiles(List <ManifestFile> onlineManifestFileEntries,
                                                     PublishOptions options)
        {
            if (onlineManifestFileEntries == null || !onlineManifestFileEntries.Any())
            {
                List <ManifestFile> files = new List <ManifestFile>();
                AddDefaultManifestFileEntry(files, options);
                return(files);
            }

            if (!ContainsDefaultEnty(onlineManifestFileEntries, options))
            {
                AddDefaultManifestFileEntry(onlineManifestFileEntries, options);
                return(onlineManifestFileEntries);
            }

            return(onlineManifestFileEntries);
        }
示例#27
0
        public void TestInvalidBuilderArgs()
        {
            Assert.Throws <ArgumentException>(() => PublishOptions.Builder().
                                              WithMessageId("").
                                              Build());

            Assert.Throws <ArgumentException>(() => PublishOptions.Builder().
                                              WithStream("stream.*").
                                              Build());

            Assert.Throws <ArgumentException>(() => PublishOptions.Builder().
                                              WithStream("stream.>").
                                              Build());

            Assert.Throws <ArgumentException>(() => PublishOptions.Builder().
                                              WithStream("stream.one").
                                              Build());
        }
示例#28
0
            private static PublishOptions GetPublishOptions(InvocationDetails invocationDetails, PublishOptions publishOptions)
            {
                PublishOptions result = publishOptions ?? mDefaultPublishOptions;

                if (result.DiscloseMe == true)
                {
                    PublishOptionsExtended extended = new PublishOptionsExtended(result);
                    result = extended;
                    extended.PublisherId        = (long)invocationDetails.Caller;
                    extended.AuthenticationId   = invocationDetails.CallerAuthenticationId;
                    extended.AuthenticationRole = invocationDetails.CallerAuthenticationRole;
                }

                result.Acknowledge = null;
                result.ExcludeMe   = null;

                return(result);
            }
示例#29
0
        public Task Publish(IFullMessage[] messages)
        {
            var options = new PublishOptions();

            _metrics.Mark("Dispatched Messages", Unit.Message);

            // Todo: publish would only be called for messages on a single stream
            // we can set a routing key somehow for BulkMessage so its routed to the same sharded queue
            var message = new BulkMessage
            {
                Messages = messages
            };

            // Publishing an IMessage normally creates a warning
            options.DoNotEnforceBestPractices();

            return(Bus.Instance.Publish(message, options));
        }
示例#30
0
        public async Task Handle(PlaceOrder message, IMessageHandlerContext context)
        {
            log.Info($"Received PlaceOrder, OrderId = {message.OrderId}");

            var orderPlaced = new OrderPlaced
            {
                OrderId  = message.OrderId,
                ClientId = message.ClientId
            };

            var publishOptions = new PublishOptions();

            publishOptions.SetHeader("insider", GetInsiderProgramValue(message));
            publishOptions.SetHeader("membership", GetMembership(message));

            // -- Echange : amq.topic, Queue : Syeremy-Messages-Events-OrderPlaced -- binding needed.
            await context.Publish(orderPlaced, publishOptions);
        }
示例#31
0
        public void TestMessagePublishWithHeadersAndSubtopics()
        {
            SetLatch();
            SetMessage();
            SetHeaders();

            string subtopic = "foo.bar";

            SubscriptionOptions subscriptionOptions = new SubscriptionOptions();

            subscriptionOptions.Subtopic = subtopic;

            channel = Backendless.Messaging.Subscribe(TEST_CHANNEL);

            channel.AddMessageListener <Message>((resultMessage) =>
            {
                if (resultMessage.MessageId.Equals(messageStatus.MessageId))
                {
                    Assert.AreEqual(message, resultMessage.Data, "Server returned a message with a wrong message data");

                    foreach (var key in PublishTest.headers.Keys)
                    {
                        Assert.IsTrue(resultMessage.Headers.ContainsKey(key),
                                      "Server returned a message with wrong headers");
                        Assert.IsTrue(resultMessage.Headers[key].Equals(PublishTest.headers[key]),
                                      "Server returned a message with wrong headers");
                    }
                }
            });

            PublishOptions publishOptions = new PublishOptions();

            publishOptions.Headers  = headers;
            publishOptions.Subtopic = subtopic;

            messageStatus = Backendless.Messaging.Publish(message, TEST_CHANNEL, publishOptions);

            Assert.IsNotNull(messageStatus.MessageId, "Server didn't set a messageId for the message");
            Assert.IsTrue(messageStatus.Status.Equals(PublishStatusEnum.PUBLISHED),
                          "Message status was not set as published");

            Await();
            CheckResult();
        }
示例#32
0
        public CommandLineParserTests(ITestOutputHelper output)
        {
            _output = output;

            _parser = CommandLineParser.Create(
                new ServiceCollection(),
                startServer: (options, invocationContext) =>
            {
                _startOptions = options;
            },
                demo: (options, console, context, startOptions) =>
            {
                _demoOptions = options;
                return(Task.CompletedTask);
            },
                tryGithub: (options, c) =>
            {
                _tryGitHubOptions = options;
                return(Task.CompletedTask);
            },
                pack: (options, console) =>
            {
                _packOptions = options;
                return(Task.CompletedTask);
            },
                install: (options, console) =>
            {
                _installOptions       = options;
                _installPackageSource = options.AddSource;
                return(Task.CompletedTask);
            },
                verify: (options, console, startupOptions) =>
            {
                _verifyOptions = options;
                return(Task.FromResult(0));
            },
                telemetry: new FakeTelemetry(),
                publish: (options, console, startupOptions) =>
            {
                _publishOptions = options;
                return(Task.FromResult(0));
            },
                firstTimeUseNoticeSentinel: new NopFirstTimeUseNoticeSentinel());
        }
        public void ShouldShallowCloneContext()
        {
            var message = new OutgoingLogicalMessage(typeof(object), new object());
            var options = new PublishOptions();

            options.Context.Set("someKey", "someValue");

            var testee = new OutgoingPublishContext(message, "message-id", options.OutgoingHeaders, options.Context, new FakeRootContext());

            testee.Extensions.Set("someKey", "updatedValue");
            testee.Extensions.Set("anotherKey", "anotherValue");
            options.Context.TryGet("someKey", out string value);
            Assert.AreEqual("someValue", value);
            Assert.IsFalse(options.Context.TryGet("anotherKey", out string _));
            testee.Extensions.TryGet("someKey", out string updatedValue);
            testee.Extensions.TryGet("anotherKey", out string anotherValue2);
            Assert.AreEqual("updatedValue", updatedValue);
            Assert.AreEqual("anotherValue", anotherValue2);
        }
示例#34
0
        /// <summary>
        /// Publish the item
        /// </summary>
        /// <param name="item"></param>
        public static void Publish(this Item item)
        {
            var publishOptions = new PublishOptions(item.Database,
                                                    Database.GetDatabase("web"),
                                                    PublishMode.SingleItem,
                                                    item.Language,
                                                    DateTime.Now); // Create a publisher with the publishoptions

            var publisher = new Publisher(publishOptions);

            // Choose where to publish from
            publisher.Options.RootItem = item;

            // Publish children as well?
            publisher.Options.Deep = true;

            // Do the publish!
            publisher.Publish();
        }
示例#35
0
            public IEnumerable <RemoteObserver> GetRelevantSubscribers(PublishOptions options)
            {
                ImmutableHashSet <RemoteObserver> result = mRemoteObservers;

                result = GetEligibleObservers(result, options);

                bool excludeMe = options.ExcludeMe ?? true;

                PublishOptionsExtended casted = options as PublishOptionsExtended;

                if (excludeMe && casted != null)
                {
                    result = result.Remove(new RemoteObserver(casted.PublisherId));
                }

                result = RemoveExcludedObservers(result, options);

                return(result);
            }
示例#36
0
        static private MessageStatus PublishMessageAsPushNotificationSync(string message)
        {
            var publishOptions = new PublishOptions();

            publishOptions.Headers = new Dictionary <string, string>()
            {
                { "android-content-title", "Notification title for Android" },
                { "android-content-text", "Notification text for Android" },
                { "android-ticker-text", "ticker" },
                { "ios-badge", "bage" },
            };


            //DeliveryOptions deliveryOptions = new DeliveryOptions() {PushPolicy = PushPolicyEnum.ALSO, PushBroadcast = 1};
            DeliveryOptions deliveryOptions = new DeliveryOptions()
            {
                PushPolicy = PushPolicyEnum.ONLY, PushBroadcast = 0
            };
            var deviceId = "7afaed6e-ff92-47e5-ba42-18f91c02fbcb";

            deliveryOptions.PushSinglecast = new List <string>()
            {
                deviceId
            };
            // deliveryOptions.SetPushBroadcast(PushBroadcastMask.ANDROID | PushBroadcastMask.IOS);
            MessageStatus messageStatus = Backendless.Messaging.Publish("Specific Message",
                                                                        message,
                                                                        publishOptions
                                                                        );

            if (messageStatus.ErrorMessage == null)
            {
                Console.WriteLine($"MessageStatus = {messageStatus.Status} Id {messageStatus.MessageId}");
                MessageStatus updatedStatus = Backendless.Messaging.GetMessageStatus(messageStatus.MessageId);

                return(messageStatus);
            }
            else
            {
                Console.WriteLine($"Server reported an error: {messageStatus.ErrorMessage}");
                return(null);
            }
        }
        public override void Execute()
        {
            DacPackage     dacpac         = DacPackage.Load(this.Parameters.PackageFilePath);
            PublishOptions publishOptions = new PublishOptions();

            publishOptions.GenerateDeploymentReport = this.Parameters.GenerateDeploymentReport;
            publishOptions.CancelToken        = this.CancellationToken;
            publishOptions.DeployOptions      = this.GetDefaultDeployOptions();
            publishOptions.DatabaseScriptPath = this.Parameters.ScriptFilePath;
            // master script is only used if the target is Azure SQL db and the script contains all operations that must be done against the master database
            publishOptions.MasterDbScriptPath = Path.Combine(Path.GetDirectoryName(this.Parameters.ScriptFilePath), string.Concat("master_", Path.GetFileName(this.Parameters.ScriptFilePath)));

            PublishResult result = this.DacServices.Script(dacpac, this.Parameters.DatabaseName, publishOptions);

            if (this.Parameters.GenerateDeploymentReport && !string.IsNullOrEmpty(this.Parameters.DeploymentReportFilePath))
            {
                File.WriteAllText(this.Parameters.DeploymentReportFilePath, result.DeploymentReport);
            }
        }
        public void Publish(TransportMessage message, PublishOptions publishOptions)
        {
        
            dynamic channel;

            if (ChannelProvider.TryGetPublishChannel(out channel))
            {
                PublishMessage(message,publishOptions,channel);
            }
            else
            {
                using (var confirmsAwareChannel = ChannelProvider.GetNewPublishChannel())
                {
                    PublishMessage(message, publishOptions, confirmsAwareChannel.Channel);    
                }
                
            }
            
        }
        public TDelegate CreatePositionalDelegate <TDelegate>(IWampTopicProxy proxy, PublishOptions publishOptions)
        {
            // Writes: topicProxy.Publish(publishOptions,
            //                            new object[]
            //                                {
            //                                      (object)arg1,
            //                                      (object)arg2,
            //                                      ...,
            //                                      (object)argn
            //                                });

            Func <ParameterExpression[], Expression> callExpression = parameters =>
                                                                      Expression.Call(Expression.Constant(proxy), mPublishPositionalMethod,
                                                                                      Expression.Constant(publishOptions),
                                                                                      Expression.NewArrayInit(typeof(object),
                                                                                                              parameters.Select(x => Expression.Convert(x, typeof(object)))));

            return(InnerCreateDelegate <TDelegate>(callExpression));
        }
示例#40
0
        private void RunPublishJob(Item item, Database sourceDatabase, Database targetDatabase, PublishMode publishMode, Language language, bool deep)
        {
            var options = new PublishOptions(sourceDatabase, targetDatabase, publishMode, language, DateTime.Now)
            {
                Deep = deep,
                PublishRelatedItems = false,
                RootItem            = item
            };

            try
            {
                var publisher = new Publisher(options);
                publisher.Publish();
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Error publishing.", ex, this);
            }
        }
示例#41
0
        public async Task WhenPublishingMessagesWithCustomHeaders_HeadersCanBeReadOnSubscriberSide()
        {
            const string HeaderKey   = "MyHeader";
            const string HeaderValue = "MyValue";

            var publishOptions = new PublishOptions();

            publishOptions.Headers.Add(HeaderKey, HeaderValue);

            await publisher.Publish(new Event
            {
                Bar = 42
            }, publishOptions);

            context.SecondHandlerCaughtHeaders.Should()
            .Contain(HeaderKey, HeaderValue);
            context.FirstcHandlerCaughtHeaders.Should()
            .Contain(HeaderKey, HeaderValue);
        }
示例#42
0
        public string Publish(string sourceDatabaseName, string[] targetNames = null, string[] languageNames = null)
        {
            using (new SecurityDisabler())
            {
                var sourceDatabase = Factory.GetDatabase(sourceDatabaseName);
                var languages = LanguageManager.GetLanguages(sourceDatabase).AsEnumerable();

                if (languageNames != null && languageNames.Length > 0)
                {
                    languages = languages.Where(l => languageNames.Contains(l.Name));
                }

                var targets = PublishManager.GetPublishingTargets(sourceDatabase).AsEnumerable();
                var targetDatabases = new List<Database>();

                if (targetNames != null && targetNames.Length > 0)
                {
                    targets = targets.Where(t => targetNames.Contains(t.Name));
                }

                foreach (var target in targets)
                {
                    targetDatabases.Add(Factory.GetDatabase(target["Target database"]));
                }

                var publishOptions = new PublishOptions(
                    sourceDatabase,
                    targetDatabases.First(),
                    PublishMode.Smart,
                    languages.First(),
                    DateTime.Now,
                    targetNames.ToList())
                {
                    Deep = true,
                    RootItem = sourceDatabase.Items["/sitecore"]
                };

                var publisher = new Sitecore.Publishing.Publisher(publishOptions, languages);
                var job = publisher.PublishAsync();

                return job.Name;
            }
        }
        public async Task Handle(BookRentalCarCommand message, IMessageHandlerContext context)
        {
            lock (Console.Out)
            {
                if (context is IMessageBrokerContext messageBrokerContext)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Received '{message.GetType().Name}' command from message broker. Message Id: '{messageBrokerContext.BrokeredMessage.MessageId}', Subscription: '{messageBrokerContext.BrokeredMessage.MessageReceiverPath}'");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Received '{message.GetType().Name}' command from local dispatcher");
                }
                Console.WriteLine($"Command Data: {JsonConvert.SerializeObject(message)}");
                Console.ResetColor();
            }

            var carRental     = new Domain.Aggregates.CarRental(); //TODO: just an example - likely more properties would be passed in via ctor
            var reservationId = carRental.Reserve(message.Car.Airport, message.Car.Vendor, message.Car.From, message.Car.Until);
            await _repository.AddAsync(carRental);

            var integrationEvents = _eventMapper.MapAll(carRental.DomainEvents);

            //throw new Exception("without using the outbox, we're in a bad state. aggregate has been saved, integration events will never be published.");

            foreach (var ie in integrationEvents)
            {
                var options = new PublishOptions()
                {
                    MessageId = Guid.NewGuid().ToString()
                };

                await _brokeredMessageDispatcher.Publish(ie, context.GetTransactionContext(), options : options);

                lock (Console.Out)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Dispatched domain event: {JsonConvert.SerializeObject(ie)}");
                    Console.ResetColor();
                }
            }
        }
示例#44
0
        public Task Handle(PlaceOrder message, IMessageHandlerContext context)
        {
            logger.Info($"Received PlaceOrder, OrderId = {message.OrderId}");

            // This is normally where some business logic would occur

            var orderPlaced = new OrderPlaced
            {
                OrderId  = message.OrderId,
                ClientId = message.ClientId
            };

            var publishOptions = new PublishOptions();

            publishOptions.SetHeader("insider", GetInsiderProgramValue(message));
            publishOptions.SetHeader("membership", GetMembership(message));

            return(context.Publish(orderPlaced, publishOptions));
        }
        public Task Should_allow_publishing_commands()
        {
            return(Scenario.Define <ScenarioContext>()
                   .WithEndpoint <Endpoint>(b => b.When((session, c) =>
            {
                var publishOptions = new PublishOptions();
                publishOptions.DoNotEnforceBestPractices();

                return session.Publish(new MyCommand(), publishOptions);
            }))
                   .Done(c => c.EndpointsStarted)
                   // This test is only relevant for message driven transports since we need to use the mappings to
                   // configure the publisher. The code first API would blow up unless we turn off the checks for the entire endpoint.
                   // But if we do that turning off checks per message becomes pointless since they are already off.
                   // We would need a new api to turn off startup checks only for this to be testable across the board.
                   .Repeat(r => r.For <AllTransportsWithMessageDrivenPubSub>())
                   .Should(c => Assert.True(c.EndpointsStarted))
                   .Run());
        }
                public async Task Handle(InitiatingMessage message, IMessageHandlerContext context)
                {
                    //HINT: this scope is never completed
                    using (new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        using (var connection = new SqlConnection(ConnectionString))
                        {
                            connection.Open();

                            var sendOptions = new SendOptions();
                            sendOptions.UseCustomSqlConnection(connection);
                            sendOptions.RouteToThisEndpoint();
                            await context.Send(new FollowUpRolledbackCommand(), sendOptions);

                            var publishOptions = new PublishOptions();
                            publishOptions.UseCustomSqlConnection(connection);
                            await context.Publish(new FollowUpRolledbackEvent(), publishOptions);
                        }
                    }

                    using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        using (var connection = new SqlConnection(ConnectionString))
                        {
                            connection.Open();

                            var sendOptions = new SendOptions();
                            sendOptions.UseCustomSqlConnection(connection);
                            sendOptions.RouteToThisEndpoint();
                            await context.Send(new FollowUpCompletedCommand(), sendOptions);

                            var publishOptions = new PublishOptions();
                            publishOptions.UseCustomSqlConnection(connection);
                            await context.Publish(new FollowUpCompletedEvent(), publishOptions);

                            scenarioContext.InHandlerTransactionEscalatedToDTC = Transaction.Current.TransactionInformation.DistributedIdentifier != Guid.Empty;
                        }

                        scope.Complete();
                    }

                    throw new Exception("This should NOT prevent the InitiatingMessage from failing.");
                }
示例#47
0
        public async Task Handle(MyMessage message, IMessageHandlerContext context)
        {
            var sendOptions = new SendOptions();

            sendOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Send(new SomeOtherMessage(), sendOptions)
            .ConfigureAwait(false);

            var replyOptions = new ReplyOptions();

            replyOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Reply(new SomeOtherMessage(), replyOptions)
            .ConfigureAwait(false);

            var publishOptions = new PublishOptions();

            publishOptions.SetHeader("MyCustomHeader", "My custom value");
            await context.Publish(new SomeOtherMessage(), publishOptions)
            .ConfigureAwait(false);
        }
        public void ShouldShallowCloneContext()
        {
            var message = new OutgoingLogicalMessage(typeof(object), new object());
            var options = new PublishOptions();
            options.Context.Set("someKey", "someValue");

            var testee = new OutgoingPublishContext(message, options, new RootContext(null, null, null));
            testee.Extensions.Set("someKey", "updatedValue");
            testee.Extensions.Set("anotherKey", "anotherValue");

            string value;
            string anotherValue;
            options.Context.TryGet("someKey", out value);
            Assert.AreEqual("someValue", value);
            Assert.IsFalse(options.Context.TryGet("anotherKey", out anotherValue));
            string updatedValue;
            string anotherValue2;
            testee.Extensions.TryGet("someKey", out updatedValue);
            testee.Extensions.TryGet("anotherKey", out anotherValue2);
            Assert.AreEqual("updatedValue", updatedValue);
            Assert.AreEqual("anotherValue", anotherValue2);
        }
 public static List<Item> GetRows(Database sourceDb, Database targetDb, int maximumRows, int startRowIndex, int pageSize)
 {
     List<Item> queuedItems = new List<Item>();
     // TODO: dynamically set language
     DateTime publishDate = DateTime.Now;
     PublishOptions options = new PublishOptions(sourceDb, targetDb, PublishMode.Incremental, Language.Parse("en"), publishDate);
     IEnumerable<PublishingCandidate> candidates = PublishQueue.GetPublishQueue(options);
     foreach (PublishingCandidate candidate in candidates)
     {
         Item item = sourceDb.GetItem(candidate.ItemId);
         if (item != null)
         {
             item = item.Publishing.GetValidVersion(publishDate, true);
             if (item != null && item.Access.CanRead() && item.Access.CanReadLanguage() && item.Access.CanWriteLanguage() && ((Sitecore.Context.IsAdministrator || item.Locking.CanLock()) || item.Locking.HasLock()))
             {
                 queuedItems.Add(item);
             }
         }
     }
     _rowCount = queuedItems.Count;
     return queuedItems.Skip(startRowIndex).Take(pageSize).ToList();
 }
        /// <summary>
        /// Publishes item to all publication databases
        /// </summary>
        /// <param name="item">Sitecore Item to publish</param>
        /// <param name="publishMode">Sitecore publish mode</param>
        public static void PublishItem(Item item, PublishMode publishMode = PublishMode.SingleItem)
        {
            if (masterDB != null && publicationDBs != null && publicationDBs.Count > 0)
            {
                var itemPublishToPublicationDatabasesOptionsArray = new PublishOptions[publicationDBs.Count][];

                for (int i = 0; i < publicationDBs.Count; i++)
                {
                    itemPublishToPublicationDatabasesOptionsArray[i] = new PublishOptions[masterDB.Languages.Length];

                    for (var j = 0; j < masterDB.Languages.Length; j++)
                    {
                        itemPublishToPublicationDatabasesOptionsArray[i][j] = new PublishOptions(masterDB, publicationDBs[i], publishMode, masterDB.Languages[j], DateTime.Now)
                        {
                            Deep = true,
                            CompareRevisions = true,
                            RootItem = item,
                        };
                    }

                    PublishManager.Publish(itemPublishToPublicationDatabasesOptionsArray[i]);
                }
            }
        }
 /// <summary>Publish data to CMS.</summary>
 /// <param name="item">Data item.</param>
 /// <param name="language">Date item language.</param>
 /// <param name="dbMaster">Database source.</param>
 /// <param name="dbWeb">Database target.</param>
 public void PublishData(Sitecore.Data.Items.Item item, Sitecore.Globalization.Language language, Sitecore.Data.Database dbMaster, Sitecore.Data.Database dbWeb)
 {
     // Use CMS security disabler to allow changes.
     using(new SecurityDisabler()) {
     PublishOptions opt = new PublishOptions(dbMaster, dbWeb, PublishMode.SingleItem, language, DateTime.Now);
     opt.RootItem = item;
     opt.Deep = false;
     Publisher pub = new Publisher(opt);
     pub.Publish();
     }
 }
示例#52
0
            public Task PublishAsync(TransportMessage message, PublishOptions options)
            {
                var brokeredMessage = message.ToBrokeredMessage();
                var transportMessage = new TransportMessage(brokeredMessage);

                return this.onMessage(transportMessage);
            }
示例#53
0
 public Task Publish(object message, PublishOptions options = null)
 {
     return this.unit.Publish(message, options);
 }
 private IEnumerable<ID> GetRelatedItemIDs(PublishOptions options)
 {
     IEnumerable<ID> publishQueueItems = GetPublishQueueItems(options);
     return publishQueueItems.SelectMany(GetReferences).ToArray();
 }
 private IEnumerable<ID> GetPublishQueueItems(PublishOptions options)
 {
     if (options.Mode == PublishMode.Incremental)
         return PublishQueue.GetPublishQueue(options).Select(candidate => candidate.ItemId).ToArray();
     return PublishQueue.GetContentBranch(options).Select(candidate => candidate.ItemId).ToArray();
 }
        /// <summary>
        /// Creates a stream of items that are candidates for publishing
        /// </summary>
        protected override ISourceObservable<CandidateValidationContext> CreatePublishSourceStream(DateTime started, PublishOptions options, IPublishCandidateSource publishSourceRepository, IPublishValidator validator, IPublisherOperationService publisherOperationService, CancellationTokenSource errorSource)
        {
            IPublishCandidate result = publishSourceRepository.GetNode(options.ItemId.Value).Result;
            if (result == null)
                throw new ArgumentNullException(string.Format("The publish could not be performed from a start item that doesn't exist : {0}.", (object) options.ItemId.Value));

            IPublishCandidate publishCandidate =    result.ParentId.HasValue ?
                                                    publishSourceRepository.GetNode(result.ParentId.Value).Result :
                                                    result;

            ISourceObservable<CandidateValidationContext> sourceObservable =
                (ISourceObservable<CandidateValidationContext>) new TreeNodeSourceProducer(
                    publishSourceRepository,
                    result,
                    validator,
                    options.Descendants,
                    this._options.SourceTreeReaderBatchSize,
                    errorSource,
                    (ILogger) LoggerFactoryExtensions.CreateLogger<TreeNodeSourceProducer>(this._loggerFactory));

            if (PublishOptionsMetadataExtensions.GetItemBucketsEnabled(options) && publishCandidate.Node.TemplateId == PublishOptionsMetadataExtensions.GetBucketTemplateId(options))
                sourceObservable =
                    (ISourceObservable<CandidateValidationContext>) new BucketNodeSourceProducer(
                        sourceObservable,
                        publishSourceRepository,
                        result,
                        PublishOptionsMetadataExtensions.GetBucketTemplateId(options),
                        errorSource,
                        (ILogger) LoggerFactoryExtensions.CreateLogger<BucketNodeSourceProducer>(this._loggerFactory));

            DeletedNodesSourceProducer dnsp = new DeletedNodesSourceProducer(
                sourceObservable,
                started,
                options.Languages,
                options.Targets,
                (IEnumerable<string>)new string[1] { PublishOptionsMetadataExtensions.GetPublishType(options) },
                publisherOperationService,
                this._options.UnpublishedOperationsLoadingBatchSize,
                errorSource,
                (ILogger)LoggerFactoryExtensions.CreateLogger<UnpublishedNodeSourceProducer>(this._loggerFactory),
                (Predicate<PublisherOperation>)(op => Enumerable.Contains<Guid>((IEnumerable<Guid>)op.Path.Ancestors, options.ItemId.Value)));

            return (ISourceObservable<CandidateValidationContext>)dnsp;
        }
        public static void PublishItem(Item item, Database database)
        {
            PublishOptions publishOptions = new PublishOptions
            (
                item.Database,
                database,
                Sitecore.Publishing.PublishMode.SingleItem,
                item.Language,
                DateTime.Now
            );

            Publisher publisher = new Publisher(publishOptions);
            publisher.Options.RootItem = item;
            publisher.Publish();
        }
 // Methods
 private IEnumerable<PublishingCandidate> GetSourceItems(PublishOptions options)
 {
     if (options.Mode == PublishMode.Incremental)
     {
         return PublishQueue.GetPublishQueue(options);
     }
     return PublishQueue.GetContentBranch(options);
 }
        /// <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;
        }
示例#60
0
        private void PublishToTarget(Item item, Database source, Database target)
        {
            if (PublishMode == PublishMode.Unknown)
            {
                PublishMode = PublishMode.Smart;
            }

            var language = item.Language;

            if (ShouldProcess(item.GetProviderPath(),
                string.Format("{3}ublishing language '{0}', version '{1}' to target '{2}'.", language, item.Version,
                    target.Name, Recurse.IsPresent ? "Recursively p" : "P")))
            {
                WriteVerbose(
                    String.Format(
                        "Publishing item '{0}' in language '{1}', version '{2}' to target '{3}'.  (Recurse={4}).",
                        item.Name, language, item.Version, target.Name, Recurse.IsPresent));

                var options = new PublishOptions(source, target, PublishMode, language, DateTime.Now)
                {
                    Deep = Recurse.IsPresent,
                    RootItem = item
                };

                var optionsArgs = new PublishOptions[1];
                optionsArgs[0] = options;

                var handle = PublishManager.Publish(optionsArgs);

                if (handle != null)
                {
                    var publishStatus = PublishManager.GetStatus(handle) ?? new PublishStatus();

                    WriteVerbose(String.Format("Publish Job submitted, current state={0}.",
                        publishStatus.State));
                }
            }
        }