static void Main(string[] args)
        {
            NamespaceManager manager = NamespaceManager.Create(); // Automatycznie bierze informacje z App.config
            //Wolę na początku - wygodniej "zaczynamy" zawsze od zera
            manager.DeleteTopic("obliczenia"); //Kasuje temat i subskrypcje
            manager.DeleteQueue("wynik");

            //Tworzenie Topics - tematu
            TopicDescription td = new TopicDescription("obliczenia");

            //Nie przewidujemy dużego ruchu nie wymagamy partycjonowania
            td.EnablePartitioning = false;
            //Wymagamy wykrywania duplikatów - by klient 2 razy nie wysłał tego samego polecenia
            td.RequiresDuplicateDetection = true;
            //Nie pozwalamy na tematy tylko w pamięci; chcemy żeby klient był pewien że wysłał wiadomość = wiadomość zostanie przetworzona
            td.EnableExpress = false;
            manager.CreateTopic(td); //Tworzenie tematu

            //Suma i średnia będzie wyliczana gdy opowiednia własciwość zostanie zdefiniowana
            manager.CreateSubscription("obliczenia", "suma", new SqlFilter("suma=1"));
            manager.CreateSubscription("obliczenia", "srednia", new SqlFilter("srednia=1"));
            //Ale zawsze będą liczone elementy w komunikacie
            manager.CreateSubscription("obliczenia", "liczba");

            QueueDescription qd = new QueueDescription("wynik");
            qd.RequiresSession = true;
            manager.CreateQueue(qd);
        }
 private async static Task TopicShouldExistAsync(NamespaceManager ns, TopicDescription topicDescription)
 {
     if (!await ns.TopicExistsAsync(topicDescription.Path))
     {
         throw new MessagingEntityNotFoundException("Topic: " + topicDescription.Path);
     }
 }
 public bool Equals(TopicDescription other)
 {
     if (ReferenceEquals(null, other))
         return false;
     if (ReferenceEquals(this, other))
         return true;
     return Equals(other.Path, Path);
 }
        private async static Task TopicCreateAsync(NamespaceManager ns, TopicDescription topicDescription)
        {
            if (!await ns.TopicExistsAsync(topicDescription.Path))
            {
                await ns.CreateTopicAsync(topicDescription);

                ServiceBusEventSource.Log.CreatedTopic(ns.Address.ToString(), topicDescription.Path);
            }
        }
        public async static Task<TopicClient> EnsureTopicAsync(this MessagingFactory factory, TopicDescription topicDescription)
        {
            await new NamespaceManager(factory.Address, factory.GetSettings().TokenProvider)
                .TryCreateEntity(
                    mgr => TopicCreateAsync(mgr, topicDescription),
                    mgr => TopicShouldExistAsync(mgr, topicDescription));

            return factory.CreateTopicClient(topicDescription.Path);
        }
        public static TopicSubscriptionSettings GetTopicSubscription(this IMessageNameFormatter messageNameFormatter, Type messageType)
        {
            bool temporary = IsTemporaryMessageType(messageType);

            var topicDescription = new TopicDescription(messageNameFormatter.GetMessageName(messageType).ToString());

            var binding = new TopicSubscription(topicDescription);

            return binding;
        }
 protected void EnsureTopic(string topicName) {
     if (!namespaceManager.TopicExists(topicName)) {
         topic = namespaceManager.CreateTopic(topicName);
         logger.Log(LogLevel.Info, "EnsureTopic Create {0} ", topicName);
     }
     else {
         topic = namespaceManager.GetTopic(topicName);
         logger.Log(LogLevel.Info, "EnsureTopic Exists {0} ", topicName);
     }
 }
        public EventTopicPublisher(string connectionString, TopicDescription topic, ITimeProvider timeProvider, ILogger logger)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.TopicExists(topic.Path))
                namespaceManager.CreateTopic(topic);

            _client = TopicClient.CreateFromConnectionString(connectionString, topic.Path);
            _timeProvider = timeProvider;
            _logger = logger;
        }
        public static async Task<TopicDescription> CreateTopicSafeAsync(this NamespaceManager namespaceManager, TopicDescription topicDescription)
        {
            bool create = true;
            try
            {
                topicDescription = await namespaceManager.GetTopicAsync(topicDescription.Path);

                create = false;
            }
            catch (MessagingEntityNotFoundException)
            {
            }

            if (create)
            {
                bool created = false;
                try
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Creating topic {0}", topicDescription.Path);

                    topicDescription = await namespaceManager.CreateTopicAsync(topicDescription);

                    created = true;
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                }
                catch (MessagingException mex)
                {
                    if (mex.Message.Contains("(409)"))
                    {
                    }
                    else
                        throw;
                }

                if (!created)
                    topicDescription = await namespaceManager.GetTopicAsync(topicDescription.Path);
            }

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Topic: {0} ({1})", topicDescription.Path,
                    string.Join(", ", new[]
                    {
                        topicDescription.EnableExpress ? "express" : "",
                        topicDescription.RequiresDuplicateDetection ? "dupe detect" : "",
                    }.Where(x => !string.IsNullOrWhiteSpace(x))));
            }

            return topicDescription;
        }
Exemple #10
0
        public void CreateTopicIfDoesntExistSilent(string topicName, long sizeInMb, TimeSpan timeToLive)
        {
            if (!_namespaceManager.TopicExists(topicName))
            {
                var availabilityQd = new TopicDescription(topicName)
                {
                    MaxSizeInMegabytes = sizeInMb,
                    DefaultMessageTimeToLive = timeToLive
                };

                _namespaceManager.CreateTopic(availabilityQd);
            }
        }
        /// <summary>
        /// Run Async
        /// </summary>
        /// <returns>Task</returns>
        public override async Task RunAsync()
        {
            var exists = await this.manager.TopicExistsAsync(name);
            if (!exists)
            {
                var td = new TopicDescription(name)
                {
                    EnableExpress = true,
                };

                await this.manager.CreateTopicAsync(td);
            }
        }
Exemple #12
0
 public TopicClient CreateTopicIfDoesntExist(string topicName, long sizeInMb, TimeSpan timeToLive)
 {
     if (_namespaceManager.TopicExists(topicName) == false)
     {
         var qd = new TopicDescription(topicName)
         {
             MaxSizeInMegabytes = sizeInMb,
             DefaultMessageTimeToLive = timeToLive
         };
         _namespaceManager.CreateTopic(qd);
     }
     return _messagingFactory.CreateTopicClient(topicName);
 }
 /// <summary>
 ///     Creates a topic client, as well as the target topic if it does not already exist.
 /// </summary>
 public static TopicClient CreateTopicClient(
     this ServiceBusSettings settings,
     string topicName,
     Action<TopicDescription> configure = null)
 {
     topicName = topicName.PrefixedIfConfigured(settings);
     var topicDescription = new TopicDescription(topicName);
     if (configure != null)
     {
         configure(topicDescription);
     }
     settings.CreateTopicIfDoesNotAlreadyExist(topicDescription);
     return TopicClient.CreateFromConnectionString(settings.ConnectionString, topicName);
 }
        public static void Init(IEnumerable<string> nodes, ref List<QueueClient> queueClients, out TopicClient topicClient, out QueueClient frontendClient)
        {
            // Node Events Queues
            foreach (var connectionString in nodes.Select(CloudConfigurationManager.GetSetting))
            {
                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    throw new NotImplementedException("Connection String can not be blank");
                }

                var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
                if (!namespaceManager.QueueExists(ServiceBusPathNames.ServiceBusEventQueue))
                {
                    namespaceManager.CreateQueue(ServiceBusPathNames.ServiceBusEventQueue);
                }

                queueClients.Add(QueueClient.CreateFromConnectionString(connectionString, ServiceBusPathNames.ServiceBusEventQueue));
            }

            var workerConn = CloudConfigurationManager.GetSetting(ServiceBusConnectionStrings.WorkerServiceBusConnection);
            var workerNamespace = NamespaceManager.CreateFromConnectionString(workerConn);

            if (string.IsNullOrWhiteSpace(workerConn))
            {
                throw new NotImplementedException("Connection String can not be blank");
            }

            // Update Node Topic
            if (!workerNamespace.TopicExists(ServiceBusPathNames.ServiceBusUpdateTopic))
            {
                var td = new TopicDescription(ServiceBusPathNames.ServiceBusUpdateTopic)
                {
                    DefaultMessageTimeToLive = new TimeSpan(0, 1, 0) // TTL 1 minute
                };

                workerNamespace.CreateTopic(td);
            }

            topicClient = TopicClient.CreateFromConnectionString(workerConn, ServiceBusPathNames.ServiceBusUpdateTopic);

            // Frontend Notification Queue
            var nm = NamespaceManager.CreateFromConnectionString(workerConn);
            if (!nm.QueueExists(ServiceBusPathNames.ServiceBusUpdateQueue))
            {
                nm.CreateQueue(ServiceBusPathNames.ServiceBusUpdateQueue);
            }

            frontendClient = QueueClient.CreateFromConnectionString(workerConn, ServiceBusPathNames.ServiceBusUpdateQueue);
        }
        public void CreateTopc()
        {
            var topicDesc = new TopicDescription(TopicName)
                {
                    MaxSizeInMegabytes = 5120,
                    DefaultMessageTimeToLive = new TimeSpan(0, 20, 0)
                };

            var namespaceManager = NamespaceManager.CreateFromConnectionString(ConnectionString);

            if (!namespaceManager.TopicExists(TopicName))
            {
                namespaceManager.CreateTopic(topicDesc);
            }
        }
        AzureServiceBusEndpointAddress([NotNull] Data data,
            AddressType addressType)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            _data = data;

            _tp = TokenProvider.CreateSharedSecretTokenProvider(_data.UsernameIssuer,
                _data.PasswordSharedSecret);

            Uri sbUri = ServiceBusEnvironment.CreateServiceUri("sb", _data.Namespace, string.Empty);

            var mfs = new MessagingFactorySettings
                {
                    TokenProvider = _tp,
                    NetMessagingTransportSettings =
                        {
                            // todo: configuration setting
                            BatchFlushInterval = 50.Milliseconds()
                        },
                    OperationTimeout = 3.Seconds()
                };
            _mff = () => MessagingFactory.Create(sbUri, mfs);

            _nm = new NamespaceManager(sbUri, _tp);

            string suffix = "";
            if (addressType == AddressType.Queue)
                _queueDescription = new QueueDescriptionImpl(data.QueueOrTopicName);
            else
            {
                _topicDescription = new TopicDescriptionImpl(data.QueueOrTopicName);
                suffix = "?topic=true";
            }

            _rebuiltUri = new Uri(string.Format("azure-sb://{0}:{1}@{2}/{3}{4}",
                data.UsernameIssuer,
                data.PasswordSharedSecret,
                data.Namespace,
                data.QueueOrTopicName,
                suffix));

            _friendlyUri = new Uri(string.Format("azure-sb://{0}/{1}{2}",
                data.Namespace,
                data.QueueOrTopicName,
                suffix));
        }
        public void CreateTopic()
        {
            var topic = new TopicDescription(_topicName);

            AuthorizationRule user1Rule = ServiceBusHelper.CreateAccessRule(TestUsers.User1.UserName, new List<AccessRights> { AccessRights.Listen, AccessRights.Send });
            topic.Authorization.Add(user1Rule);

            AuthorizationRule user2Rule = ServiceBusHelper.CreateAccessRule(TestUsers.User2.UserName, new List<AccessRights> { AccessRights.Listen });
            topic.Authorization.Add(user2Rule);

            AuthorizationRule user3Rule = ServiceBusHelper.CreateAccessRule(TestUsers.User3.UserName, new List<AccessRights> { AccessRights.Send });
            topic.Authorization.Add(user3Rule);

            NamespaceManager nsManager = ServiceBusHelper.GetNamespaceManager();
            nsManager.CreateTopic(topic);
        }
Exemple #18
0
        public Bus() {
            connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            // Configure Topic Settings
            var td = new TopicDescription(topicName);
            td.MaxSizeInMegabytes = 5120;
            td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);

            if (!namespaceManager.TopicExists(topicName)) {
                namespaceManager.CreateTopic(topicName);
            }

            factory = MessagingFactory.CreateFromConnectionString(connectionString);
            sender = factory.CreateMessageSender(topicName);
        }
        public AzureReceiverHelper(TopicDescription topic, IServiceBusConfigurationFactory configurationFactory, IBusConfiguration config, IServiceBusSerializer serializer, RetryPolicy verifyRetryPolicy, RetryPolicy retryPolicy, ServiceBusEnpointData endpoint) {
            Guard.ArgumentNotNull(topic, "topic");
            Guard.ArgumentNotNull(configurationFactory, "configurationFactory");
            Guard.ArgumentNotNull(config, "config");
            Guard.ArgumentNotNull(serializer, "serializer");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");
            Guard.ArgumentNotNull(endpoint, "endpoint");
            this.topic = topic;
            this.configurationFactory = configurationFactory;
            this.config = config;
            this.serializer = serializer;
            this.verifyRetryPolicy = verifyRetryPolicy;
            this.retryPolicy = retryPolicy;
            this.endpoint = endpoint;

            Configure(endpoint);
        }
        public CoAppRepositoryDaemonMain() {
            connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

            // Configure Topic Settings
            var td1 = new TopicDescription(regenSiteTopic) {
                MaxSizeInMegabytes = 5120,
                DefaultMessageTimeToLive = new TimeSpan(0, 1, 0)
            };

            if (!namespaceManager.TopicExists(regenSiteTopic)) {
                namespaceManager.CreateTopic(regenSiteTopic);
            }

            factory = MessagingFactory.CreateFromConnectionString(connectionString);
            _running = true;
        }
        private static void ensureTopicExists(string connectionString, string serviceBusTopic)
        {
            lock (createLock)
            {
                var nsMgr = NamespaceManager.CreateFromConnectionString(connectionString);
                if (nsMgr.TopicExists(serviceBusTopic))
                    return;

                var definition = new TopicDescription(serviceBusTopic)
                                     {
                                         MaxSizeInMegabytes = 1024,
                                         DefaultMessageTimeToLive = TimeSpan.FromDays(365)
                                     };

                nsMgr.CreateTopic(definition);
            }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // Configure Topic Settings.
            TopicDescription td = new TopicDescription("TestTopic2");
            td.MaxSizeInMegabytes = 5120;
            td.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);

            string connectionString = new Properties.Settings().ConnectionString;

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            if (!namespaceManager.TopicExists("TestTopic2"))
            {
                namespaceManager.CreateTopic(td);
            }
        }
        public AzureServiceBusMessageQueue(string connectionString, string inputQueue)
        {
            try
            {
                log.Info("Initializing Azure Service Bus transport with logical input queue '{0}'", inputQueue);

                namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);

                InputQueue = inputQueue;

                log.Info("Ensuring that topic '{0}' exists", TopicName);
                if (!namespaceManager.TopicExists(TopicName))
                {
                    try
                    {
                        namespaceManager.CreateTopic(TopicName);
                    }
                    catch
                    {
                        // just assume the call failed because the topic already exists - if GetTopic below
                        // fails, then something must be wrong, and then we just want to fail immediately
                    }
                }

                topicDescription = namespaceManager.GetTopic(TopicName);

                log.Info("Creating topic client");
                topicClient = TopicClient.CreateFromConnectionString(connectionString, topicDescription.Path);

                // if we're in one-way mode, just quit here
                if (inputQueue == null) return;

                GetOrCreateSubscription(InputQueue);

                log.Info("Creating subscription client");
                subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, TopicName, InputQueue, ReceiveMode.PeekLock);
            }
            catch (Exception e)
            {
                throw new ApplicationException(
                    string.Format(
                        "An error occurred while initializing Azure Service Bus with logical input queue '{0}'",
                        inputQueue), e);
            }
        }
        public static SubscriptionDescription GetOrCreateSubscription(this NamespaceManager namespaceManager, TopicDescription topicDescription,
                                                                      string name)
        {
            if (!namespaceManager.SubscriptionExists(topicDescription.Path, name))
            {
                try
                {
                    var filter = new SqlFilter(string.Format("LogicalDestinationQueue = '{0}'", name));
                    var subscription = namespaceManager.CreateSubscription(topicDescription.Path, name, filter);
                    return subscription;
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                }
            }

            return namespaceManager.GetSubscription(topicDescription.Path, name);
        }
        public static async Task CreateTopicIfNotExists(this NamespaceManager namespaceManager, ILogger logger, string topicIdentifier)
        {
            if (await namespaceManager.TopicExistsAsync(topicIdentifier))
                return;

            try
            {
                logger.Debug("Creating topic:{0}", topicIdentifier);

                var topicDescription = new TopicDescription(topicIdentifier);
                await namespaceManager.CreateTopicAsync(topicDescription);
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // the topic was created while we were trying to create it.
                logger.Warn("A topic with the name {0} already exists", topicIdentifier);
            }
        }
        public static TopicDescription GetTopicDescription(this Uri address)
        {
            if (string.Compare("sb", address.Scheme, StringComparison.OrdinalIgnoreCase) != 0)
                throw new ArgumentException("The invalid scheme was specified: " + address.Scheme);

            var topicPath = address.AbsolutePath.Trim('/');

            var topicDescription = new TopicDescription(topicPath)
            {
                EnableBatchedOperations = true,
                DefaultMessageTimeToLive = TimeSpan.FromDays(365)
            };

            topicDescription.DefaultMessageTimeToLive = address.GetValueFromQueryString("ttl", topicDescription.DefaultMessageTimeToLive);
            topicDescription.EnableExpress = address.GetValueFromQueryString("express", topicDescription.EnableExpress);

            return topicDescription;
        }
 public TopicDefinition(string topicName, TopicDescription topicDescription)
 {
     TopicName = topicName;
     //LockDuration = topicDescription.LockDuration;
     MaxSizeInMegabytes = topicDescription.MaxSizeInMegabytes;
     RequiresDuplicateDetection = topicDescription.RequiresDuplicateDetection;
     DefaultMessageTimeToLive = topicDescription.DefaultMessageTimeToLive;
     //DeadLetteringOnMessageExpiration = topicDescription.EnableDeadLetteringOnMessageExpiration;
     DuplicateDetectionHistoryTimeWindow = topicDescription.DuplicateDetectionHistoryTimeWindow;
     /*
     MaxDeliveryCount =
         (topicDescription.MaxDeliveryCount < 0 || topicDescription.MaxDeliveryCount > UInt16.MaxValue) ?
         UInt16.MaxValue :
         Convert.ToUInt16(topicDescription.MaxDeliveryCount);
     */
     EnableBatchedOperations = topicDescription.EnableBatchedOperations;
     EnableFilteringMessagesBeforePublishing = topicDescription.EnableFilteringMessagesBeforePublishing;
     //SupportOrdering = topicDescription.SupportOrdering;
 }
        public void OnSubscriptionAdded(SubscriptionAdded message)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            Type messageType = Type.GetType(message.MessageName);
            if (messageType == null)
            {
                _log.InfoFormat("Unknown message type '{0}', unable to add subscription", message.MessageName);
                return;
            }

            MessageName messageName = _formatter.GetMessageName(messageType);
            var topicDescription = new TopicDescription(messageName.ToString());

            _inboundTransport.AddTopicSubscriber(topicDescription);

            _bindings[message.SubscriptionId] = topicDescription;
        }
        protected void EnsureTopic(string topicName, bool enablePartitioning) {
            Guard.ArgumentNotNull(topicName, "topicName");
            bool createNew = false;

            try {
                logger.Info("EnsureTopic Try {0} ", topicName);
                // First, let's see if a topic with the specified name already exists.
                defaultTopic = verifyRetryPolicy.ExecuteAction<TopicDescription>(() => {
                    return configurationFactory.NamespaceManager.GetTopic(topicName);
                });

                createNew = (defaultTopic == null);
            }
            catch (MessagingEntityNotFoundException) {
                logger.Info("EnsureTopic Does Not Exist {0} ", topicName);
                // Looks like the topic does not exist. We should create a new one.
                createNew = true;
            }

            if (!createNew && defaultTopic != null && !defaultTopic.EnablePartitioning && enablePartitioning) {
                throw new Exception("EnablePartitioning may not be changed on an existing Topic.");
            }

            // If a topic with the specified name doesn't exist, it will be auto-created.
            if (createNew) {
                try {
                    logger.Info("EnsureTopic CreateTopic {0} ", topicName);
                    var newTopic = new TopicDescription(topicName) { EnablePartitioning = enablePartitioning };

                    defaultTopic = retryPolicy.ExecuteAction<TopicDescription>(() => {
                        return configurationFactory.NamespaceManager.CreateTopic(newTopic);
                    });
                }
                catch (MessagingEntityAlreadyExistsException) {
                    logger.Info("EnsureTopic GetTopic {0} ", topicName);
                    // A topic under the same name was already created by someone else, perhaps by another instance. Let's just use it.
                    defaultTopic = retryPolicy.ExecuteAction<TopicDescription>(() => {
                        return configurationFactory.NamespaceManager.GetTopic(topicName);
                    });
                }
            }
        }
Exemple #30
0
        protected void EnsureTopic(string topicName)
        {
            Guard.ArgumentNotNull(topicName, "topicName");
            bool createNew = false;

            try
            {
                // First, let's see if a topic with the specified name already exists.
                topic = verifyRetryPolicy.ExecuteAction<TopicDescription>(() =>
                {
                    return configurationFactory.NamespaceManager.GetTopic(topicName);
                });

                createNew = (topic == null);
            }
            catch (MessagingEntityNotFoundException)
            {
                // Looks like the topic does not exist. We should create a new one.
                createNew = true;
            }

            // If a topic with the specified name doesn't exist, it will be auto-created.
            if (createNew)
            {
                try
                {
                    var newTopic = new TopicDescription(topicName);
                    topic = retryPolicy.ExecuteAction<TopicDescription>(() =>
                    {
                        return configurationFactory.NamespaceManager.CreateTopic(newTopic);
                    });
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                    // A topic under the same name was already created by someone else, perhaps by another instance. Let's just use it.
                    topic = retryPolicy.ExecuteAction<TopicDescription>(() =>
                    {
                        return configurationFactory.NamespaceManager.GetTopic(topicName);
                    });
                }
            }
        }
Exemple #31
0
 public TopicStat(TopicDescription topic, double score)
 {
     this.Topic = topic;
     this.Score = score;
 }
 public TopicSendSettings(TopicDescription description)
 {
     _description = description;
 }
 void OverrideImmutableMembers(TopicDescription existingDescription, TopicDescription newDescription)
 {
     newDescription.RequiresDuplicateDetection = existingDescription.RequiresDuplicateDetection;
     newDescription.EnablePartitioning         = existingDescription.EnablePartitioning;
 }
Exemple #34
0
        private TopicDescription CreateTopicDescription()
        {
            var td = new TopicDescription(_options.Topic);

            if (_options.TopicAutoDeleteOnIdle.HasValue)
            {
                td.AutoDeleteOnIdle = _options.TopicAutoDeleteOnIdle.Value;
            }

            if (_options.TopicDefaultMessageTimeToLive.HasValue)
            {
                td.DefaultMessageTimeToLive = _options.TopicDefaultMessageTimeToLive.Value;
            }

            if (_options.TopicMaxSizeInMegabytes.HasValue)
            {
                td.MaxSizeInMegabytes = _options.TopicMaxSizeInMegabytes.Value;
            }

            if (_options.TopicRequiresDuplicateDetection.HasValue)
            {
                td.RequiresDuplicateDetection = _options.TopicRequiresDuplicateDetection.Value;
            }

            if (_options.TopicDuplicateDetectionHistoryTimeWindow.HasValue)
            {
                td.DuplicateDetectionHistoryTimeWindow = _options.TopicDuplicateDetectionHistoryTimeWindow.Value;
            }

            if (_options.TopicEnableBatchedOperations.HasValue)
            {
                td.EnableBatchedOperations = _options.TopicEnableBatchedOperations.Value;
            }

            if (_options.TopicEnableFilteringMessagesBeforePublishing.HasValue)
            {
                td.EnableFilteringMessagesBeforePublishing = _options.TopicEnableFilteringMessagesBeforePublishing.Value;
            }

            if (_options.TopicIsAnonymousAccessible.HasValue)
            {
                td.IsAnonymousAccessible = _options.TopicIsAnonymousAccessible.Value;
            }

            if (_options.TopicStatus.HasValue)
            {
                td.Status = _options.TopicStatus.Value;
            }

            if (_options.TopicSupportOrdering.HasValue)
            {
                td.SupportOrdering = _options.TopicSupportOrdering.Value;
            }

            if (_options.TopicEnablePartitioning.HasValue)
            {
                td.EnablePartitioning = _options.TopicEnablePartitioning.Value;
            }

            if (_options.TopicEnableExpress.HasValue)
            {
                td.EnableExpress = _options.TopicEnableExpress.Value;
            }

            if (!String.IsNullOrEmpty(_options.TopicUserMetadata))
            {
                td.UserMetadata = _options.TopicUserMetadata;
            }

            return(td);
        }
 public Task <TopicDescription> CreateTopicAsync(TopicDescription topicDescription)
 {
     return(RunOperation(() => _managementClient.CreateTopicAsync(topicDescription)));
 }
Exemple #36
0
        /// <summary>
        /// Updates shared access signature authorization for the service bus entity. This authorization works on
        /// public Windows Azure environments and Windows Azure Pack on prim as well.
        /// </summary>
        /// <param name="namespaceName">The service bus namespace name</param>
        /// <param name="entityName">The fully qualified service bus entity name</param>
        /// <param name="entityType">The service bus entity type (e.g. Queue)</param>
        /// <param name="ruleName">The SAS authorization rule name</param>
        /// <param name="primaryKey">The SAS primary key. It'll be generated if empty</param>
        /// <param name="secondaryKey">The SAS secondary key</param>
        /// <param name="permissions">Set of permissions given to the rule</param>
        /// <returns>The created Shared Access Signature authorization rule</returns>
        public ExtendedAuthorizationRule UpdateSharedAccessAuthorization(
            string namespaceName,
            string entityName,
            ServiceBusEntityType entityType,
            string ruleName,
            string primaryKey,
            string secondaryKey,
            params AccessRights[] permissions)
        {
            bool removed = false;
            ExtendedAuthorizationRule rule = GetAuthorizationRule(namespaceName, entityName, entityType, ruleName);

            if (null == rule)
            {
                throw new ArgumentException(Resources.ServiceBusAuthorizationRuleNotFound);
            }

            SharedAccessAuthorizationRule oldRule = (SharedAccessAuthorizationRule)rule.Rule;

            SharedAccessAuthorizationRule newRule = new SharedAccessAuthorizationRule(
                ruleName,
                string.IsNullOrEmpty(primaryKey) ? SharedAccessAuthorizationRule.GenerateRandomKey() : primaryKey,
                secondaryKey,
                permissions ?? oldRule.Rights);

            // Create namespace manager
            NamespaceManager namespaceManager = CreateNamespaceManager(namespaceName);

            // Add the SAS rule and update the entity
            switch (entityType)
            {
            case ServiceBusEntityType.Queue:
                QueueDescription queue = namespaceManager.GetQueue(entityName);
                removed = queue.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                queue.Authorization.Add(newRule);
                namespaceManager.UpdateQueue(queue);
                break;

            case ServiceBusEntityType.Topic:
                TopicDescription topic = namespaceManager.GetTopic(entityName);
                removed = topic.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                topic.Authorization.Add(newRule);
                namespaceManager.UpdateTopic(topic);
                break;

            case ServiceBusEntityType.Relay:
                RelayDescription relay = namespaceManager.GetRelayAsync(entityName).Result;
                removed = relay.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                relay.Authorization.Add(newRule);
                namespaceManager.UpdateRelayAsync(relay).Wait();
                break;

            case ServiceBusEntityType.NotificationHub:
                NotificationHubDescription notificationHub = namespaceManager.GetNotificationHub(entityName);
                removed = notificationHub.Authorization.Remove(oldRule);
                Debug.Assert(removed);
                notificationHub.Authorization.Add(newRule);
                namespaceManager.UpdateNotificationHub(notificationHub);
                break;

            default:
                throw new Exception(string.Format(Resources.ServiceBusEntityTypeNotFound, entityType.ToString()));
            }

            return(CreateExtendedAuthorizationRule(newRule, namespaceName, entityName, entityType));
        }
Exemple #37
0
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, FormTypeEnum formType, TopicDescription topicDescription, List <SubscriptionDescription> subscriptionList)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm        = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testTopicControl = new TestTopicControl(mainForm, WriteToLog, StopLog, StartLog, new ServiceBusHelper(WriteToLog, serviceBusHelper), topicDescription, subscriptionList)
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size     = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor   = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };


                if (formType == FormTypeEnum.Send)
                {
                    testTopicControl.mainTabControl.TabPages.RemoveAt(2);
                    testTopicControl.receiverEnabledCheckBox.Checked = false;
                    testTopicControl.senderEnabledCheckBox.Checked   = true;
                    testTopicControl.senderEnabledCheckBox.Visible   = false;
                    testTopicControl.grouperMessage.Location         = new Point(testTopicControl.grouperMessage.Location.X, 8);
                    testTopicControl.grouperMessage.Size             = new Size(testTopicControl.grouperMessage.Size.Width,
                                                                                testTopicControl.grouperMessage.Size.Height + 16);
                    testTopicControl.grouperSender.Location = new Point(testTopicControl.grouperSender.Location.X, 8);
                    testTopicControl.grouperSender.Size     = new Size(testTopicControl.grouperSender.Size.Width,
                                                                       testTopicControl.grouperSender.Size.Height + 16);
                    Text = string.Format(SendMessagesFormat, topicDescription.Path);
                }
                else
                {
                    Text             = string.Format(TestTopicFormat, topicDescription.Path);
                    logTraceListener = new LogTraceListener(WriteToLog);
                    Trace.Listeners.Add(logTraceListener);
                }

                testTopicControl.btnCancel.Text   = CloseLabel;
                testTopicControl.btnCancel.Click -= testTopicControl.btnCancel_Click;
                testTopicControl.btnCancel.Click += BtnCancelOnClick;
                testTopicControl.Focus();

                panelMain.HeaderText = string.Format(HeaderTextTestTopicFormat, topicDescription.Path);
                panelMain.Controls.Add(testTopicControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
 internal IEnumerable <SubscriptionDescription> GetSubscriptions(TopicDescription topic)
 {
     return(_namespaceManager.GetSubscriptions(topic.Path));
 }
 internal TopicDescription UpdateTopic(TopicDescription topic)
 {
     return(_namespaceManager.UpdateTopic(topic));
 }
 public void DeleteUser(TopicDescription topic, QueueUser user)
 {
     topic.Authorization.Remove(topic.Authorization.Single(a => a.ClaimValue.StartsWith(user.UserName)));
     UpdateTopic(topic);
 }
Exemple #41
0
 public HandleTopicControl(MainForm mainForm, WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, TopicDescription topic, string path)
 {
     this.mainForm         = mainForm;
     this.writeToLog       = writeToLog;
     this.serviceBusHelper = serviceBusHelper;
     this.topic            = topic;
     this.path             = path;
     InitializeComponent();
     InitializeData();
 }
Exemple #42
0
        public async Task <TopicDescription> CreateTopic(TopicDescription topicDescription)
        {
            var create = true;

            try
            {
                if (await RootNamespaceManager.TopicExistsAsync(topicDescription.Path).ConfigureAwait(false))
                {
                    topicDescription = await RootNamespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false);

                    create = false;
                }
            }
            catch (MessagingEntityNotFoundException)
            {
            }

            if (create)
            {
                var created = false;
                try
                {
                    if (_log.IsDebugEnabled)
                    {
                        _log.DebugFormat("Creating topic {0}", topicDescription.Path);
                    }

                    topicDescription = await RootNamespaceManager.CreateTopicAsync(topicDescription).ConfigureAwait(false);

                    created = true;
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                }
                catch (MessagingException mex)
                {
                    if (mex.Message.Contains("(409)"))
                    {
                    }
                    else
                    {
                        throw;
                    }
                }

                if (!created)
                {
                    topicDescription = await RootNamespaceManager.GetTopicAsync(topicDescription.Path).ConfigureAwait(false);
                }
            }

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Topic: {0} ({1})", topicDescription.Path,
                                 string.Join(", ", new[]
                {
                    topicDescription.EnableExpress ? "express" : "",
                    topicDescription.RequiresDuplicateDetection ? "dupe detect" : ""
                }.Where(x => !string.IsNullOrWhiteSpace(x))));
            }

            return(topicDescription);
        }
 Task <TopicDescription> NamespaceContext.CreateTopic(TopicDescription topicDescription)
 {
     return(_context.CreateTopic(topicDescription));
 }
        public override string ToString()
        {
            StringBuilder __sb    = new StringBuilder("DDCreateTopicRequest(");
            bool          __first = true;

            if (SessionId != null && __isset.sessionId)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("SessionId: ");
                __sb.Append(SessionId);
            }
            if (AppId != null && __isset.appId)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("AppId: ");
                __sb.Append(AppId);
            }
            if (Id != null && __isset.id)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("Id: ");
                __sb.Append(Id);
            }
            if (Title != null && __isset.title)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("Title: ");
                __sb.Append(Title.ToDebugString());
            }
            if (TopicDescription != null && __isset.topicDescription)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("TopicDescription: ");
                __sb.Append(TopicDescription.ToDebugString());
            }
            if (AvatarUrl != null && __isset.avatarUrl)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("AvatarUrl: ");
                __sb.Append(AvatarUrl);
            }
            if (Permissions != null && __isset.permissions)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("Permissions: ");
                __sb.Append(Permissions.ToDebugString());
            }
            if (Properties != null && __isset.properties)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("Properties: ");
                __sb.Append(Properties.ToDebugString());
            }
            if (__isset.isDiscoverable)
            {
                if (!__first)
                {
                    __sb.Append(", ");
                }
                __first = false;
                __sb.Append("IsDiscoverable: ");
                __sb.Append(IsDiscoverable);
            }
            __sb.Append(")");
            return(__sb.ToString());
        }
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, FormTypeEnum formTypeType, TopicDescription topicDescription, List <SubscriptionDescription> subscriptionList)
        {
            try
            {
                InitializeComponent();
                this.mainForm        = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testTopicControl = new TestTopicControl(mainForm, WriteToLog, new ServiceBusHelper(WriteToLog, serviceBusHelper), topicDescription, subscriptionList)
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1)
                };


                if (formTypeType == FormTypeEnum.Send)
                {
                    testTopicControl.mainTabControl.TabPages.RemoveAt(2);
                    testTopicControl.receiverEnabledCheckBox.Checked = false;
                    Text = string.Format(SendMessagesFormat, topicDescription.Path);
                }
                else
                {
                    Text             = string.Format(TestTopicFormat, topicDescription.Path);
                    logTraceListener = new LogTraceListener(WriteToLog);
                    Trace.Listeners.Add(logTraceListener);
                }

                testTopicControl.btnCancel.Text   = CloseLabel;
                testTopicControl.btnCancel.Click -= testTopicControl.btnCancel_Click;
                testTopicControl.btnCancel.Click += BtnCancelOnClick;
                testTopicControl.Focus();

                panelMain.HeaderText = string.Format(HeaderTextTestTopicFormat, topicDescription.Path);
                panelMain.Controls.Add(testTopicControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
 internal void RemoveSubscription(TopicDescription topic, string name)
 {
     _namespaceManager.DeleteSubscription(topic.Path, name);
 }
Exemple #47
0
 public Task <TopicDescription> CreateTopic(TopicDescription topicDescription)
 {
     return(_context.CreateTopic(topicDescription));
 }
 /// <summary>
 /// Initializes a new instance of the SubscriptionWrapper class.
 /// </summary>
 /// <param name="subscription">A subscription.</param>
 /// <param name="topic">The topic the subscription belongs to.</param>
 public SubscriptionWrapper2(SubscriptionDescription subscription, TopicDescription topic)
 {
     SubscriptionDescription = subscription;
     TopicDescription        = topic;
 }
Exemple #49
0
 public TopicHandle CreateTopic(TopicDescription topicDescription)
 {
     return(_builder.CreateTopic(topicDescription));
 }
Exemple #50
0
 public Task <TopicDescription> CreateTopic(TopicDescription topicDescription)
 {
     throw new NotImplementedException();
 }
        public static SubscriptionDescription GetOrCreateSubscription(this NamespaceManager namespaceManager, TopicDescription topicDescription,
                                                                      string name)
        {
            if (!namespaceManager.SubscriptionExists(topicDescription.Path, name))
            {
                try
                {
                    var filter       = new SqlFilter(string.Format("LogicalDestinationQueue = '{0}'", name));
                    var subscription = namespaceManager.CreateSubscription(topicDescription.Path, name, filter);
                    return(subscription);
                }
                catch (MessagingEntityAlreadyExistsException)
                {
                }
            }

            return(namespaceManager.GetSubscription(topicDescription.Path, name));
        }
        public async Task <TopicDescription> Create(string topicPath, INamespaceManagerInternal namespaceManager)
        {
            var topicDescription = new TopicDescription(topicPath)
            {
                SupportOrdering                         = topicSettings.SupportOrdering,
                MaxSizeInMegabytes                      = topicSettings.MaxSizeInMegabytes,
                DefaultMessageTimeToLive                = topicSettings.DefaultMessageTimeToLive,
                RequiresDuplicateDetection              = topicSettings.RequiresDuplicateDetection,
                DuplicateDetectionHistoryTimeWindow     = topicSettings.DuplicateDetectionHistoryTimeWindow,
                EnableBatchedOperations                 = topicSettings.EnableBatchedOperations,
                EnablePartitioning                      = topicSettings.EnablePartitioning,
                AutoDeleteOnIdle                        = topicSettings.AutoDeleteOnIdle,
                EnableFilteringMessagesBeforePublishing = topicSettings.EnableFilteringMessagesBeforePublishing
            };

            topicSettings.DescriptionCustomizer(topicDescription);

            try
            {
                if (!await ExistsAsync(topicPath, namespaceManager).ConfigureAwait(false))
                {
                    await namespaceManager.CreateTopic(topicDescription).ConfigureAwait(false);

                    logger.InfoFormat("Topic '{0}' created", topicDescription.Path);
                    await rememberExistence.AddOrUpdate(topicDescription.Path, notFoundTopicPath => TaskEx.CompletedTrue, (updateTopicPath, previousValue) => TaskEx.CompletedTrue).ConfigureAwait(false);
                }
                else
                {
                    logger.InfoFormat("Topic '{0}' already exists, skipping creation", topicDescription.Path);
                    logger.InfoFormat("Checking if topic '{0}' needs to be updated", topicDescription.Path);
                    var existingTopicDescription = await namespaceManager.GetTopic(topicDescription.Path).ConfigureAwait(false);

                    if (MembersAreNotEqual(existingTopicDescription, topicDescription))
                    {
                        OverrideImmutableMembers(existingTopicDescription, topicDescription);
                        logger.InfoFormat("Updating topic '{0}' with new description", topicDescription.Path);
                        await namespaceManager.UpdateTopic(topicDescription).ConfigureAwait(false);
                    }
                }
            }
            catch (MessagingEntityAlreadyExistsException)
            {
                // the topic already exists or another node beat us to it, which is ok
                logger.InfoFormat("Topic '{0}' already exists, another node probably beat us to it", topicDescription.Path);
            }
            catch (TimeoutException)
            {
                logger.InfoFormat("Timeout occurred on topic creation for '{0}' going to validate if it doesn't exist", topicDescription.Path);

                // there is a chance that the timeout occurred, but the topic was still created, check again
                if (!await ExistsAsync(topicDescription.Path, namespaceManager, removeCacheEntry: true).ConfigureAwait(false))
                {
                    throw;
                }

                logger.InfoFormat("Looks like topic '{0}' exists anyway", topicDescription.Path);
            }
            catch (MessagingException ex)
            {
                var loggedMessage = string.Format("{1} {2} occurred on topic creation {0}", topicDescription.Path, ex.IsTransient ? "Transient" : "Non transient", ex.GetType().Name);

                if (!ex.IsTransient)
                {
                    logger.Fatal(loggedMessage, ex);
                    throw;
                }

                logger.Info(loggedMessage, ex);
            }

            return(topicDescription);
        }
 public SubscriptionEndpointSettings(TopicDescription topicDescription, string subscriptionName)
     : this(topicDescription, new SubscriptionConfigurator(topicDescription.Path, subscriptionName))
 {
 }
Exemple #54
0
        private void btnAction_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnAction.Text == DeleteText)
                {
                    var deleteForm = new DeleteForm(topic.Path, TopicEntity.ToLower());
                    if (deleteForm.ShowDialog() == DialogResult.OK)
                    {
                        serviceBusHelper.DeleteTopic(topic);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var topicDescription = new TopicDescription(txtPath.Text);
                    if (!string.IsNullOrEmpty(txtMaxTopicSizeInMegabytes.Text))
                    {
                        long value;
                        if (long.TryParse(txtMaxTopicSizeInMegabytes.Text, out value))
                        {
                            topicDescription.MaxSizeInMegabytes = value;
                        }
                        else
                        {
                            writeToLog(MaxTopicSizeInBytesMustBeANumber);
                            return;
                        }
                    }

                    var days         = 0;
                    var hours        = 0;
                    var minutes      = 0;
                    var seconds      = 0;
                    var milliseconds = 0;

                    if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveDays.Text) ||
                        !string.IsNullOrEmpty(txtDefaultMessageTimeToLiveHours.Text) ||
                        !string.IsNullOrEmpty(txtDefaultMessageTimeToLiveMinutes.Text) ||
                        !string.IsNullOrEmpty(txtDefaultMessageTimeToLiveSeconds.Text) ||
                        !string.IsNullOrEmpty(txtDefaultMessageTimeToLiveMilliseconds.Text))
                    {
                        if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveDays.Text))
                        {
                            if (!int.TryParse(txtDefaultMessageTimeToLiveDays.Text, out days))
                            {
                                writeToLog(DefaultMessageTimeToLiveDaysMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveHours.Text))
                        {
                            if (!int.TryParse(txtDefaultMessageTimeToLiveHours.Text, out hours))
                            {
                                writeToLog(DefaultMessageTimeToLiveHoursMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveMinutes.Text))
                        {
                            if (!int.TryParse(txtDefaultMessageTimeToLiveMinutes.Text, out minutes))
                            {
                                writeToLog(DefaultMessageTimeToLiveMinutesMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveSeconds.Text))
                        {
                            if (!int.TryParse(txtDefaultMessageTimeToLiveSeconds.Text, out seconds))
                            {
                                writeToLog(DefaultMessageTimeToLiveSecondsMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDefaultMessageTimeToLiveMilliseconds.Text))
                        {
                            if (!int.TryParse(txtDefaultMessageTimeToLiveMilliseconds.Text, out milliseconds))
                            {
                                writeToLog(DefaultMessageTimeToLiveMillisecondsMustBeANumber);
                                return;
                            }
                        }
                        topicDescription.DefaultMessageTimeToLive = new TimeSpan(days, hours, minutes, seconds, milliseconds);
                    }

                    days         = 0;
                    hours        = 0;
                    minutes      = 0;
                    seconds      = 0;
                    milliseconds = 0;

                    if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowDays.Text) ||
                        !string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowHours.Text) ||
                        !string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowMinutes.Text) ||
                        !string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowSeconds.Text) ||
                        !string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowMilliseconds.Text))
                    {
                        if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowDays.Text))
                        {
                            if (!int.TryParse(txtDuplicateDetectionHistoryTimeWindowDays.Text, out days))
                            {
                                writeToLog(DuplicateDetectionHistoryTimeWindowDaysMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowHours.Text))
                        {
                            if (!int.TryParse(txtDuplicateDetectionHistoryTimeWindowHours.Text, out hours))
                            {
                                writeToLog(DuplicateDetectionHistoryTimeWindowHoursMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowMinutes.Text))
                        {
                            if (!int.TryParse(txtDuplicateDetectionHistoryTimeWindowMinutes.Text, out minutes))
                            {
                                writeToLog(DuplicateDetectionHistoryTimeWindowMinutesMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowSeconds.Text))
                        {
                            if (!int.TryParse(txtDuplicateDetectionHistoryTimeWindowSeconds.Text, out seconds))
                            {
                                writeToLog(DuplicateDetectionHistoryTimeWindowSecondsMustBeANumber);
                                return;
                            }
                        }
                        if (!string.IsNullOrEmpty(txtDuplicateDetectionHistoryTimeWindowMilliseconds.Text))
                        {
                            if (!int.TryParse(txtDuplicateDetectionHistoryTimeWindowMilliseconds.Text, out milliseconds))
                            {
                                writeToLog(DuplicateDetectionHistoryTimeWindowMillisecondsMustBeANumber);
                                return;
                            }
                        }
                        topicDescription.DuplicateDetectionHistoryTimeWindow = new TimeSpan(days, hours, minutes, seconds, milliseconds);
                    }

                    topicDescription.EnableBatchedOperations    = checkedListBox.GetItemChecked(EnableBatchedOperationsIndex);
                    topicDescription.RequiresDuplicateDetection = checkedListBox.GetItemChecked(RequiresDuplicateDetectionIndex);

                    topic = serviceBusHelper.CreateTopic(topicDescription);
                    InitializeData();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
        public void CreateTopic(TopicDescription topic)
        {
            topic = _namespaceManager.CreateTopic(topic);

            Topics.Add(topic);
        }
Exemple #56
0
 public static int MaxSizeInGigabytes(this TopicDescription topicDescription)
 {
     return((int)(topicDescription.MaxSizeInMegabytes / 1024));
 }
Exemple #57
0
            protected override IEnumerator <AsyncStep> GetAsyncSteps()
            {
                this.owner.namespaceManager = NamespaceManager.CreateFromConnectionString(this.owner.connectionString);

                for (int partitionId = 0; partitionId < this.owner.partitionCount; partitionId++)
                {
                    // Create topic if not exists.
                    string topicPath = this.owner.GetTopicPath(partitionId);

                    bool topicExist = false;

                    yield return(this.CallAsync(
                                     (thisPtr, t, c, s) => thisPtr.owner.namespaceManager.BeginTopicExists(topicPath, c, s),
                                     (thisPtr, r) => topicExist = thisPtr.owner.namespaceManager.EndTopicExists(r),
                                     ExceptionPolicy.Transfer));

                    if (!topicExist)
                    {
                        this.topicDescription = new TopicDescription(topicPath);

                        yield return(this.CallAsync(
                                         (thisPtr, t, c, s) => thisPtr.owner.namespaceManager.BeginCreateTopic(thisPtr.topicDescription, c, s),
                                         (thisPtr, r) => thisPtr.topicDescription = thisPtr.owner.namespaceManager.EndCreateTopic(r),
                                         ExceptionPolicy.Transfer));
                    }

                    for (int nodeId = 0; nodeId < this.owner.nodeCount; nodeId++)
                    {
                        // Create subscriptions if not exist
                        string subscriptionName = GetSubscriptionName(nodeId);

                        bool subscriptionExists = false;

                        yield return(this.CallAsync(
                                         (thisPtr, t, c, s) => thisPtr.owner.namespaceManager.BeginSubscriptionExists(topicPath, subscriptionName, c, s),
                                         (thisPtr, r) => subscriptionExists = thisPtr.owner.namespaceManager.EndSubscriptionExists(r),
                                         ExceptionPolicy.Transfer));

                        if (!subscriptionExists)
                        {
                            SubscriptionDescription subscriptionDescription = new SubscriptionDescription(topicPath, subscriptionName)
                            {
                                RequiresSession = false
                            };

                            yield return(this.CallAsync(
                                             (thisPtr, t, c, s) => thisPtr.owner.namespaceManager.BeginCreateSubscription(subscriptionDescription, c, s),
                                             (thisPtr, r) => thisPtr.owner.namespaceManager.EndCreateSubscription(r),
                                             ExceptionPolicy.Transfer));
                        }
                    }
                }

                for (int partitionId = 0; partitionId < this.owner.partitionCount; partitionId++)
                {
                    this.factory = MessagingFactory.CreateFromConnectionString(this.owner.connectionString);

                    this.owner.factories.Add(partitionId, this.factory);

                    string topicPath              = this.owner.GetTopicPath(partitionId);
                    string subscriptionName       = GetSubscriptionName(this.owner.nodeId);
                    string subscriptionEntityPath = SubscriptionClient.FormatSubscriptionPath(topicPath, subscriptionName);

                    MessageSender sender = null;

                    yield return(this.CallAsync(
                                     (thisPtr, t, c, s) => thisPtr.factory.BeginCreateMessageSender(topicPath, c, s),
                                     (thisPtr, r) => sender = thisPtr.factory.EndCreateMessageSender(r),
                                     ExceptionPolicy.Transfer));

                    this.owner.senders.Add(partitionId, sender);

                    MessageReceiver receiver = null;

                    yield return(this.CallAsync(
                                     (thisPtr, t, c, s) => factory.BeginCreateMessageReceiver(subscriptionEntityPath, ReceiveMode.ReceiveAndDelete, c, s),
                                     (thisPtr, r) => receiver = factory.EndCreateMessageReceiver(r),
                                     ExceptionPolicy.Transfer));

                    var pump = new MessagePump(topicPath, receiver, this.owner.inputQueue, this.owner.semaphore);
                    this.owner.pumps.Add(partitionId, pump);

                    pump.Start();
                }

                this.owner.dispatcher = new MessageDispatcher(this.owner.inputQueue, this.owner.onReceivedAsync);
                this.owner.dispatcher.Start();
            }
 public TopicDescription CreateTopic(TopicDescription description)
 {
     return(namespaceManager.CreateTopic(description));
 }
        public async Task BasicTopicCrudTest()
        {
            var topicName = Guid.NewGuid().ToString("D").Substring(0, 8);
            var client    = new ManagementClient(new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString));

            try
            {
                var td = new TopicDescription(topicName)
                {
                    AutoDeleteOnIdle                    = TimeSpan.FromHours(1),
                    DefaultMessageTimeToLive            = TimeSpan.FromDays(2),
                    DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
                    EnableBatchedOperations             = true,
                    EnablePartitioning                  = false,
                    MaxSizeInMB = 2048,
                    RequiresDuplicateDetection = true,
                    UserMetadata = nameof(BasicTopicCrudTest)
                };

                td.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
                                              "allClaims",
                                              new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));

                var createdT = await client.CreateTopicAsync(td);

                Assert.Equal(td, createdT);

                var getT = await client.GetTopicAsync(td.Path);

                Assert.Equal(td, getT);

                getT.EnableBatchedOperations  = false;
                getT.DefaultMessageTimeToLive = TimeSpan.FromDays(3);

                var updatedT = await client.UpdateTopicAsync(getT);

                Assert.Equal(getT, updatedT);

                var exists = await client.TopicExistsAsync(topicName);

                Assert.True(exists);

                var topics = await client.GetTopicsAsync();

                Assert.True(topics.Count >= 1);
                Assert.Contains(topics, e => e.Path.Equals(topicName, StringComparison.OrdinalIgnoreCase));

                await client.DeleteTopicAsync(updatedT.Path);

                await Assert.ThrowsAsync <MessagingEntityNotFoundException>(
                    async() =>
                {
                    await client.GetTopicAsync(td.Path);
                });

                exists = await client.TopicExistsAsync(topicName);

                Assert.False(exists);
            }
            catch
            {
                await SafeDeleteTopic(client, topicName);

                throw;
            }
            finally
            {
                await client.CloseAsync();
            }
        }
 /// <summary>
 /// Initializes a new instance of the SubscriptionWrapper class.
 /// </summary>
 /// <param name="subscription">A subscription.</param>
 /// <param name="topic">The topic the subscription belongs to.</param>
 /// <param name="filter">The OData filter.</param>
 public SubscriptionWrapper2(SubscriptionDescription subscription, TopicDescription topic, string filter)
 {
     SubscriptionDescription = subscription;
     TopicDescription        = topic;
     Filter = filter;
 }